Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a Symfony2 form (without entity) with at least 1 of 2 fields required?

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?

like image 431
Gregoire Avatar asked Dec 20 '22 10:12

Gregoire


1 Answers

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();
    }
}
like image 78
Gregoire Avatar answered May 12 '23 21:05

Gregoire