Symfony 2:添加自定义表单元素,而不是在实体中 [英] Symfony 2 : Add a custom form element, not in an Entity

查看:27
本文介绍了Symfony 2:添加自定义表单元素,而不是在实体中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Symfony2 工作,我想创建一个注册表单.我不想使用 FOSUserBundle.

I work with Symfony2 and I would like to create a registration form. I don't want to use FOSUserBundle.

因此,我创建了一个实体帐户(包含字段:用户名、密码、电子邮件...)并创建了表单:

So, I create an Entity Account (with fields : username, password, email...) and I create the form :

 $account = new Account();

$form = $this->createFormBuilder($account)
  ->add('username',         'text', array('label' => 'Nom de compte :'))
  ->add('password',    'password', array('label' => 'Mot de passe :'))
  ->add('email',            'email', array('label' => 'Adresse email :'))
  ->getForm();

现在,我想为密码添加一个确认字段.但是,当我尝试使用 add() 方法添加字段时,例如password_confirmation"我有这个:

Now, I want to add a confirmation field for the password. But, when I try to add a field with add() method, for example "password_confirmation" I have this :

App\FrontBundle\Entity\Account"类中既不存在属性password_confirmation",也不存在方法getPasswordConfirmation()"和方法isPasswordConfirmation()"

Neither property "password_confirmation" nor method "getPasswordConfirmation()" nor method "isPasswordConfirmation()" exists in class "App\FrontBundle\Entity\Account"

如何添加自定义字段?之后,如何验证它?

How can I add a custom field ? And after, how to valid it ?

谢谢.BR.

推荐答案

在正常情况下,您需要使用 property_path 选项.

In a normal situation, you'd need to explicitly specify that *password_confirmation* isn't part of the entity, using the property_path option.

->add('password_confirmation', 'password', array('property_path' => false))

然后使用 CallBackValidator 对其进行验证.

And then to validate it with a CallBackValidator.

但是,在这种特定情况下,您想要重复一个字段,重复 小部件可以为您做到这一点.

But, in this specific case, where you want to repeat a field, the repeated widget can do that for you.

->add('password_confirmation', 'repeated', array(
    // See the docs :)
));

这篇关于Symfony 2:添加自定义表单元素,而不是在实体中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆