Adding customised validation rules to SonataUserBundle

♀尐吖头ヾ 提交于 2019-12-04 02:32:29

The UserAdmin form is NOT the same as the profile form.


To find out what validation group a form is using open up symfony’s profiler

  1. post your form in the development environment (app_dev.php)
  2. open http://127.0.0.1:8000/app_dev.php/_profiler/
  3. view the last 10 submissions.
  4. click the POST method your form was submitted on (in this case the sonata user admin create form)
  5. click FORMS
  6. in Passed Options or Resolved Options you should see what validation_groups is set.

To add customized validation rules to the SonataUserBundle’s UserAdmin create or edit user, you’ll need to do the following:

if you look at https://github.com/sonata-project/SonataUserBundle/blob/master/Admin/Model/UserAdmin.php You’ll see the validation_groups for the user admin are hard coded to Registration (new) or Profile (edit).

You have 2 choices.

A) Just add your validation rules to your projects validation.yml and use the existing Registration validation group.

Application\Sonata\UserBundle\Entity\User:
    properties:
        foo:
            - NotNull: { groups: [Registration, Profile] }

B) Override the UserAdmin::getFormBulder() to add your custom validation group

// In Application\Sonata\UserBundle\Admin\UserAdmin.php
public function getFormBuilder()
{
    $this->formOptions['data_class'] = $this->getClass();

    $options = $this->formOptions;
    $options['validation_groups'] = (!$this->getSubject() || is_null($this->getSubject()->getId())) ? ['CustomGroup','Registration'] : 'Profile';

    $formBuilder = $this->getFormContractor()->getFormBuilder( $this->getUniqid(), $options);

    $this->defineFormBuilder($formBuilder);

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