Reputation: 1500
In my Symfony2 app, I have actions handling form submissions. In an effort to clean up my controllers, I want to know where is the best place to do something like the following, or if the controller is the right place to handle the form and validate it.
public function addAction(Request $request)
{
$article = new Article();
$articleForm = $this->createForm(
'web_article_type',
$article
);
$articleForm->handleRequest($request);
if ($articleForm->isValid()) {
$manager = $this->getDoctrine()->getManager();
$manager->persist($article);
$manager->flush();
}
return $this->redirect($this->generateUrl('web_article_show'));
}
Upvotes: 0
Views: 103
Reputation: 4766
This is already the best practice form!
The Controller is the correct place for it because it handels the data that comes from the frontend. Also it renders a template if the form got errors or fires other actions if the form is valid.
I'd only get away from that way in the following case:
You have a form that should be extended with different fields for different user roles/permissions.
Then I'd define that form as a service for better handling of the form and better design.
Upvotes: 2