SonataAdminBundle has a powerful extensions feature which allows you to add or change features of one or more Admin instances.
I needed my extension to change some validation rules, and it turned out that imposing different validation groups was a good way to achieve it.
$formOptions attribute of Sonata\AdminBundle\Admin\AbstractAdmin class allows for setting validation groups, but I couldn’t find an easy way to modify it in my extension.
getFormBuilder method of AbstractAdmin class is where these $formOptions are added to the form builder:
<?php | |
// .... | |
public function getFormBuilder() | |
{ | |
$this->formOptions['data_class'] = $this->getClass(); | |
$formBuilder = $this->getFormContractor()->getFormBuilder( | |
$this->getUniqid(), | |
$this->formOptions | |
); | |
$this->defineFormBuilder($formBuilder); | |
return $formBuilder; | |
} |
So, in my admin class I override this method, to add support for extensions:
<?php | |
// .... | |
public function getFormBuilder() | |
{ | |
$this->configureFormOptions(); // additional call that includes extensions | |
$this->formOptions['data_class'] = $this->getClass(); | |
$formBuilder = $this->getFormContractor()->getFormBuilder( | |
$this->getUniqid(), | |
$this->formOptions | |
); | |
$this->defineFormBuilder($formBuilder); | |
return $formBuilder; | |
} | |
public function configureFormOptions() | |
{ | |
$extensions = $this->getExtensions(); | |
foreach ($extensions as $extension) { | |
if (method_exists($extension, 'configureFormOptions')) { | |
$this->formOptions = $extension->configureFormOptions($this->formOptions); | |
} | |
} | |
} | |
// .... |
Now, in your admin extension you can add a method to actually modify $formOptions of the admin class:
<?php | |
// .... | |
public function configureFormOptions(array $formOptions): array | |
{ | |
$formOptions['validation_groups'] = ['myValidationGroup', 'anotherValidationGroup']; | |
return $formOptions; | |
} |