3

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.

1
  • does your JS reside in the index.html.twig template? or in a separate JS file? Commented Jun 24, 2015 at 13:48

3 Answers 3

3

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

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

Comments

2

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 %}

Comments

0

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.

Comments

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.