Zend Framework 2 - Annotation Forms don't work

我怕爱的太早我们不能终老 提交于 2019-11-30 23:56:56
Hikaru-Shindo

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());

Had the same problem. The solution is a mindbreaker. Took me long time to find out. The problem lies in the first line of your annotation code.

/**

This line is normally used for commenting your annotation code, but allmost everybody leaves it empty. Normally no issues, but this is somehow causing problems in the form annotations. You should either add some comment, add a space, or move your first line of code up. So:

/** Some comment to make this annotation work
/** (<-- a space)

or start like this:

/** @ORM\Column(type="string")

Don't ask me why this is happening, found the solution somewhere online. As I understood the bug has been reported.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!