I have a search form with 2 fields, not linked to an entity. Let's say it's built like this:
$builder
->add('orderNumber', 'text', array('required' => false))
->add('customerNumber', 'text', array('required' => false))
;
I want the users to be obliged to fill at least one of the two fields.
What is the proper way to achieve this with Symfony 2.5?
Edit: Can it be done without adding a data class?
Thanks to @redbirdo answer, I result in this code:
$builder
->add('orderNumber', 'text', array(
'required' => false,
'constraints' => new Callback(array($this, 'validate'))
))
->add('customerNumber', 'text', array('required' => false))
;
And the validate method is:
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With