Naeem Ali
Naeem Ali

Reputation: 332

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]],

`

Upvotes: 0

Views: 676

Answers (1)

Insane Skull
Insane Skull

Reputation: 9368

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
    ],
]);

Upvotes: 2

Related Questions