/** * Создает DataProvider на основе переданных данных * @param $params - параметры * @return ActiveDataProvider */ public function search($params) { $query = Field::find(); $dataProvider = new ActiveDataProvider(['query' => $query, 'pagination' => ['pageSize' => $this::COUNT]]); $this->load($params); // Если валидация не пройдена, то ничего не выводить if (!$this->validate()) { $query->where('0=1'); return $dataProvider; } // Фильтрация $query->andFilterWhere(['id' => $this->id, 'template_id' => $this->template_id, 'type' => $this->type, 'min' => $this->min, 'max' => $this->max]); $query->andFilterWhere(['like', 'name', $this->name])->andFilterWhere(['like', 'param', $this->param]); return $dataProvider; }
/** * Добавляем дополнительные валидаторы * в зависимости от типа записи */ public function beforeValidate() { switch ($this->type) { case 4: // Строка // Строка case 8: // Файл (выбор с сервера) $this->validators[] = Validator::createValidator('string', $this, 'value'); break; case 9: // Регулярное выражение $field = Field::findOne($this->field_id); if ($field) { $pattern = $field->param ? $field->param : '\\w'; $this->validators[] = Validator::createValidator('match', $this, 'value', ['pattern' => $pattern]); } break; } return true; }
/** * Сохранение дополнительных полей * документа */ protected function fieldsSave() { if ($this->fields) { $field_count = 0; foreach ($this->fields as $field_id => $field) { if (isset($field['data']) && count($field['data']) && in_array($field['type'], array_keys(Field::getTypes()))) { foreach ($field['data'] as $data_id => $data) { // Перебираем все значения дополнительных полей if (in_array($field['type'], array_keys(ValueNumeric::getTypes()))) { // Числовой тип $item[$field_count] = substr_count($data_id, 'new') ? new ValueNumeric() : ValueNumeric::findOne($data_id); } elseif (in_array($field['type'], array_keys(ValueString::getTypes()))) { // Строковый тип $item[$field_count] = substr_count($data_id, 'new') ? new ValueString() : ValueString::findOne($data_id); } elseif (in_array($field['type'], array_keys(ValueText::getTypes()))) { // Текстовый тип $item[$field_count] = substr_count($data_id, 'new') ? new ValueText() : ValueText::findOne($data_id); } elseif (in_array($field['type'], array_keys(ValueDate::getTypes()))) { // Тип дата $item[$field_count] = substr_count($data_id, 'new') ? new ValueDate() : ValueDate::findOne($data_id); } $item[$field_count]->document_id = $this->id; $item[$field_count]->field_id = $field_id; $item[$field_count]->type = $field['type']; // Преобразуем дату в формат для хранения в БД if ($field['type'] == 7) { if (isset($data['value']) && $data['value'] != '') { $date = new \DateTime($data['value']); $value = $date->format('Y-m-d'); } else { $value = null; } } else { $value = isset($data['value']) ? $data['value'] : null; } $item[$field_count]->value = $value; $item[$field_count]->position = isset($data['position']) ? $data['position'] : null; // Не сохраняем если значение пустое или равно 0 когда тип Флажок if ($item[$field_count]->value == '' || $item[$field_count]->value == 0 && $item[$field_count]->type == 3) { // Удаляем если значение пустое, но оно есть в базе данных if (!$item[$field_count]->isNewrecord) { $item[$field_count]->delete(); } } else { // Сохраняем если значение не пустое $item[$field_count]->save(); } $field_count++; } } } } }
/** * Добавление значения мультиполя */ public function actionField() { $document_id = Yii::$app->request->post('document_id'); $model = $document_id ? Document::findOne($document_id) : new Document(); $field_id = Yii::$app->request->post('field_id'); $field = Field::findOne($field_id); if (!$field) { return false; } $data_id = Yii::$app->request->post('data_id'); $data_id = 'new_multi_' . $data_id; // 0 перед id нового поля свидетельствует о добавлении мультизначения $data = ['value' => '', 'position' => '']; return $this->renderAjax('@vendor/lowbase/yii2-document/views/document/_field', ['model' => $model, 'field' => $field, 'field_id' => $field_id, 'data' => $data, 'data_id' => $data_id]); }
/** * Поля шаблона * @return \yii\db\ActiveQuery */ public function getFields() { return $this->hasMany(Field::className(), ['template_id' => 'id']); }
/** * Поле * @return \yii\db\ActiveQuery */ public function getField() { return $this->hasOne(Field::className(), ['id' => 'field_id']); }
/** * Поиск модели (поле шаблона по ID) * @param integer $id - ID поля шаблона * @return Field the loaded model * @throws NotFoundHttpException if the model cannot be found */ protected function findModel($id) { if (($model = Field::findOne($id)) !== null) { return $model; } else { throw new NotFoundHttpException(Yii::t('document', 'Запрашиваемая страница не найдена')); } }
<?php /** * @package yii2-document * @author Yuri Shekhovtsov <*****@*****.**> * @copyright Copyright © Yuri Shekhovtsov, lowbase.ru, 2015 - 2016 * @version 1.0.0 */ use kartik\grid\GridView; use lowbase\document\models\Field; use yii\helpers\Html; use yii\helpers\Url; $gridColumns = [['class' => 'kartik\\grid\\SerialColumn', 'contentOptions' => ['class' => 'kartik-sheet-style'], 'width' => '30px', 'header' => '', 'headerOptions' => ['class' => 'kartik-sheet-style']], ['attribute' => 'id', 'width' => '70px'], 'name', ['attribute' => 'type', 'value' => function ($model) { return Field::getTypes()[$model->type]; }, 'filter' => Field::getTypes()], 'min', 'max', ['template' => '{update} {delete}', 'buttons' => ['update' => function ($url, $model, $key) { $options = ['title' => Yii::t('yii', 'Update'), 'aria-label' => Yii::t('yii', 'Update'), 'data-pjax' => '0']; return Html::a('<span class="glyphicon glyphicon-pencil"></span>', ['field/update', 'id' => $key], $options); }, 'delete' => function ($url, $model, $key) { $options = ['title' => Yii::t('yii', 'Delete'), 'aria-label' => Yii::t('yii', 'Delete'), 'data-confirm' => Yii::t('yii', 'Are you sure you want to delete this item?'), 'data-method' => 'post']; return Html::a('<span class="glyphicon glyphicon-trash"></span>', ['field/delete', 'id' => $key], $options); }], 'class' => 'kartik\\grid\\ActionColumn'], ['class' => 'kartik\\grid\\CheckboxColumn', 'headerOptions' => ['class' => 'kartik-sheet-style']]]; echo GridView::widget(['layout' => "{items}\n{summary}\n{pager}", 'dataProvider' => $dataProvider, 'filterModel' => $searchModel, 'columns' => $gridColumns, 'containerOptions' => ['style' => 'overflow: auto'], 'headerRowOptions' => ['class' => 'kartik-sheet-style'], 'filterRowOptions' => ['class' => 'kartik-sheet-style'], 'pjax' => false, 'panel' => ['heading' => '<i class="glyphicon glyphicon-th-list"></i> ' . Yii::t('document', 'Дополнительные поля'), 'type' => GridView::TYPE_PRIMARY, 'before' => Html::a('<span class="glyphicon glyphicon-plus"></span> ' . Yii::t('document', 'Добавить'), ['field/create', 'template_id' => $model->id], ['class' => 'btn btn-success']), 'after' => "<div class='text-right'><b>" . Yii::t('document', 'Выбранные') . ":</b> " . Html::button('<span class="glyphicon glyphicon-trash"></span> ' . Yii::t('document', 'Удалить'), ['class' => 'btn btn-danger delete-all']) . "</div>"], 'export' => ['fontAwesome' => true], 'bordered' => true, 'striped' => true, 'condensed' => true, 'persistResize' => false, 'hover' => true, 'responsive' => true]); ?> <?php $this->registerJs(' $(".delete-all").click(function(){ var keys = $(".grid-view").yiiGridView("getSelectedRows"); $.ajax({ url: "' . Url::to(['field/multidelete']) . '", type:"POST",
<div class="col-lg-6"> <?php echo $form->field($model, 'name')->textInput(['maxlength' => true]); ?> </div> <div class="col-lg-6"> <?php echo $form->field($model, 'template_id')->widget(Select2::classname(), ['data' => Template::getAll(), 'options' => ['placeholder' => '', 'id' => 'template_id'], 'pluginOptions' => ['allowClear' => true]]); ?> </div> </div> <div class="row"> <div class="col-lg-6"> <?php echo $form->field($model, 'type')->dropDownList(Field::getTypes()); ?> </div> <div class="col-lg-6"> <?php echo $form->field($model, 'param')->textInput(['maxlength' => true]); ?> </div> </div> <div class="row"> <div class="col-lg-6"> <?php echo $form->field($model, 'min')->textInput(); ?> </div>
</div> <p> <?php echo Html::a('<i class="glyphicon glyphicon-pencil"></i> ' . Yii::t('document', 'Редактировать'), ['update', 'id' => $model->id], ['class' => 'btn btn-primary']); ?> <?php echo Html::a('<i class="glyphicon glyphicon-trash"></i> ' . Yii::t('document', 'Удалить'), ['delete', 'id' => $model->id], ['class' => 'btn btn-danger', 'data' => ['confirm' => Yii::t('document', 'Вы уверены, что хотите удалить шаблон?'), 'method' => 'post']]); ?> <?php echo Html::a('<i class="glyphicon glyphicon-menu-left"></i> ' . Yii::t('document', 'Отмена'), ['index'], ['class' => 'btn btn-default']); ?> </p> <?php $html = null; if ($model->fields) { $html .= '<ul>'; foreach ($model->fields as $field) { $html .= '<li>' . Html::a($field->name, ['field/update', 'id' => $field->id]) . ' (' . Field::getTypes()[$field->type] . ')</li>'; } $html .= '</ul>'; } ?> <?php echo DetailView::widget(['model' => $model, 'attributes' => ['id', 'name', 'description:ntext', 'path', ['attribute' => Yii::t('document', 'Дополнительные поля'), 'format' => 'raw', 'value' => $html]]]); ?> </div>