One field should not be blank if some fields are blank in Symfony Form

php, symfony

Solution

There are even easier solutions than writing a custom validator. The easiest of all is probably the expression constraint:

class MyEntity
{
    private $fieldA;

    private $fieldB;

    /**
     * @Assert\Expression(
     *     expression="this.fieldA != '' || this.fieldB != '' || value != ''",
     *     message="Either field A or field B or field C must be set"
     * )
     */
    private $fieldC;
}

You can also add a validation method to your class and annotate it with the Callback constraint:

/**
 * @Assert\Callback
 */
public function validateFields(ExecutionContextInterface $context)
{
    if ('' === $this->fieldA && '' === $this->fieldB && '' === $this->fieldC) {
        $context->addViolation('At least one of the fields must be filled');
    }
}

The method will be executed during the validation of the class.

Problem

In my Symfony 2 (2.4.2) application, there is a Form Type which consists of 3 fields. I'd like the validation be like this: If `field A` and `field B` are blank, `field C` should not be blank. This means that at least one field should receive some data. Currently, I check the received data in the controller. Is there a more recommended way to do this?

Original source