【问题标题】:Doctrine 2 - Magic getter on an ObjectSelect element using Zend FormDoctrine 2 - 使用 Zend Form 的 ObjectSelect 元素上的魔法吸气剂
【发布时间】: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


    【解决方案1】:

    由于这个问题没有得到解决,我相信诀窍是在 DoctrineHydrator 构造函数中将“byValue”设置为 false。

    $hydrator = new DoctrineHydrator($em, 'Users\Entity\User', false);
    

    默认情况下,byValue 为 true,并指示 Doctrine 使用 getProperty() 方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-16
      • 1970-01-01
      • 2018-04-05
      • 1970-01-01
      • 1970-01-01
      • 2023-02-02
      • 2019-11-26
      相关资源
      最近更新 更多