How does Symfony handle POST method towards controllers? For example, this code in ASP.NET makes it possible to use an exact similar name for a controller, in a different manner:
public ActionResult Create()
{
return View();
}
// POST: Objects/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create()
{
//Code here that only runs on POST method of a form
return View();
}
I have seen something like:
public function createAction()
{
return $this->render('formPage.html.twig');
}
/**
* @Method({"POST"})
*/
public function createAction()
{
//Some code...
return new Response('Added item with id: ' . $item->getId() . 'to database');
}
Is the latter possible and similar to the former? Is it necessary to use such annotation like this or can it also be added to routing and if so, should I make different routing names or something?
movie_create:
path: /movies/create
defaults: { _controller: AppBundle:Movie:create }
Controllers in Symfony2 are classes, in which you cannot re-defined methods with the same name.
I'm afraid you'll need to either split your controller into two:
class ViewController extends Controller {
public function createAction()
{
return $this->render('formPage.html.twig');
}
}
class CreateController extends Controller {
/**
* @Method({"POST"})
*/
public function createAction()
{
//Some code...
return new Response('Added item with id: ' . $item->getId() . 'to database');
}
}
Or a much simpler solution, simply re-name your methods in your routing:
movie_view:
path: /movies/view
defaults: { _controller: AppBundle:Movie:view }
movie_create:
path: /movies/create
defaults: { _controller: AppBundle:Movie:create }
requirements:
_method: POST
You can define what methods a route will accept, either by annotation as per your example or in the routing.yml;
my_route:
path: /foo/bar/{id}
defaults: { _controller: AppBundle:Fubar:foo }
methods: [POST]
this will acept only POST.
You can't define two methods with the same name, that is a limitation of PHP in general. In your case you could have one route to show the form and another to handle the request.