How to define a Symfony2 form (no object) with at least 1 of 2 fields?
I have a search form with two non-entity related fields. Let's say it's built like this:
$builder
->add('orderNumber', 'text', array('required' => false))
->add('customerNumber', 'text', array('required' => false))
;
I want users to be required to fill in at least one of the two fields.
What's the correct way to achieve this with Symfony 2.5?
Edit: is it possible to do this without adding a data class?
+3
source to share
2 answers
Thanks to @redbirdo's answer, I will lead to this code:
$builder
->add('orderNumber', 'text', array(
'required' => false,
'constraints' => new Callback(array($this, 'validate'))
))
->add('customerNumber', 'text', array('required' => false))
;
And the check method:
public function validate($value, ExecutionContextInterface $context)
{
/** @var \Symfony\Component\Form\Form $form */
$form = $context->getRoot();
$data = $form->getData();
if (null === $data['orderNumber'] && null === $data['customerNumber']) {
$context->buildViolation('Please enter at least an order number or a customer number')
->addViolation();
}
}
+6
source to share
When you use a form with an array of data rather than a base data class, you need to set validation constraints yourself and attach them to individual fields. See the Symfony documentation:
Forms → Use the form without a class → Adding Validation
for example
$builder
->add('orderNumber', 'text', array(
'required' => false
'constraints' => new NotBlank()
))
->add('customerNumber', 'text', array(
'required' => false
'constraints' => new NotBlank()
))
;
Note. As per the example documentation, "constraints" can be provided as a single constraint or an array of constraints.
+3
source to share