.. index::
single: Routing; _method
Using HTTP Methods beyond GET and POST in Routes
================================================
The HTTP method of a request is one of the requirements that can be checked
when seeing if it matches a route. This is introduced in the routing chapter
of the book ":doc:`/book/routing`" with examples using GET and POST. You
can also use other HTTP verbs in this way. For example, if you have a blog
post entry then you could use the same url pattern to show it, make changes
to it and delete it by matching on GET, PUT and DELETE.
.. configuration-block::
.. code-block:: yaml
blog_show:
pattern: /blog/{slug}
defaults: { _controller: AcmeDemoBundle:Blog:show }
requirements:
_method: GET
blog_update:
pattern: /blog/{slug}
defaults: { _controller: AcmeDemoBundle:Blog:update }
requirements:
_method: PUT
blog_delete:
pattern: /blog/{slug}
defaults: { _controller: AcmeDemoBundle:Blog:delete }
requirements:
_method: DELETE
.. code-block:: xml
AcmeDemoBundle:Blog:show
GET
AcmeDemoBundle:Blog:update
PUT
AcmeDemoBundle:Blog:delete
DELETE
.. code-block:: php
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\Route;
$collection = new RouteCollection();
$collection->add('blog_show', new Route('/blog/{slug}', array(
'_controller' => 'AcmeDemoBundle:Blog:show',
), array(
'_method' => 'GET',
)));
$collection->add('blog_update', new Route('/blog/{slug}', array(
'_controller' => 'AcmeDemoBundle:Blog:update',
), array(
'_method' => 'PUT',
)));
$collection->add('blog_delete', new Route('/blog/{slug}', array(
'_controller' => 'AcmeDemoBundle:Blog:delete',
), array(
'_method' => 'DELETE',
)));
return $collection;
Unfortunately, life isn't quite this simple, since most browsers do not
support sending PUT and DELETE requests. Fortunately Symfony2 provides you
with a simple way of working around this limitation. By including a ``_method``
parameter in the query string or parameters of an HTTP request Symfony2 will
use this as the method when matching routes. This can be done easily in forms
with a hidden field. Suppose you have a form for editing a blog post:
.. code-block:: html+jinja
The submitted request will now match the ``blog_update`` route and the ``updateAction``
will be used to process the form.
Likewise the delete form could be changed to look like this:
.. code-block:: html+jinja
It will then match the ``blog_delete`` route.