1

I have a general question how the currently correct way of processing a submitted form should look like, the symfony docs aren't that clear what's the proper way to go.
Currently I am always doing something like this:

if ($request->isMethod(Request::METHOD_POST)) {
   $form->handle($request)
   if ($form->isValid()) {...}
}

but I have also seen some examples (also in the symfony docs) where this statement is used:

$form->handle($request);
if ($form->isSubmitted() && $form->isValid()) {...}

So does anyone know what's the currently correct way to go following symfony developer guidelines, should the first statement be used or second, or should both be combined (although this would make either the $request->isMethod call or the $form->isSubmitted redundant)

0

2 Answers 2

5

Technically all you need is:

if ($form->isValid()) {
    ...
}

That's because:

  • the isValid() check includes the isSubmitted check.
  • the isMethod(Request::METHOD_POST) check is not necessarily correct (a form can use a different method than POST

But if you really want to follow best practices, you should use:

if ($form->isSubmitted() && $form->isValid()) {
    ...
}

See http://symfony.com/doc/current/best_practices/forms.html#handling-form-submits for details.

Additional info

You may want to use the isSubmitted method separately if you want to perform some special task before the data is actually validated. I use it often for custom validations, e.g.

if ($form->isSubmitted()) {
    ...
    if ($form->isValid()) {
        ...
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

In general both is correct. Just first example has check of request type when second simply check for submit and doing validation.

2 Comments

I know that both work, but there must be a guideline which one is the "standard" code styling
First sample just check request method -- POST/GET/PUT etc. In this example if request is not POST method form won't be processed. In second sample -- form will be processed with any request method so it simply uses $form->isSubmitted(). It's a same thing like this: if ($request->isMethod(Request::METHOD_POST)||$request->isMethod(Request::METHOD_GET)).... So in second simply omitted this check.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.