简体   繁体   中英

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!

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 }

I solved it by using this routing sheme:

users_create:
    pattern:     /
    defaults: { _controller: "RentalAPIBundle:User:create" }
    requirements: { _method: post }

users:    
    pattern:     /    
    defaults: { _controller: "RentalAPIBundle:User:index" }    
    requirements: { _method: get }

then when calling the Url you can either call user or user/ for GET but only users/ for POST. I can't say why but it works

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM