Skip to content

[Form] Document conditional constraints in forms without classes #21043

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: 6.4
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions form/without_class.rst
Original file line number Diff line number Diff line change
Expand Up @@ -177,3 +177,41 @@ in your controller::
->add('firstName', TextType::class)
->add('lastName', TextType::class)
->getForm();

Conditional Constraints
~~~~~~~~~~~~~~~~~~~~~~~

It's possible to define field constraints that depend on the value of other
fields (e.g. a field must not be blank when another field has a certain value).
To achieve this, use the ``expression`` option of the
:doc:`When constraint </reference/constraints/When>` to reference the other field::

$builder
->add('how_did_you_hear', ChoiceType::class, [
'required' => true,
'label' => 'How did you hear about us?',
'choices' => [
'Search engine' => 'search_engine',
'Friends' => 'friends',
'Other' => 'other',
],
'expanded' => true,
'constraints' => [
new Assert\NotBlank(),
]
])

// this field is only required if the value of the 'how_did_you_hear' field is 'other'
->add('other_text', TextType::class, [
'required' => false,
'label' => 'Please specify',
'constraints' => [
new Assert\When(
expression: 'this.getParent().get("how_did_you_hear").getData() == "other"',
constraints: [
new Assert\NotBlank(),
],
)
],
])
;