Enable dynamic set of validation groups by a callback or Closure

This will enable developer, to set a callback or a closure as a `'validation_groups'` form option,
this is usefull when we have to determine validation groups based on a client submitted data.
This commit is contained in:
Dariusz Górecki 2011-10-27 14:48:38 +02:00
parent 8c0517f305
commit e1822e7807
3 changed files with 33 additions and 3 deletions

View File

@ -27,9 +27,13 @@ class FieldTypeValidatorExtension extends AbstractTypeExtension
public function buildForm(FormBuilder $builder, array $options)
{
$options['validation_groups'] = empty($options['validation_groups'])
? null
: (array)$options['validation_groups'];
if (empty($options['validation_groups'])) {
$options['validation_groups'] = null;
} else {
$options['validation_groups'] = is_callable($options['validation_groups'])
? $options['validation_groups']
: (array) $options['validation_groups'];
}
$builder
->setAttribute('validation_groups', $options['validation_groups'])

View File

@ -133,6 +133,10 @@ class DelegatingValidator implements FormValidatorInterface
if ($form->hasAttribute('validation_groups')) {
$groups = $form->getAttribute('validation_groups');
if (is_callable($groups)) {
$groups = (array) call_user_func($groups, $form);
}
}
$currentForm = $form;
@ -141,6 +145,10 @@ class DelegatingValidator implements FormValidatorInterface
if ($currentForm->hasAttribute('validation_groups')) {
$groups = $currentForm->getAttribute('validation_groups');
if (is_callable($groups)) {
$groups = (array) call_user_func($groups, $currentForm);
}
}
}

View File

@ -38,6 +38,24 @@ class FieldTypeValidatorExtensionTest extends TypeTestCase
$this->assertEquals(array('group1', 'group2'), $form->getAttribute('validation_groups'));
}
public function testValidationGroupsCanBeSetToCallback()
{
$form = $this->factory->create('field', null, array(
'validation_groups' => array($this, 'testValidationGroupsCanBeSetToCallback'),
));
$this->assertTrue(is_callable($form->getAttribute('validation_groups')));
}
public function testValidationGroupsCanBeSetToClosure()
{
$form = $this->factory->create('field', null, array(
'validation_groups' => function($data, $extraData){ return null; },
));
$this->assertTrue(is_callable($form->getAttribute('validation_groups')));
}
public function testBindValidatesData()
{
$builder = $this->factory->createBuilder('field', null, array(