1

I am developing an application using symfony2. I would like to know how I can receive arguments from a template in a controller because I want to store the value of the argument in the data base. The argument will get its value in a JavaScript script inside the template and must be passed to the controller when submitting a button. This is the script:

$("MatchedTag").click(function () 
 {
       $(this).toggleClass("highlight");

       var IdOfTag = this.id;  

 }); 

The variable I want to receive in the controller is IdOfTag. How can I do this? Thanks.

2 Answers 2

4

In our applications we use two approaches.

First approach

First approach is to create the "configuration" file in twig, that would be included somewhere in header. This file contains all JS variables you would need in the script. These values of these variables are passed from the controller. Then in twig template of the "parameters" file you simply add them in appropriate places:

   <script>
       myObj.var = "{{ var_from_controller }}";
   </script>

Second approach

Another approach is to put needed variables into additional custom attributes of html tag. We usually do it, when we need to take certain route.

   <p id="myDataHolder" data-src="{{ path('MyUserBundle_ajax_route') }}">blah</p>

And then, in your JS you just parse an attribute of that tag.

Sign up to request clarification or add additional context in comments.

1 Comment

For the sake of completeness: jQuery can access the data attribute directly e.g. for the above example ('#myDataHolder').data('src') (api.jquery.com/data)
1

You can pass the variable using AJAX (take a look at $.ajax, $.post, $.get - jQuery) or add a hidden input field to form with the desired value.

Example

If you want to pass IdOfTag to /path/controller/tags (as example) using jQuery.ajax your code will looks like this:

$("MatchedTag").click(function () 
 {
       $(this).toggleClass("highlight");

       var IdOfTag = this.id;  
       $.ajax({
          url: "/path/controller/tags",
          type: "POST",
          data: { "tag_id" : idOfTag },
          success: function(data) {
             //(success) do something...
             //variable "data" contains data returned by the controller. 
          }
       });
});

Then in the controller you can get the value of idOfTag through $_POST["tag_id"]

Good look and check the links above.

2 Comments

Could you please be more specific, some example please @Karo. Thanks
I did but with not code of how I can use that in a twig template to pass the variable to the controller I am quite lost. Some help please

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.