Open
Description
When submitting a form with a dependent field if the dependent field is not shown then a "This form should not contain extra fields." error is shown.
$builder = new DynamicFormBuilder($builder);
$builder
->add('comparison', ChoiceType::class, [
'choices' => [
'is…' => 'eq',
'is not…' => 'neq',
'is empty' => 'empty',
]
])
->addDependent(
name:'value',
dependencies: ['comparison'],
callback: function (DependentField $field, ?string $comparison) use ($options): void {
if ($comparison === 'empty') {
return;
}
$field->add(TextType::class, [
'required' => false
]);
}
);
Video:
Screen.Recording.2024-04-19.at.20.50.53.mov
I'm not using any javascript to remove the value
field before submission so the data is being submitted triggering the error.
I've also implemented this with PRE_SUBMIT
on the parent form which checks the view data, adds / removes the value
field and unsets the data which works without error.
// Add an PRE_SET_DATA event listener that adds or removes the value field based on the original comparison data
// This fires when the data is set on the form
$builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) use ($options) {
$form = $event->getForm();
$data = $event->getData();
$comparison = $data['comparison'] ?? null;
if (!in_array($comparison, [ComparisonType::EMPTY, ComparisonType::NOT_EMPTY])) {
$form->add('value', TextType::class, ['required' => false]);
}
});
// Add a PRE_SUBMIT event listener that adds or removes the value field based on the submitted comparison data
// This fires when the form is submitted
$builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) use ($options) {
$form = $event->getForm();
$data = $event->getData();
$comparison = $data['comparison'] ?? null;
if (!in_array($comparison, [ComparisonType::EMPTY, ComparisonType::NOT_EMPTY])) {
$form->add('value', TextType::class, ['required' => false]);
return;
}
// Remove the form field
$form->remove('value');
// Unset the value and the submitted data
// Removing the submitted data removes the extra fields error
unset($data['value']);
$event->setData($data);
});
Metadata
Metadata
Assignees
Labels
No labels