Recently on a project I had a situation where I was using the Symfony2 forms component without an entity. In addition to each field’s constraints, I needed to something similar to symfony 1.4’s conditional validator so that I could make sure that the form on the whole was valid. There are a bunch of docs out there on how to use callback functions on an entity to do this, however I didn’t see much on how to get the entire form that has no entity to do a callback. After reading some of the source code, found that you can set up some ‘form level’ constraints in the setDefaultOptions method. So it will look something like this:
public function setDefaultOptions(OptionsResolverInterface $resolver) | |
{ | |
$resolver->setDefaults( | |
array('constraints'=>array(new Callback(array('methods'=>array(array($this,'checkAvailableFunds'))))), | |
) | |
); | |
} |
You pass the Callback constraint an array methods which it can call. If you pass one of those methods is an array it is parsed as class::method. In my case by passing $this it uses the currently instantiated form, rather than trying to call the method statically.
From there you can do something like this:
public function checkAvailableFunds($data,ExecutionContextInterface $context) | |
{ | |
if($data['oneField']===1&&$data['twoField']===3){ | |
$context->addViolation('No or not enough giftcodes for selected export are available!'); | |
} | |
} |
The first parameter is the form’s data fields. From there you can add global level errors to the form, such as if a combination of fields are not valid.
Good luck out there.