37
votes

Quite odd problem, sorry for asking, i'm quite new to Symfony/Twig. My route requires a mandatory region_id paramenter:

ajax_provinces_by_region:
  pattern: /ajax/region/{region_id}/provinces
  defaults: {_controller: SWAItaliaInCifreBundle:Ajax:provincesByRegion }
  requirements: {region_in: \d+}

The question is: how can i generate this route based on a select element in javascript (code below)?

The problem is: i can't use path and url helpers from Symfony as they require to specify the region_id parameter (this.value) i can't access because it's a javascript variable (and Twig is compiled server-side).

$(document).ready(function() {
    $('select#regions').change(function(){

        // Make an ajax call to get all region provinces
        $.ajax({
            url: // Generate the route using Twig helper
        });

    });
});
5
you can use this trick if you don't like to use bundle : stackoverflow.com/a/16584335/4008043Najd Mrabet

5 Answers

45
votes
77
votes

I know it's an old question, but just in case you don't want to install a bundle like FOSJsRoutingBundle, here's a little hack:

var url = '{{ path("yourroute", {'region_id': 'region_id'}) }}'; 
url = url.replace("region_id", this.value);

'region_id' is just used as a placeholder, then you replace it in JS with your actual variable this.value

4
votes
url:  "{{ path('SampleBundle_route',{'parameter':controller_value}) }}"

Where SampleBundle_route is a valid path defined in routing.yml or annotatins.

For testing, write this in the twig template:

<script>
    var url= "{{ path('SampleBundle_route') }}";
    alert(url);
</script>
0
votes
 * @Route("/{id}/edit", name="event_edit", options={"expose"=true})
0
votes

You can use data attribute in your HTML:

<select id="regions">
    {% for region in regions %}
        <option data-path="{{ path('ajax_provinces_by_region', {'region_id': region.id}) }}">...</option>
    {% endfor %}
</select>

then in your javascript:

$('select#regions').on('change', function() {

    let path = $(this).find(':selected').data('path')

    $.ajax({
        'url': path
    })
})