Yii сохранение множества чекбоксов

1.Таблица вида

CREATE TABLE site.a_smena (
  id SERIAL,
  f_timestamp DATE DEFAULT now() NOT NULL,
  smena INTEGER NOT NULL,
  value INTEGER,
  mine_id INTEGER NOT NULL,
  lvl_id INTEGER,
  CONSTRAINT a_smena_idx UNIQUE(f_timestamp, smena, lvl_id),
  CONSTRAINT a_smena_pkey PRIMARY KEY(id),
  CONSTRAINT a_lvl_fk FOREIGN KEY (lvl_id)
    REFERENCES site.t_department(id)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION
    NOT DEFERRABLE,
  CONSTRAINT a_mine_fk FOREIGN KEY (mine_id)
    REFERENCES site.t_department(id)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION
    NOT DEFERRABLE
) 
WITH (oids = false);

COMMENT ON COLUMN site.a_smena.id
IS 'id';

COMMENT ON COLUMN site.a_smena.f_timestamp
IS 'дата';

COMMENT ON COLUMN site.a_smena.smena
IS 'смена';

COMMENT ON COLUMN site.a_smena.value
IS 'значение';

COMMENT ON COLUMN site.a_smena.mine_id
IS 'шахта';

COMMENT ON COLUMN site.a_smena.lvl_id
IS 'горизонт';

2.view

<?php
$form = $this->beginWidget('bootstrap.widgets.TbActiveForm', array(
    'id' => 'plan-form',
    'enableAjaxValidation' => false,
        ));
?>
<?php
/* @var $this QualityController */
/* @var $model Quality */

$menu = [];
require(dirname(__FILE__) . DIRECTORY_SEPARATOR . '_menu.php');
?>
<style>
    .body tr.filters{ display: none;}

    .mine { background-color: #AAAAAA }  
    .lvl { background-color: #A9BCF5 }  
    .dep { background-color: #DBD7D2 } 
    .table td{padding: 0;}

    .columns { overflow: hidden; clear: both; width: 100%; }
    .columns .left, .columns .right { float: left; }
    .columns .left { width: 80%; }
    .columns .right { width: 20%; }
    .modal-body {
        max-height: 800px; }
    .bootstrap-widget {  
        margin-bottom: 0px;}

    form {
        margin: 0;
    }
    .form-actions {
        margin-bottom: 0px;
    }
    .bootstrap-widget-content {
        padding: 20px 4px 15px;
    }

</style>

<script type="text/javascript">
    window.onload = function () {
        document.getElementById('create_time').onchange = function () {
            window.location.search = "month=" + this.value;
        };
    };
</script>
<?php
//**************************** Глобальные переменные *************************//
//****открываем сессию****//
$session = new CHttpSession;
$session->open();
//************************//
//------------------------Первоначальное опрделение месяца----------------------/
if (isset($_GET['month']))
{
    $month = Yii::app()->request->getQuery('month');
}
else
{
    $month = date('Y-m-d');
    $time = strtotime($month);
    $month = date("Y-m", strtotime("+1 month", $time));
};
?>

<?php
$box = $this->beginWidget(
        'bootstrap.widgets.TbBox', array(
    'title' => ' ' . $month . ' Смены',
    'headerIcon' => 'icon- fa fa-tasks',
    'headerButtons' => array(
        array(
            'class' => 'bootstrap.widgets.TbButtonGroup',
            'type' => 'success',
            // '', 'primary', 'info', 'success', 'warning', 'danger' or 'inverse'
            'buttons' => $this->menu
        ),
    )
        )
);
?>      
<?php
$this->widget('bootstrap.widgets.TbAlert', array(
    'block' => false, // display a larger alert block?
    'fade' => true, // use transitions?
    'closeText' => '&times;', // close link text - if set to false, no close link is displayed
    'alerts' => array(// configurations per alert type
        'success' => array('block' => true, 'fade' => true, 'closeText' => '&times;'), //success, info, warning, error or danger
        'info' => array('block' => true, 'fade' => true, 'closeText' => '&times;'), //success, info, warning, error or danger
        'warning' => array('block' => true, 'fade' => true, 'closeText' => '&times;'), //success, info, warning, error or danger
        'error' => array('block' => true, 'fade' => true, 'closeText' => '&times;'), //success, info, warning, error or danger
        'danger' => array('block' => true, 'fade' => true, 'closeText' => '&times;'), //success, info, warning, error or danger
    ),
));
?>

<?php
/* ----------------------------Управление---------------------------------- */

$this->widget('bootstrap.widgets.TbDatePicker', array(
    'value' => $month,
    'name' => 'create_time',
    'options' => array(
        'language' => 'ru',
        'format' => 'yyyy-mm',
        'autoclose' => 'true',
        'minViewMode' => 1,
        'showButtonPanel' => true,
        'keyboardNavigation' => true,
    ),
    'htmlOptions' => array(
    ),
));
?>

<?php
$myarray = [];

$myarray[] = array(
    'name' => 'name',
    'value' => '($data->name)',
    'headerHtmlOptions' => array('style' => 'text-align:center;'),
);

$number = cal_days_in_month(CAL_GREGORIAN, date('m', strtotime($month)), date('Y', strtotime($month)));

$connection = Yii::app()->db;
$sql = "
            SELECT id,
                   name,
                   id_parent,
                   COMMENT,
                   p_order,
                   hidden,
                   TYPE,
                   mine
            FROM site.t_department
            WHERE TYPE = 2
                      AND mine = 5;
                            ";
$dataReader = $connection->createCommand($sql)->query();
$rows = $dataReader->readAll();

function ischecked($month, $lvl_id, $smena, $day) //проверяем есть ли смена
{
    $day = sprintf('%02d', $day);
    $timestamp = $month . '-' . $day;
    $value = Yii::app()->db->createCommand()
            ->select('value')
            ->from('vgok_site.a_smena')
            ->where("smena = $smena
                                   AND to_char(f_timestamp, 'YYYY-MM-DD') = '$timestamp'
                                   AND lvl_id = $lvl_id")
            ->queryScalar();
    return ($value) ? 1 : null;
}

for($i = 1, $m = 1, $e = $m + 2; $i <= $number; $i++, $m+=3, $e += 3)
{
    $mergeHeaders[] = array(
        'name' => $i,
        'start' => $m, //начало сложной шапки
        'end' => $e, //конец сложной шапки 
    );
    for($c = 1; $c <= 3; $c++)
    {
        $myarray[] = array(
            'name' => '',
            'value' => 'CHtml::checkBox("cid[]",ischecked(\'' . $month . '\',$data->id,' . $c . ', ' . $i . '),array("value"=>$data->id,"id"=>"cid[$data->id][' . $i . '][' . $c . ']"))',
            'type' => 'raw',
            'htmlOptions' => array('width' => 5),
            'header' => $c,
        );
    }
}
?>

<?php
$this->widget('ext.HeaderGroupGridView', array(
    'id' => 'quality-grid',
    'dataProvider' => $model->recsearch('5'),
    'template' => "{items}",
    'fixedHeader' => true,
    'htmlOptions' => array('style' => 'width: 80%'),
    'headerOffset' => 30,
    'enableSorting' => false, //tag for sorting - true or false               
    'mergeHeaders' => $mergeHeaders,
    'columns' => $myarray,
    'rowCssClassExpression' => '$data->getRowCssClass()',
));
?>
            <?php
            echo '<div class="column" style="display:none">';
            echo CHtml::textField("id_template", 51);
            echo '</div>';
            echo '<div class="column" style="display:none">';
            echo CHtml::textField("mine", 5);
            echo '</div>';

            for($i = 1; $i <= $number; $i++) //число дней
            {
                for($c = 1; $c <= 3; $c++) //число смен
                {
                    for($x = 0, $cnt = count($rows); $x < $cnt; $x++) //число горизонтов
                    {
                        $id = $rows[$x]['id'];
                        echo '<div class="column" style="display:none">'; //запоминеам значение
                        echo CHtml::textField("elem[$id][$i][$c]", ischecked("$month", $id, $c, $i), array('id' => "elem_cid[$id][$i][$c]", 'class' => 'span1'));
                        echo '</div>';
                        ?>
                <script>
                    var name = "cid[<?php echo $id; ?>][<?php echo $i ?>][<?php echo $c ?>]";                   

                    var checkbox = document.getElementById(name);

                    checkbox.onchange = function () { //заносим значение в невидимый textField
                        if (this.checked) {
                            document.getElementById("elem_" + this.id).value = 1;
                        }
                        else
                        {
                            document.getElementById("elem_" + this.id).value = '';
                        }
                    };
                </script>
            <?php
        }
    }
}
?>



<div class="rowspan">
<?php
$this->widget('bootstrap.widgets.TbButton', array(
    'buttonType' => 'submit',
    'icon' => 'ok',
    'type' => 'success',
    'label' => ($new) ? 'Создать' : 'Сохранить',
));
?>
</div>
    <?php $this->endWidget(); ?>
    <?php $this->endWidget(); ?>
 
3.контролер
public function actionSmen()
    {
        $model = new Quality('mysearch');
        $model->unsetAttributes();  // clear any default values

        if (isset($_POST['elem']))
        {
            $Elems = Yii::app()->request->getParam('elem');
            $month = Yii::app()->request->getParam('create_time'); //месяц
       
            $mine = Yii::app()->request->getParam('mine');
         
            $connection = Yii::app()->db;
            $sql = "                
                    DELETE FROM 
                      site.a_smena 
                    WHERE 
                      to_char(f_timestamp, 'YYYY-MM') = '$month'                                  
                                    ";
            $dataReader = $connection->createCommand($sql)->execute(); //удаляем все записи за месяц

            $cnt = max(array_keys($Elems));
            $min = min(array_keys($Elems));
           
            for($i = $min; $i <= $cnt; $i++) //горизонты
            {               
                $lvlElem = $Elems[$i];
             
                for($c = 0, $cntg = count($lvlElem); $c <= $cntg; $c++) //дни
                {
                    $dayElem = $lvlElem[$c];
                    $day = sprintf('%02d', $c);

                    for($x = 0, $cntl = count($dayElem); $x <= $cntl; $x++) //смены
                    {                     
                        $elem = $dayElem[$x];
                        if ($elem)
                        {
                            $timestamp = $month . '-' . $day;
                            $sql = "                
                                INSERT INTO site.a_smena ( f_timestamp, smena, value, mine_id, lvl_id)
                                VALUES ( '$timestamp',
                                         $x,
                                         1,
                                         $mine,
                                         $i)                                         
                            ";
                            $dataReader = $connection->createCommand($sql)->execute();
                        }
                    }
                }
            }
        }

        $this->render('smen', array(
            'model' => $model,
        ));
    }

Комментарии

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

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

Учебник yii2