Zend Framework 2 - show a select with values of an entity using annotationbuilder (having a ManyToOne relationship)


July 07, 2014 at 13:19
Zend Framework

Mit dem annotationbuilder generiere ich ein Formular basierend auf einer Entity:
$text = new Text();
    $builder = new AnnotationBuilder( $entityManager);
    $form = $builder->createForm( $text );
    $form->setHydrator(new DoctrineHydrator($entityManager,'Backend\Entity\Text'));
    $form->bind($text);
Das einzige Problem war das Feld categoryId, das eine manyToOne Beziehung zu einer weiteren Entity namens TextCategory hat. Ich wollte, dass nur anhand der Annotations ein select mit den entsprechenden Werten (aus dem Feld "name" in TextCategory) angezeigt wird. Das geht so:
      /**
       * @var string $categoryId
       * 
       * @ORM\ManyToOne(targetEntity="Backend\Entity\TextCategory", fetch="EAGER")
       * @ORM\JoinColumn(name="categoryId", referencedColumnName="id", nullable=false)
       * @Annotation\Type("DoctrineORMModule\Form\Element\EntitySelect")
       * @Annotation\Required({"required":"true" })
       * @Annotation\Filter({"name":"StripTags"})
       * @Annotation\Options({"label":"Class:",  "property":"name", "target_class" : "Backend\Entity\TextCategory"})
       * @Annotation\Attributes({"value":"0"}) 
       * 
       */
      private $categoryId;    
Das Ergebnis ist geradezu berauschend gut. Using the annotationbuilder I generated a form based on an entity:
$text = new Text();
    $builder = new AnnotationBuilder( $entityManager);
    $form = $builder->createForm( $text );
    $form->setHydrator(new DoctrineHydrator($entityManager,'Backend\Entity\Text'));
    $form->bind($text);
The only difficulty was the field categoryId, which has a many-to-one relation to another entity named TextCategory. What I wanted to do was show a simple select with the values from the field "name" in TextCategory. And this is done as follows:
      /**
       * @var string $categoryId
       * 
       * @ORM\ManyToOne(targetEntity="Backend\Entity\TextCategory", fetch="EAGER")
       * @ORM\JoinColumn(name="categoryId", referencedColumnName="id", nullable=false)
       * @Annotation\Type("DoctrineORMModule\Form\Element\EntitySelect")
       * @Annotation\Required({"required":"true" })
       * @Annotation\Filter({"name":"StripTags"})
       * @Annotation\Options({"label":"Class:",  "property":"name", "target_class" : "Backend\Entity\TextCategory"})
       * @Annotation\Attributes({"value":"0"}) 
       * 
       */
      private $categoryId;    
Making this work took me HOURS. But now I'm very happy :D

Tags: annotationbuilder Annotations zend forms ZF2


Hinterlasse einen Kommentar:
Search