Doctrine + ZF2 tips: Doctrine Entity and Zend Form

Docblock Annotations in Doctrine is a really nice way to specify object-relational mapping metadata. But ZF2 also comes with a Zend\Form\Annotation class for specifying field properties on forms. Wouldn’t it be nice if you could combine these two? It turns out you can. Let’s have a look at how easily a Doctrine entity can be turned into a Zend form.

A really nice feature in ZF2 Forms – you can use Doctrine Annotations to create a form. How cool is this? 🙂

use Zend\View\Model\ViewModel;
use DoctrineModule\Stdlib\Hydrator\DoctrineObject as DoctrineHydrator;
use DoctrineORMModule\Form\Annotation\AnnotationBuilder;


$entityManager = $this->getServiceLocator()->get('doctrine.entitymanager.orm_default');
$repository = $entityManager()->getRepository('Admin\Entity\SystemUser');
$id = (int)$this->params()->fromQuery('id');
$user = $repository->find($id);

/* here comes the magic */
$builder = new AnnotationBuilder( $entityManager);
$form = $builder->createForm( $user );
$form->setHydrator(new DoctrineHydrator($entityManager,'Admin\Entity\SystemUser'));

$view =  new ViewModel();

And on the entity, you add form annotations!

use Doctrine\ORM\Mapping as ORM;
use Zend\Form\Annotation;

  * Application\Entity\SystemUser
  * @ORM\Table(name="system_user")
  * @ORM\Entity(repositoryClass="Admin\Repository\UserRepository")
  * @Annotation\Name("user")
class SystemUser implements UserInterface, SoftDeleteInterface
      * @var integer $userId
      * @ORM\Column(name="user_id", type="bigint", nullable=false)
      * @ORM\Id
      * @ORM\GeneratedValue(strategy="IDENTITY")
      * @Annotation\Attributes({"type":"hidden"})
    private $userId;

      * @var string $code
      * @ORM\Column(name="code", type="string", length=255, nullable=true)
      * @Annotation\Attributes({"type":"text"})
      * @Annotation\Options({"label":"Code:"})

    private $code;

      * @var string $email
      * @ORM\Column(name="email", type="string", length=250, nullable=false)
      * @Annotation\Type("Zend\Form\Element\Email")
      * @Annotation\Options({"label":"Your email address:"})
    private $email;

Of course, sometimes you don’t want to allow the user to edit all properties; in these cases you can use @Annotation\Exclude().

Latest News & Insights

Say connected – get Loft updates straight to your inbox.