Zend Framework 2 - 注释表单不起作用

2022-01-02 00:00:00 model forms php zend-framework2 zend-form

感谢 @Hikaru-Shindo 我研究了 AnnotationForms,这似乎是最好的可用作 ModelForms 的变通方法.但是示例显示 这里对我不起作用.

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 here doesn't work for me.

use ZendFormAnnotationAnnotationBuilder;

$builder = new AnnotationBuilder();
$form    = $builder->createForm('User');

看着这段代码,我想知道 AnnotationBuilder 在哪里知道在哪里寻找这个用户表单.特别是因为在 def 形式的注释中有一个小写的 'user'

Looking at this code I wonder where the AnnotationBuilder knows where to look for this user form. Especially because in the annotation in the form def there is a lowercase 'user'

@AnnotationName("user")

我将表单定义代码放入MyModule/Form/UserForm.php",将较低的代码放入我的控制器.这是正确的方法吗?

I put the form def code into 'MyModule/Form/UserForm.php' and the lower code into my Controller. Is this the right way?

推荐答案

这可能是用户实体的实体(和表单定义)(缩写版本):

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

namespace ApplicationEntity;
use DoctrineORMMapping as ORM;
use ZendFormAnnotation as Form;

/**
 * @ORMEntity
 * @ORMTable(name="application_user")
 * @FormName("user")
 * @FormHydrator("ZendStdlibHydratorObjectProperty")
 */
class User
{

    /**
     * @var int
     * @ORMId @ORMColumn(name="id", type="integer")
     * @ORMGeneratedValue
     * @FormExclude()
     */
    protected $id;

    /**
     * @var string
     * @ORMColumn(name="user_name", type="string", length=255, nullable=false)
     * @FormFilter({"name":"StringTrim"})
     * @FormValidator({"name":"StringLength", "options":{"min":1, "max":25}})
     * @FormValidator({"name":"Regex", "options":{"pattern":"/^[a-zA-Z][a-zA-Z0-9_-]{0,24}$/"}})
     * @FormAttributes({"type":"text"})
     * @FormOptions({"label":"Username:"})
     */
    protected $username;

    /**
     * @var string
     * @ORMColumn(name="email", type="string", length=90, unique=true)
     * @FormType("ZendFormElementEmail")
     * @FormOptions({"label":"Your email address:"})
     */
    protected $email;

}

并使用这种形式:

use ZendFormAnnotationAnnotationBuilder;

$builder = new AnnotationBuilder();
$form    = $builder->createForm('ApplicationEntityUser');
// Also possible:
// $form = $builder->createForm(new ApplicationEntityUser());

因此构建器需要定义类的完全限定名称.您使用注释设置的名称是用于创建表单的 id 属性的表单的名称.

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.

如果你有一个 use 语句,你也可以取消命名空间:

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

use ZendFormAnnotationAnnotationBuilder;
use ApplicationEntityUser;

$builder = new AnnotationBuilder();
$form    = $builder->createForm('User');
// Also possible:
// $form = $builder->createForm(new User());

相关文章