Search code examples
javascriptphpmysqlyii2-advanced-appcanvasjs

Canvas js how to push data from database to chart in Yii2


I am working on yii2. I have installed the canvas js library, tried to run the sample chart example. Now I want to push data from my database. I am able to view single data from my DB, but I want to put all the data when the database is updated i.e. I have a button and on that button click my table is updated during that period I want to update my chart also to show the updated value(s).

Note: Chart should show the trend

Below is my controller code from which I am inserting the data into my table

public function actionData()
{
    try {
        $cust_met_data = Yii::$app->db->createCommand(
            "SELECT m.`meter_id` , m.`msn` , 
                  m.`cust_id` , m.`device_id` FROM `mdc_meter_cust_rel` m ")->queryAll();
    } catch (Exception $e) {
    }

    $slave_id = $cust_met_data[0]['device_id'];
    $address = 0;
    $count = 14;
    $msn = $cust_met_data[0]['msn'];
    $cust_id = $cust_met_data[0]['cust_id'];

    // my base URL
    $api_url = 'https://localhost:44337/api/rtu/GetData/' . $slave_id . '/' . $address . '/' . $count;


    $curl = curl_init($api_url);

    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_TIMEOUT, 1000);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

    $curl_response = curl_exec($curl);

    $json = json_decode($curl_response);

    if($json->{0} == '06')
    {
        Yii::$app->getSession()->setFlash('error', '
 <div class="alert alert-error alert-dismissable">
 <button aria-hidden="true" data-dismiss="alert" class="close" type="button">×</button>
 <strong>No Communication! </strong> Meter Data is Unavailable.</div>');

        return $this->redirect(['index']);
    }
    else
    {
        $vol_1 = $json->{0};
        $vol_2 = $json->{1};
        $vol_3 = $json->{2};
        $curr_1 = $json->{3};
        $curr_2 = $json->{4};
        $curr_3 = $json->{5};
        $kwh = $json->{6};

        $model = new MdcmetersData();
        $model->load(Yii::$app->request->post());
        $model->data_date_time = date('Y-m-d H:i:s');
        $model->device_id = $slave_id;
        $model->msn = $msn;
        $model->cust_id = $cust_id;
        $model->voltage_p1 = $vol_1;
        $model->voltage_p2 = $vol_2;
        $model->voltage_p3 = $vol_3;
        $model->current_p1 = $curr_1;
        $model->current_p2 = $curr_2;
        $model->current_p3 = $curr_3;
        $model->kwh = $kwh;

        if($model->save())
        {
            return $this->redirect(['index', 'model' => $model]);
        }
        else
        {
            return $this->redirect(['index']);

        }

    }




}

Index.php

<script type="text/javascript" src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<?PHP
  $model = $dataProvider->getModels()[0];
  $model['data_date_time'];

  $dataPoints1 = array(
  array("label"=> $model['data_date_time'], "y"=> $model['kwh']),

  );

 ?>
<div id="chartContainer1" style="width: 100%; height: 300px;display: inline-block;"></div>
<p>
    <?= Html::a('Get Meter Data', ['data'], ['class' => 'btn btn-success']) ?>
</p>



<script>
window.onload = function () {
 var chart = new CanvasJS.Chart("chartContainer1", {
    animationEnabled: true,
    theme: "light2",
    title:{
        text: "kWh of Meter"
    },
    legend:{
        cursor: "pointer",
        verticalAlign: "center",
        horizontalAlign: "right",
        itemclick: toggleDataSeries
    },
    data: [{
        type: "column",
        name: "kwh",
        indexLabel: "{y}",

        showInLegend: true,
        dataPoints: <?php echo json_encode($dataPoints1, JSON_NUMERIC_CHECK); ?>
    }
    ]
});
chart.render();

function toggleDataSeries(e){
    e.dataSeries.visible = !(typeof (e.dataSeries.visible) === "undefined" || e.dataSeries.visible);
    chart.render();
}
};

Chart output

enter image description here

It's a single value shown but in actual I have more than one value.

I have searched for the solution but all I found is the traditional way to push data. i.e. in PHP, I have to run a query and then perform an action on that. A sample is shown here PHP Chart Data from Database

How can I do it? Any help would be highly appreciated


Solution

  • Because you are getting the first record to populate from the $dataProvider

    $model = $dataProvider->getModels()[0];
    

    it should be

    $model = $dataProvider->getModels();
    

    Apart from it I would keep things simple and pull the data by making a separate static function in the model and call it from the controller and pass the data on to the view to the charts to display.