【发布时间】:2014-03-24 20:09:42
【问题描述】:
当使用 Doctrine 的 ObjectSelect 使用 Zend Form 填充表单元素时,property 参数需要对应实体中的 getPropertyName() 方法。
我们可以告诉ObjectSelect 使用魔术getter,而不是为实体中的每个受保护属性创建getter,例如。 __get('PropertyName')?
原因是如果一个表有 +100 列,我们应该为每个列创建 getter,还是我们可以使用魔术 getter 来填充表单元素?
实体
namespace Users\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
* @ORM\Table(name="tbl_users")
* @property int $id
* @property string $firstname
*/
class User{
/**
* @ORM\Id
* @ORM\Column(type="integer");
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\Column(type="string")
*/
protected $firstname;
/**
* Exposes protected properties
*
* @param string $prop
*/
public function __get($prop){
return $this->$prop;
}
/**
* Saves protected properties
*
* @param string $prop
* @param mixed $val
*/
public function __set($prop, $val){
$this->$prop = $val;
}
}
表格
namespace Users\Form;
use Zend\Form\Form;
use DoctrineModule\Stdlib\Hydrator\DoctrineObject as DoctrineHydrator;
use DoctrineModule\Persistence\ObjectManagerAwareInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\ORM\EntityManager;
class UserForm extends Form implements ObjectManagerAwareInterface{
protected $em;
public function __construct(EntityManager $em, $name = null){
parent::__construct('Edit User');
$hydrator = new DoctrineHydrator($em, 'Users\Entity\User');
$this->setHydrator($hydrator);
$this->add(array(
'type' => 'DoctrineModule\Form\Element\ObjectSelect',
'name' => 'firstname',
'options' => array(
'object_manager' => $em,
'target_class' => 'Users\Entity\User',
'property' => 'firstname'
)
));
}
【问题讨论】:
标签: php forms doctrine-orm doctrine zend-framework2