Search code examples
phprestsymfony1routeshttp-method

Configuring a route in Symfony with the same URL but different HTTP methods and controller actions


I have the following routes configuration in a Symfony application:

label:
  url:          /label
  param:        { module: label, action: configure }
  requirements: { sf_method: get }

label_create:
  url:          /label
  param:        { module: label, action: create }
  requirements: { sf_method: post }

linked to executeConfigure and executeCreate actions. Then I have a form configured this way:

<form action="<?php echo url_for('@label_create') ?>" method="POST">
  <?php echo $form->renderHiddenFields() ?>
  <input type="hidden" name="sf_method" value="post" />
  <!-- more stuff here -->
</form>

Whenever the form is submitted executeConfigure is executed, although as far as I know the route configured with POST method should avoid that and executes executeCreate.

How can I differentiate between these two actions keeping the same URL?

Thanks!


Solution

  • I had this issue as well and found the answer in an old forum message (http://oldforum.symfony-project.org/index.php/t/25750/).

    If it is completely ignoring the request method then it is most likely using the regular sfRoute. You need to use sfRequestRoute to make the routing 'method-aware'. So, in your example you will do:

    label:
      url:          /label
      class:        sfRequestRoute
      param:        { module: label, action: configure }
      requirements: { sf_method: get }
    
    label_create:
      url:          /label
      class:        sfRequestRoute
      param:        { module: label, action: create }
      requirements: { sf_method: post }