S
S
symnoob2018-05-15 10:36:46
symfony
symnoob, 2018-05-15 10:36:46

Symfony 4, how to make one of the fields required?

Good afternoon Forum,
how can I solve the following problem?:
There is a form with multiple fields, almost all are mandatory.
but there are three fields of which at least one must be filled.
Can anyone suggest how this can be done?
and can anyone tell me what it is for?

резолвер public function configureOptions(OptionsResolver $resolver)
and why do we need groups in validation?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
voronkovich, 2018-05-15
@voronkovich

The easiest way is to manually check the fields and add an error to the form:

$form = $this->createForm(MyFormType::class, $data);

$form->handleRequest($request);

if ($form->isSubmitted() && (/* Проверка полей */)) {
    $form->addError(new FormError('Хотя бы одно из полей ... должно быть заполнено'));
}

if ($form->isSubmitted() && $form->isValid()) {
   // Сохранение результатов
}

For more complex cases (if you are going to reuse the form in other places) it is better to add your own validator: https://coderwall.com/p/1blgvq/symfony2-custom-fie...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question