Small tweak on a JS file : initialisation before loop

14 views
Skip to first unread message

GregLL

unread,
Aug 27, 2018, 10:33:19 AM8/27/18
to Google Visualization API
I have downloaded a small code snippet that allows me to filter a google chart series when the user clicks on the legend.

Basically, I have the code that generates the graph and then an event listener that hides/shows series depending on the user click.

What I would like to do is to either trigger the event within the code or to loop through the series to hide some of them depending on the parameter.

Here is my code :

function get_performances_graph_data(){
    $values
= $kpis_array = array();
    $kpis
= get_kpi_array();
   
global $wpdb;

    $i
= 0;
   
foreach( $kpis as $k ){
       
if( !isset( $k['hidden'] ) ){
            $h
= $k['header'];
            $format
= 'number';
           
if( isset( $k['format'] ) )
                $format
= $k['format'];
            $temp
= array(  'label' => $h , 'slug' => toUri( $h ) , 'id' => $i , 'format' => $format );
            $kpis_array
[] = $temp;
            $i
++;
       
}
   
}

    $req
= "SELECT * FROM " . gq_prefix() . "performances ORDER BY date ASC";
   
// debug_var( $req );
    $performances
= $wpdb->get_results( $req );
    $prev_val
= array();
   
foreach( $performances as $p ){
       
// debug_var( $p );
       
foreach( $kpis as $k ){
           
if( !isset( $k['hidden'] ) ){
                $slug
= toUri( $k['header'] );
                $val
= '';
               
if( isset( $p->$slug ) )
                    $val
= $p->$slug;
               
if( isset( $k['format'] ) && $k['format'] == 'date' ){
                    $date_str
= explode( ";" , str_replace( '-' , ';' , $val ) );
                    $y
= $date_str[0];
                    $m
= $date_str[1] - 1;
                    $d
= $date_str[2];
                    $row
[$slug] = "new Date($y, $m, $d)";
               
}
               
else{
                   
if( empty( $val ) ){
                       
if( isset( $prev_val[$slug] ) )
                            $val
= $prev_val[$slug];
                   
}
                   
else
                        $prev_val
[$slug] = $val;
                    $row
[$slug] = $val;
               
}
               
// debug_var( $val , $slug );
           
}
       
}
        $values
[] = $row;
   
}

   
// debug_var( $values );
   
return array( 'values' => $values , 'kpis' => $kpis_array );
}
function get_ticks( $dataset ){
   
// debug_var( $dataset );
    $first
= reset( $dataset )['date'];
    $last
= end( $dataset )['date'];
    $dates
= array( $first );

   
// debug_var( $last , $first );

    $f_s
= explode( ';' , str_replace( 'new Date(' , '' , str_replace( ')' , '' ,  str_replace( ', ' , ';' , $first ) ) ) );
    $y
= $f_s[0];
    $m
= $f_s[1];
   
// $d = $f_s[2];
   
// debug_var( $f_s );
    $l_s
= explode( ';' , str_replace( 'new Date(' , '' , str_replace( ')' , '' ,  str_replace( ', ' , ';' , $last ) ) ) );
    $y_l
= $l_s[0];
    $m_l
= $l_s[1];
   
// $d = $l_s[2];
   
// debug_var( $l_s );

    $out
= false;
   
while( !$out ){
       
if( $m >= 6 ){
           
// debug_var( $m , 1 );
            $m
= 0;
           
// debug_var( $m , 11 );
            $y
++;
       
}
       
else{
           
// debug_var( $m , 2  );
            $m
= 6;
       
}
       
// debug_var( $y , $y_l );
       
// debug_var( $m , $m_l );
       
if( $y > $y_l || ( $y == $y_l && $m > $m_l ) )
            $out
= true;
       
else
            $dates
[] = "$y,0$m,01";

   
}
    $dates
[] = $last;

    $output
= '[';
   
foreach( $dates as $d ){
        $output
.= "new Date($d), "; // 2014,3,15
   
}
    $output
= rtrim( $output , ', ' );
    $output
.= ']';

   
return $output ;
}
function display_graph( $atts ){
    $dataset
= array( 'all' );
   
if( isset( $atts['dataset'] ) )
        $dataset
= $atts['dataset']; // string

    $dataset
= array( 'date' , 'cac-40' , 'marches-actions' , 'fonds-en-euros' );

    $output
= '';

   
// $graph_type = 'ScatterChart';
    $graph_type
= 'LineChart';
    $data
= get_performances_graph_data();
   
// debug_var( $data );

    $data_values
= $data['values']; // Contains the dataset
    $data_kpis
= $data['kpis']; // Contains each KPI's ID

    $ticks_string
= get_ticks( $data_values );

    $options
= "
            chartArea: {
                width: '90%'
            },
            // pointSize: 1,
            legend:{
                maxLines: 3,
                position: 'top',
                textStyle: {
                    fontSize: 15
                }
            },
            hAxis: {
                fontSize: 10,
                format: 'MMM y',
                gridlines: {
                    color: '#eaeaea',
                    count: 15
                },
                ticks: $ticks_string,
            },
            crosshair: {
                trigger: 'selection',
                orientation: 'vertical',
                color: '#143278',
            }
    "
;

    $output
.= '<div id="chart_div"></div>';
    $output
.= '
    <script type="text/javascript" src="https://www.google.com/jsapi?autoload={\'modules\':[{\'name\':\'visualization\',\'version\':\'1.1\',\'packages\':[\'corechart\']}]}"></script>

    <script>
      google.load("visualization", "1", {packages:["corechart"]});
      google.setOnLoadCallback(drawChart);
      function drawChart() {
        var data = new google.visualization.DataTable();'
. "\n";

   
foreach( $data_kpis as $d ){
        $output
.= "data.addColumn('" . $d['format'] . "', '" . $d['label'] . "');\n";
   
}

   
// $rows = "\ndata.addRows([\n";
    $rows
= '';
   
foreach( $data_values as $d ){
       
// $row = "[";
        $row
= "\ndata.addRow([";
       
foreach( $data_kpis as $k ){
            $slug
= $k['slug'];
            $val
= $d[$slug];
           
// debug_var( $val );
           
if( isset( $k['format'] ) && $k['format'] == 'date' ){
                $row
.= "$val,\n";
           
}
           
else{
               
if( !isset( $val ) )
                    $val
= "''";
                $row
.= "// $slug\n$val, \n";
               
// $row .= "$val,\n";
           
}
       
}
       
// $rows .= rtrim( rtrim( $row , ',') , ",\n") . "],\n";
        $rows
.= rtrim( rtrim( $row , ',') , ",\n") . "]);\n";
   
}
   
// $output .= rtrim( rtrim( $rows , ',') , ",\n") . "]);\n";
    $output
.= rtrim( rtrim( $rows , ',') , ",\n") . "\n";
    $output
.= '

        var options = {'
. $options . '};
        var chart = new google.visualization.'
. $graph_type . '(document.getElementById(\'chart_div\'));
        chart.draw(data, options);

        var columns = [];
        var series = {};
        for (var i = 0; i < data.getNumberOfColumns(); i++) {
            // HERE, I need to select which column is in $dataset (if $dataset != array("all")) and hide the rest
            columns.push(i);
            if (i > 0) {
                series[i - 1] = {};
            }
        }

        console.dir(series);
        console.dir(columns);

        var options = {
            series: series,
            '
. $options . '
        }

        var view = new google.visualization.DataView(data);
        view.setColumns(columns);
        chart.draw(view, options);

        google.visualization.events.addListener(chart, \'select\', function () {
            var sel = chart.getSelection();
            // if selection length is 0, we deselected an element
            if (sel.length > 0) {
                // if row is undefined, we clicked on the legend
                if (sel[0].row === null) {
                    var col = sel[0].column;
                    if (columns[col] == col) {
                        // hide the data series
                        columns[col] = {
                            label: data.getColumnLabel(col),
                            type: data.getColumnType(col),
                            calc: function () {
                                return null;
                            }
                        };

                        // grey out the legend entry
                        series[col - 1].color = \'#CCCCCC\';
                    }
                    else {
                        // show the data series
                        columns[col] = col;
                        series[col - 1].color = null;
                    }
                    var view = new google.visualization.DataView(data);
                    view.setColumns(columns);
                    chart.draw(view, options);

                    console.log( series );
                    console.log( columns );

                }
            }
        });

      }</script>
    '
;

   
return $output;
}


My function is parsing an array called $dataset. The default value is "all", but I've added a small line of code in order to test with a pattern that could be parsed in the future.
$dataset = array( 'date' , 'cac-40' , 'marches-actions' , 'fonds-en-euros' );



As you can see in my code, at some point I get arrays of series and columns :

var columns = [];
       
var series = {};
       
for (var i = 0; i < data.getNumberOfColumns(); i++) {
           
// HERE, I need to select which column is in $dataset (if $dataset != array("all")) and hide the rest
            columns
.push(i);
           
if (i > 0) {
                series
[i - 1] = {};
           
}
       
}

        console
.dir(series);
        console
.dir(columns);


At the end of the script, I have a loop that hides/shows columns on click event :

google.visualization.events.addListener(chart, \'select\', function () {
            var sel = chart.getSelection();
            // if selection length is 0, we deselected an element
            if (sel.length > 0) {
                // if row is undefined, we clicked on the legend
                if (sel[0].row === null) {
                    var col = sel[0].column;
                    if (columns[col] == col) {
                        // hide the data series
                        columns[col] = {
                            label: data.getColumnLabel(col),
                            type: data.getColumnType(col),
                            calc: function () {
                                return null;
                            }
                        };

                        // grey out the legend entry
                        series[col - 1].color = \'#CCCCCC\';
                    }
                    else {
                        // show the data series
                        columns[col] = col;
                        series[col - 1].color = null;
                    }
                    var view = new google.visualization.DataView(data);
                    view.setColumns(columns);
                    chart.draw(view, options);

                    console.log( series );
                    console.log( columns );

                }
            }
        });


This is the part where I'm lost.

I was thinking that where I get the first set of series and columns, I could hide some of them either by looping within them and checking against the &atts['dataset'] parameter or maybe changing them directly using the index.

Thank you very much for your help and time !

Greg





Reply all
Reply to author
Forward
0 new messages