SlimZ
SlimZ

Reputation: 43

Symfony2 pass variable from controller to javascript

I have this controller.php

    $repository = $this->getDoctrine()->getManager()->getRepository('TechappStatsBundle:ParentForm');
    $data = $repository->findBy(array(),array('id' => 'desc'),1,0); 

    $formulaire = new ParentForm();

    $parent= $this->get('form.factory')->create(new ParentFormType(),$formulaire);

    if ($parent->handleRequest($request)->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $em->persist($formulaire);
        $em->flush();
    }

    return $this->render('TechappStatsBundle:Stats:index.html.twig',array("res" => $data,
        "parentform"=>$parent->createView(),));

I want to check the variable res in my view with js if it is equals to a specific value or not but I don't know how to pass it.

Upvotes: 3

Views: 3435

Answers (3)

Fernando Caraballo
Fernando Caraballo

Reputation: 583

My option always is send it in a data-value,

You can do something like

<div id="res-result" data-res="{{ res }}" style="display: none;">

The div doesn't need to be hidden, if it's something related with a div I always put it inside the div related, even if it's not hidden

And then from Jquery:

resValue = $('#res-result').data('res');

Having the JS file outside of the HTML is the cleanest way IMO

Upvotes: 3

Sachin I
Sachin I

Reputation: 1508

You can pass the parameters from controller like:

return $this->render('TechappStatsBundle:Stats:index.html.twig', array(
                "res" => "Your data here"));

And you can access the "res" parameter in index.html.twig like:

{% block js %}
 <script type="text/javascript">
var res = '{{ res }}';
alert(res);
</script>
{% endblock %}

Upvotes: 2

Dric512
Dric512

Reputation: 3729

If you want to pass data to Javascript, you can update your view to either:

  • Add an hidden input (if this is a form) that contains the value of the data
  • Add data to a DIV or P (or whatever) that you hide with CSS
  • Add an attribute to a specific field, for example data-<field>

Once you get it, you can easily fetch the value from jQuery.

Upvotes: 0

Related Questions