Configuring a route in Symfony with the same URL b

2019-09-21 09:46发布

问题:

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!

回答1:

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 }


回答2:

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