Search code examples
highchartsyii2yii2-advanced-appyii2-basic-app

yii2 : dynamic dosamigos HighCharts from database


I need to generate a dynamic Highcharts get the data from database , so i tried to follow the example here :

https://github.com/2amigos/yii2-highcharts-widget

in My Controller :

public function actionReports()
{
   $data= User::find()
        ->select(['COUNT(*) AS count,gender '])
        ->groupBy(['gender'])
        ->all();
    return $this->render('reports',[
        'data' => $data,
    ]);
}

in my View :

<?php 
use dosamigos\highcharts\HighCharts;



      foreach ($data  as $user) {
          $gender= "['name'=>'".$user->gender."','data'=>[".$user->count."]],";
          print_r($gender);
       }
 echo \dosamigos\highcharts\HighCharts::widget([
'clientOptions' => [
    'chart' => [
            'type' => 'bar'
    ],
    'title' => [
         'text' => 'By Gender'
         ],

    'yAxis' => [
        'title' => [
            'text' => 'Genders'
        ]
    ],
    'series' =>[ $gender,]
]
 ]);
?>

but after that there is something wrong because No charts appears , But In $gender there is data as it has to be to make the charts work :

['name'=>'female','data'=>[1]],['name'=>'male','data'=>[4]],

`


Solution

  • Highchart require data as integer but active record returns it as string. We have to type cast data to integer.

    $data = User::find()
        ->select(['COUNT(*) AS count,gender'])
        ->groupBy('gender')
        ->asArray()
        ->all();
    
    foreach ($data  as $user) {
        $gender[] = ['name' => $user['gender'], 'data' => [(int) $user['count']]];
    }
    
    echo HighCharts::widget([
        'clientOptions' => [
            'chart' => [
                'type' => 'bar',
            ],
            'title' => [
                'text' => 'By Gender',
            ],
            'yAxis' => [
                'title' => [
                   'text' => 'Genders',
                ],
            ],
            'series' => $gender
        ],
    ]);