Yii графики

1. Установка

Скачать https://github.com/yiisoft/yii

консоль

cd F:\OpenServer\domains\localhost

php F:/OpenServer/domains/localhost/yii-master/framework/yiic.php webapp yiilesson

2. htaccess

localhost\yiilesson\.htaccess

Options Includes FollowSymLinks
#hide index.php
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php
--------------------------------
\protected\config\main.php

       'urlManager' => array(
            'urlFormat' => 'path',
            'showScriptName' => false,
            'rules' => array(
                // стандартное правило для обработки '/' как 'site/index'
                '' => 'site/index',
                // это пример добавления который заработал
                //'secondcontroller/<action:.*>'=>'secondcontroller/<action>',
                'user/<action:.*>' => 'user/<action>',
                //'<action:.*>'=>'site/<action>', //закомментил а то глючило с ним
                '<controller:\w+>/<id:\d+>' => '<controller>/view',
                '<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
                '<controller:\w+>/<action:\w+>' => '<controller>/<action>',
            ),
        ),

3.DDL
CREATE TABLE `data` (
  `id` INTEGER(11) NOT NULL AUTO_INCREMENT COMMENT 'id',
  `id_proc` INTEGER(11) NOT NULL COMMENT 'id процесса',
  `value` VARCHAR(20) COLLATE utf8_general_ci NOT NULL COMMENT 'значение',
  `f_time` TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) COMMENT 'время',
  PRIMARY KEY (`id`) USING BTREE,
  UNIQUE KEY `id` (`id`) USING BTREE,
  KEY `data_idx1` (`f_time`, `id_proc`) USING BTREE
) ENGINE=InnoDB
AUTO_INCREMENT=1 CHARACTER SET 'utf8' COLLATE 'utf8_general_ci'
COMMENT='таблица для графика'
;

4. контролер protected\modules\graph\controllers\GdataController.php

public $layout = '//layouts/myrenderAll'; //здесь указываем что отображать шапку не надо

где \protected\extensions\heart\views\layouts\myrender.php

--------------------
<?php /* @var $this Controller */ ?>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <meta name="language" content="en">

        <!-- blueprint CSS framework -->
        <link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->request->baseUrl; ?>/css/screen.css" media="screen, projection">
        <link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->request->baseUrl; ?>/css/print.css" media="print">
        <!--[if lt IE 8]>
        <link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->request->baseUrl; ?>/css/ie.css" media="screen, projection">
        <![endif]-->

        <link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->request->baseUrl; ?>/css/main.css">
        <link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->request->baseUrl; ?>/css/form.css">

        <title><?php echo CHtml::encode($this->pageTitle); ?></title>
    </head>
    <body>
        <div class="container" id="page">
            <?php echo $content; ?>
        </div><!-- page -->
    </body>
</html>
--------------------

5. в \protected\modules\graph\views\gdata\index.php
подключим библиотеку http://www.highcharts.com/products/highstock

============
<?php

// remember that you can actually point to the js files directly if
// your script file is outside of protected/subfolders

$path = Yii::app()->assetManager->publish(Yii::app()->basePath . '/scripts/');
Yii::app()->clientScript->registerScriptFile($path . '/highstock.js');
/* @var $this DataController */
/* @var $dataProvider CActiveDataProvider */

if (Yii::app()->request->getParam('date'))
{
    $date = Yii::app()->request->getParam('date');
    $date = date('Y-m-d', strtotime($date));
} else
{
    $date = date('Y-m-d');
}
?>
<?php

$form = $this->beginWidget('CActiveForm', array(
    'id' => 'data-form',
    // Please note: When you enable ajax validation, make sure the corresponding
    // controller action is handling ajax validation correctly.
    // There is a call to performAjaxValidation() commented in generated controller code.
    // See class documentation of CActiveForm for details on this.
    'enableAjaxValidation' => false,
        ));
?>

<?php

$this->widget('zii.widgets.jui.CJuiDatePicker', array(
    'name' => 'date',
    'language' => 'ru',
    'value' => $date,
    // additional javascript options for the date picker plugin
    'options' => array(
        'showAnim' => 'fold',
    ),
    'htmlOptions' => array(
        'style' => 'height:20px;',
        'onChange' => 'document.getElementById("data-form").submit();',
    ),
));
?>

<?php $this->renderPartial('_graph', array('date'=>$date)); ?>

<?php $this->endWidget(); ?>
============

есть и расширение http://www.yiiframework.com/extension/highcharts/
но хитрые вещи там сделать сложнее

6. в модели получим данные

    public static function data_($date)
    {
        $data = Yii::app()->db->createCommand()
                ->select('value, f_time')
                ->from('data')
                ->where("DATE_FORMAT(`f_time`, '%Y-%m-%d')=:f_time", array(':f_time' => $date))
                ->queryRow();

        return $data;
    }

7.localhost\yiilesson\protected\modules\graph\views\data\_graph.php
<div id="container"></div>
<?php 
$data = Data::data_($date);

var_dump($data);

echo $date;
?>
<script>
    $(function () {

    $.getJSON('https://www.highcharts.com/samples/data/jsonp.php?filename=aapl-c.json&callback=?', function (data) {
        // Create the chart
        $('#container').highcharts('StockChart', {


            rangeSelector : {
                selected : 1
            },

            title : {
                text : 'AAPL Stock Price'
            },

            series : [{
                name : 'AAPL',
                data : data,
                tooltip: {
                    valueDecimals: 2
                }
            }]
        });
    });

});
</script>









Комментарии

Популярные сообщения из этого блога

Пишем логи на C# (.NET). Легкий способ.

Учебник yii2

Автоматический вход пользователя на сервер посредством putty (протокол SSH)