dcd0181
dcd0181

Reputation: 1503

Doctrine 2 - Magic getter on an ObjectSelect element using Zend Form

When populating a form element with Zend Form using Doctrines' ObjectSelect, the property parameter expects a getPropertyName() method within the corresponding entity.

Instead of creating getters for each protected property within an entity, are we able to tell ObjectSelect to use a magic getter, e.x. __get('PropertyName')?

Reason being what if a table has +100 columns, are we supposed to create getters for each, or can we use a magic getter to populate form elements?

Entity

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;
    }
}

Form

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'
        )
    ));
}

Upvotes: 1

Views: 748

Answers (1)

ainesophaur
ainesophaur

Reputation: 804

Since this went unanswered, I believe the trick is to set "byValue" to false in the DoctrineHydrator constructor.

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

By default the byValue is true and instructs Doctrine to use the getProperty() methods.

Upvotes: 1

Related Questions