Zend Framework 2 - Annotation Forms don't work

后端 未结 2 531
天命终不由人
天命终不由人 2021-01-06 11:41

Thanks to @Hikaru-Shindo I looked into AnnotationForms which seem to be the best available as a work-around for ModelForms. But the example shown h

2条回答
  •  北荒
    北荒 (楼主)
    2021-01-06 12:01

    This could be your entity (and form definition) for a user entity (shortend version):

    namespace Application\Entity;
    use Doctrine\ORM\Mapping as ORM;
    use Zend\Form\Annotation as Form;
    
    /**
     * @ORM\Entity
     * @ORM\Table(name="application_user")
     * @Form\Name("user")
     * @Form\Hydrator("Zend\Stdlib\Hydrator\ObjectProperty")
     */
    class User
    {
    
        /**
         * @var int
         * @ORM\Id @ORM\Column(name="id", type="integer")
         * @ORM\GeneratedValue
         * @Form\Exclude()
         */
        protected $id;
    
        /**
         * @var string
         * @ORM\Column(name="user_name", type="string", length=255, nullable=false)
         * @Form\Filter({"name":"StringTrim"})
         * @Form\Validator({"name":"StringLength", "options":{"min":1, "max":25}})
         * @Form\Validator({"name":"Regex", "options":{"pattern":"/^[a-zA-Z][a-zA-Z0-9_-]{0,24}$/"}})
         * @Form\Attributes({"type":"text"})
         * @Form\Options({"label":"Username:"})
         */
        protected $username;
    
        /**
         * @var string
         * @ORM\Column(name="email", type="string", length=90, unique=true)
         * @Form\Type("Zend\Form\Element\Email")
         * @Form\Options({"label":"Your email address:"})
         */
        protected $email;
    
    }
    

    And to use this form:

    use Zend\Form\Annotation\AnnotationBuilder;
    
    $builder = new AnnotationBuilder();
    $form    = $builder->createForm('Application\Entity\User');
    // Also possible:
    // $form = $builder->createForm(new Application\Entity\User());
    

    So the builder needs the fully qualified name of your definition class. The name you set using the annotations is the name of the form used for example to create the form's id attribute.

    If you have a use statement for it you could also abond the namespace:

    use Zend\Form\Annotation\AnnotationBuilder;
    use Application\Entity\User;
    
    $builder = new AnnotationBuilder();
    $form    = $builder->createForm('User');
    // Also possible:
    // $form = $builder->createForm(new User());
    

提交回复
热议问题