Symfony 2 : Add a custom form element, not in an Entity

偶尔善良 提交于 2019-12-03 14:33:23

问题


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

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 :

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 ?

Thank you. BR.


回答1:


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

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



回答2:


An update for Symfony 2.1:

property_path has been deprecated and instead you should use mapped. The syntax remains the same:

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


来源:https://stackoverflow.com/questions/10950203/symfony-2-add-a-custom-form-element-not-in-an-entity

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