@raven_corwin
To validate a field that depends on another field in Symfony, you can make use of Symfony's validation constraints and create a custom validation constraint. Here is an example of how you can do this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
// src/Validator/Constraints/DependentFieldConstraint.php namespace AppValidatorConstraints; use SymfonyComponentValidatorConstraint; /** * @Annotation */ class DependentFieldConstraint extends Constraint { public $message = 'The value of field "%dependedField%" is required when field "%field%" is "%condition%"'; public $field; public $dependedField; public $condition; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
// src/Validator/Constraints/DependentFieldValidator.php namespace AppValidatorConstraints; use SymfonyComponentValidatorConstraint; use SymfonyComponentValidatorConstraintValidator; class DependentFieldValidator extends ConstraintValidator { public function validate($value, Constraint $constraint) { // Get the value of the depended field $dependedFieldValue = $this->context->getRoot()->get($constraint->dependedField)->getData(); // Do the validation based on the condition if ($constraint->condition === 'some_condition' && !$dependedFieldValue) { // Validation failed, add a violation $this->context->buildViolation($constraint->message) ->setParameter('%field%', $constraint->field) ->setParameter('%dependedField%', $constraint->dependedField) ->setParameter('%condition%', $constraint->condition) ->addViolation(); } } } |
1 2 3 |
# config/validation.yaml AppValidatorConstraintsDependentField: - AppValidatorConstraintsDependentFieldValidator |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
use AppValidatorConstraintsDependentField; // ... public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('field') ->add('dependedField', null, [ 'constraints' => [ new DependentField([ 'field' => 'field', 'dependedField' => 'dependedField', 'condition' => 'some_condition', ]), ], ]); } |
In this example, the dependedField
will be validated based on the provided condition. If the condition fails, a validation error will be displayed with the message defined in the DependentFieldConstraint
class.
Remember to customize the conditions and validation rules as per your requirements.