Max
Max

Reputation: 860

Symfony2: Problems with function parameter

In my template I call a function like this:

  loadResults('asc');

  function loadResults(order) {
            return $.get('{{ url('_example_results', { 'order' : ''}) }}'+order, function (html) {
                $('#results').html(html);
            });
        }

The function in my controller looks like this:

 public function resultsAction($order, Request $request)
 {
      // content is not crucial for solving my problem
 }

My results don't get loaded, I get the following error:

Controller "...resultsAction()" requires that you provide a value for the "$order" argument (because there is no default value or because there is a non optional argument after this one).

What adjustments do I need to make?

Upvotes: 2

Views: 69

Answers (1)

Matteo
Matteo

Reputation: 39470

Because TWIG render the page BEFORE you can act with js, you can't compose the right route with TWIG. You can archive your problem with two approach:

1) Make the param optional and pass it on query string as follow:

js

loadResults('asc');

  function loadResults(order) {
            return $.get('{{ url('_example_results') }}'+"?order="order, function (html) {
                $('#results').html(html);
            });
        }

controller

public function resultsAction(Request $request)
 {
      //...
      $order= $request->get('order','asc'); // second parameter is the default if is null 
 }

2) Using FOSJsRoutingBundle

Hope this help

Upvotes: 2

Related Questions