0

I am adding a Highcharts for my project.I want to populate Javascript array from database values..

{% extends '::base.html.twig' %}

{% block stylesheets %}
  {{ parent() }}
{% endblock %}

{% block body -%}
 <div class="page-header">
     Supporters
 </div>
 <div id="container" style="min-width: 300px; height: 400px; margin: 0 auto"></div>
{% endblock %}

{% block javascripts %}
{{ parent() }}
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<script>
    $(function () {
        $('#container').highcharts({
            chart: {
                type: 'column'
            },
            title: {
                text: 'World\'s largest cities per 2014'
            },
            subtitle: {
                text: 'Source: <a href="http://en.wikipedia.org/wiki/List_of_cities_proper_by_population">Wikipedia</a>'
            },
            xAxis: {
                type: 'category',
                labels: {
                    rotation: -45,
                    style: {
                        fontSize: '13px',
                        fontFamily: 'Verdana, sans-serif'
                    }
                }
            },
            yAxis: {
                min: 0,
                title: {
                    text: 'Population (millions)'
                }
            },
            legend: {
                enabled: false
            },
            tooltip: {
                pointFormat: 'Population in 2008: <b>{point.y:.1f} millions</b>'
            },
            series: [{
                name: 'Population',

                /*data: [
                    ['Shanghai', 23.7],
                    ['Lagos', 16.1],
                    ['Instanbul', 14.2],
                    ['Karachi', 14.0],
                    ['Mumbai', 12.5],
                    ['Moscow', 12.1],
                    ['São Paulo', 11.8],
                    ['Beijing', 11.7],
                    ['Guangzhou', 11.1],
                    ['Delhi', 11.1],
                    ['Shenzhen', 10.5],
                    ['Seoul', 10.4],
                    ['Jakarta', 10.0],
                    ['Kinshasa', 9.3],
                    ['Tianjin', 9.3],
                    ['Tokyo', 9.0],
                    ['Cairo', 8.9],
                    ['Dhaka', 8.9],
                    ['Mexico City', 8.9],
                    ['Lima', 8.9]
                ],*/
                dataLabels: {
                    enabled: true,
                    rotation: -90,
                    color: '#FFFFFF',
                    align: 'right',
                    format: '{point.y:.1f}', // one decimal
                    y: 10, // 10 pixels down from the top
                    style: {
                        fontSize: '13px',
                        fontFamily: 'Verdana, sans-serif'
                    }
                }
            }]
        });
    });
</script>
{% endblock %}

I want to replace those dummy data from real values in database.I created a method that will call Doctrine and retrieve thos records.So far, I can successfully retrieve those data using Symfony's dump tool.

 $em = $this->getDoctrine()->getManager();
    $province = $em->getRepository('DuterteBundle:Grps')->createQueryBuilder('g')
      // ->join('p.region', 'r')
      // ->where('r.id =:x')
      // ->setParameter('x', 1)
       ->orderBy('g.name', 'ASC')
       ->getQuery()
       ->getResult();

   // $dat = $this->container->get('duterte.twig.province_voters_extension');
    $datas = array();//initialise array
        foreach ($province as $r) {

           // $datas[] = array($r->getName(),(int)$dat->a($r->getId()),$r->getName());
            $datas[] = array($r->getName(),123);
        }

    $data = $datas;
    echo '<pre>';
    \Doctrine\Common\Util\Debug::dump($data);
    echo '</pre>';
    return $this->render('GraphBundle:Default:group.html.twig', array(
        'data' => $data
    ));

Variable data contains real data which I want to populate in Javascript data variable.How to achieve this?I tried to use this

 <script>
  ...
   data= <?php $data ?>

   /*data: [
            ['Shanghai', 23.7],
            ['Lagos', 16.1],
            ['Instanbul', 14.2],
            ['Karachi', 14.0],
            ['Mumbai', 12.5],
    */


 </script>

Doesn't work in Twig environment

3
  • Did you try {{ data }}? Commented Sep 5, 2015 at 8:09
  • yes I already tried that, throws an error "Notice array to string conversion" Commented Sep 5, 2015 at 8:16
  • i tried {{ data|json_encode() }}, the data shows in browser console, but show error "Uncaught SyntaxError: Unexpected token &" Commented Sep 5, 2015 at 8:19

1 Answer 1

1

Try {{ data|json_encode|raw }}. By default Twig will escape any content for HTML, the |raw filter prevents that.

Also if you're running into an issue where the json_encode call is creating a JavaScript object {} rather than an array [], just call array_merge on your data before passing it to Twig:

$data = array_merge($data);

This will rekey the array to use numeric indices and will correctly be transformed into a JavaScript array when using json_encode.

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

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.