M
M
MikUrrey2022-02-13 15:01:43
symfony
MikUrrey, 2022-02-13 15:01:43

SYmfony 3.4: how to do form validation correctly?

Greetings!
There is an essence

class Meeting
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    //......и т. д.
}

and form
class MeetingType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('title', TextType::class)
            ->add('desctiption', TextareaType::class)
            ->add('avatar', FileType::class)
            ->add('beginAt', IntegerType::class)
            ->add('createdAt', IntegerType::class)
            ->add('updatedAt', IntegerType::class)
            ->add('uid', IntegerType::class)
            ;
    }
}

The data is sent by XHR, so everything in the controller is like this:
public function createAction(Request $request)
{
    $data = $request->request->all();
    $formData = [
       //... здесь заполнение в соответствии с моделью и преобразование некоторых полей
       //... так же подцепляется CSRF токен
    ];
    $form = $this->createForm(MeetingType::class, new Meeting);
    $form->submit($formData);
    if (!$form->isValid()) {
        $errors = [];
               foreach ($form->getErrors(true, false) as $key => $error) {
                    if (method_exists($error, 'getMessage')) {
                        $errors[] = $error->getMessage();
                    } else {
                        foreach ($error as $k => $e) {
                            $errors[] = $e->getMessage();
                        }
                    }
                }
                return new JsonResponse([
                    'success' => false,
                    'errors' => $errors,
                    'type' => 'form-validation',
                ]);
    }
}

The problems are:
a) If getErrors(false) , then the form is !isValid , but the list of errors is empty. That is, for some reason, errors are not converted to a flat list.
b) If I add constraints to the entity using loadValidatorMetadata , or as field options in the MeetingType , it doesn't work.
c) Two errors came from somewhere. The value should not be empty , although constraints are not specified.
d) There is no way to associate errors with certain fields.
e) For some reason, $error->getCause() causes a brutal memory hog and a dead freeze of the entire server for good.

Obviously, there are a lot of things here that I do not understand and do wrong. How to organize the correct field validation on the server side?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
BoShurik, 2022-02-16
@MikUrrey

In your case, "correct" is not to use forms. symfony/serializer+ symfony/validator+ symfony/security-csrf
https://qna.habr.com/q/548586#answer_1249224
+ You need to use DependencyInjection: https://symfony.com/doc/current/service_container.html

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question