Поиск по дате в gridview[Решено]

Общие вопросы по использованию второй версии фреймворка. Если не знаете как что-то сделать и это про Yii 2, вам сюда.
Ответить
Аватара пользователя
svil
Сообщения: 563
Зарегистрирован: 2018.02.12, 22:41

Поиск по дате в gridview[Решено]

Сообщение svil »

Дата записывается в БД integer автоматически по поведению created_at, updated_at
Как сделать поиск по дате в гриде?
Модель

Код: Выделить всё

<?php

namespace app\models;

use app\models\FilesTag;

use app\models\Tag;

use Yii;
use yii\behaviors\TimestampBehavior;

/**
 * This is the model class for table "files".
 *
 * @property int $id
 * @property string $title Название
 * @property string $description Описание
 * @property string $type Тип
 * @property string $file Файл
 * @property string $params Параметры
 * @property int $date_create Дата добавление
 */
class Files extends \yii\db\ActiveRecord
{
    public $image;
    public $tags_array;
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'files';
    }
    public function behaviors()
    {
        return [
            TimestampBehavior::className(),
        ];
    }
    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['description', 'file'], 'string'],
           // [['date_create'], 'required'],
           //[['created_at'], 'integer'],
          //  [['created_at', 'updated_at'], 'date', 'format' => 'php:Y-m-d'],
            [['title'], 'string', 'max' => 500],
            [['type', 'params'], 'string', 'max' => 255],
            [['image'], 'safe'],
            [['image'], 'file', 'extensions'=>'jpg, gif, png, pdf'],
            [['image'], 'file', 'maxSize'=>'100000000'],
            [['title', 'params'], 'string', 'max' => 255],
            [['tags_array'], 'safe'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'title' => 'Title',
            'description' => 'Description',
            'type' => 'Type',
            'file' => 'File',
            'params' => 'Params',
            'created_at' => 'Дата создания',
            'updated_at' => 'Date Update',
            'tagsAsString' => 'Тэги',
            'tags_array' => 'Тэги',
            'image' => 'Файл',

        ];
    }



    public function getFilesTag(){
        return $this->hasMany(FilesTag::className(),['files_id'=>'id']);
    }

    public function getTags()
    {
        return $this->hasMany(Tag::className(), ['id' => 'tag_id'])->via('filesTag');
    }

    public function getTagsAsString()
    {
        $arr = \yii\helpers\ArrayHelper::map($this->tags,'id','name');
        return implode(', ',$arr);
    }
    public function afterFind()
    {
        parent::afterFind();
        $this->tags_array = $this->tags;
    }


    public function afterSave($insert, $changedAttributes)
    {
        parent::afterSave($insert, $changedAttributes);
        $arr = \yii\helpers\ArrayHelper::map($this->tags,'id','id');
        foreach ($this->tags_array as $one){
            if(!in_array($one,$arr)){
                $model = new FilesTag();
                $model->files_id = $this->id;
                $model->tag_id = $one;
                $model->save();
            }
            if(isset($arr[$one])){
                unset($arr[$one]);
            }
        }
        FilesTag::deleteAll(['tag_id'=>$arr]);
    }

    public function beforeDelete()
    {
        if (parent::beforeDelete()) {

            FilesTag::deleteAll(['files_id'=>$this->id]);
            return true;
        } else {
            return false;
        }
    }

}
Модель Search

Код: Выделить всё

<?php

namespace app\models;

use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\Files;

/**
 * FilesSearch represents the model behind the search form of `app\models\Files`.
 */
class FilesSearch extends Files
{
    public $tagsAsString;

    public $date_from;
    public $date_to;
    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['id'], 'integer'],
            [['date_from', 'date_to'], 'created_at', 'format' => 'php:Y-m-d'],
            [['title', 'description', 'type', 'file', 'params'], 'safe'],
            [['tagsAsString'], 'safe'],

        ];
    }

    /**
     * {@inheritdoc}
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = Files::find();

        // add conditions that should always apply here

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);
        $dataProvider->setSort([
            'attributes' => [
                'files.id',
                'files.params',
              //  'files.created_at',

                'tagsAsString' => [
                    'asc' => ['tag.name' => SORT_ASC],
                    'desc' => ['tag.name' => SORT_DESC],
                    'label' => 'Тэги'
                ],
                'created_at' => [
                    'asc' => ['files.created_at' => SORT_ASC],
                    'desc' => ['files.created_at' => SORT_DESC],
                    'label' => 'Дата'
                ],
            ]
        ]);
        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            $query->joinWith(['tags']);
            return $dataProvider;
        }

        // grid filtering conditions
        $query->andFilterWhere([
            'files.id' => $this->id,
         //  'files.created_at' => $this->created_at,
        ]);

        $query->andFilterWhere(['like', 'files.title', $this->title])
          //  ->andFilterWhere(['like', 'files.created_at', $this->created_at])
            ->andFilterWhere(['like', 'files.description', $this->description])
            ->andFilterWhere(['like', 'files.type', $this->type])
            ->andFilterWhere(['like', 'files.file', $this->file])
            ->andFilterWhere(['like', 'files.params', $this->params]);

//        ->andFilterWhere(['>=', 'created_at', $this->date_from ? strtotime($this->date_from.' 00:00:00') : null])
//        ->andFilterWhere(['<=', 'created_at', $this->date_to ? strtotime($this->date_to.' 23:59:59') : null]);


        $query->joinWith(['tags' => function ($q) {
            $q->where('tag.name LIKE "%' . $this->tagsAsString . '%"');
        }]);

        return $dataProvider;
    }
}
Грид

Код: Выделить всё

<?php

use yii\helpers\Html;
use yii\grid\GridView;
use kartik\widgets\DatePicker;

/* @var $this yii\web\View */
/* @var $searchModel app\models\FilesSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */

$this->title = 'Файловый менеджер';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="files-index">

    <h1><?= Html::encode($this->title) ?></h1>
<div class="row">
    <p>
        <?= Html::a('Добавить', ['create'], ['class' => 'btn btn-success']) ?>

        <?= Html::a('Тэги', ['tag/'], ['class' => 'btn btn-info']) ?>
    </p>
</div>
    <?php // echo $this->render('_search', ['model' => $searchModel]); ?>

    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'options' => ['style' => 'width:100%'],
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],

            //'id',
            //'title',
            //'description:ntext',
            //'type',
            //'file:ntext',
            [
                'attribute' => 'image',
                'format' => 'raw',
                'value' => function ($model) {
                    if ($model->params!='')
                        return '<img src="'.Yii::$app->homeUrl. '/uploads/files/'.$model->params.'" width="50px" height="auto">'; else return 'нет картинки';

                },
            ],

            [
                'filter' => DatePicker::widget([
                    'model' => $searchModel,
                    'attribute' => 'created_at',
                    'attribute2' => 'created_at',
                    'type' => DatePicker::TYPE_RANGE,
                    'separator' => '-',
                    'pluginOptions' => ['format' => 'dd.mm.yyyy'],
                ]),
                'attribute' => 'created_at',
                'format' => 'datetime',
                'label' => 'Дата создания'
            ],
           ['attribute'=>'tagsAsString', 'value'=>'tagsAsString'],

            ['class' => 'yii\grid\ActionColumn'],
            [
                'class' => 'yii\grid\ActionColumn',
                'template' => '{confirm}',
                'visibleButtons' => [
                    'confirm' => true,
                ],
                'buttons' => [
                    'confirm' => function ($dataProvider, $model) {

                        return Html::a('', ['/uploads/files/'.$model->params], ['class' => 'glyphicon glyphicon-zoom-in']);
                    },


                ],
            ],
            [
                'class' => 'yii\grid\ActionColumn',
                'template' => '{confir}',
                'visibleButtons' => [
                    'confirm' => true,
                ],
                'buttons' => [


                    'confir' => function ($dataProvider, $model) {

                        return Html::a('', ['/files/download', 'file'=>'uploads/files/'.$model->params], ['class' => 'glyphicon glyphicon-cloud-download']);

                    },
                ],
            ],
        ],
    ]); ?>


</div>
Ошибка

Код: Выделить всё

Failed to instantiate component or class "created_at".
↵
Caused by: ReflectionException
Class created_at does not exist
Последний раз редактировалось svil 2019.07.23, 18:03, всего редактировалось 1 раз.
masson
Сообщения: 545
Зарегистрирован: 2012.07.03, 15:59

Re: Поиск по дате в gridview

Сообщение masson »

Ошибки здесь :

Код: Выделить всё

    public function rules()
    {
        return [
            [['id'], 'integer'],
            [['date_from', 'date_to'], 'created_at', 'format' => 'php:Y-m-d'],
            [['title', 'description', 'type', 'file', 'params'], 'safe'],
            [['tagsAsString'], 'safe'],

        ];
    }
И здесь :

Код: Выделить всё

                'filter' => DatePicker::widget([
                    'model' => $searchModel,
                    'attribute' => 'created_at',
                    'attribute2' => 'created_at',
                    'type' => DatePicker::TYPE_RANGE,
                    'separator' => '-',
                    'pluginOptions' => ['format' => 'dd.mm.yyyy'],
                ]),
Аватара пользователя
svil
Сообщения: 563
Зарегистрирован: 2018.02.12, 22:41

Re: Поиск по дате в gridview

Сообщение svil »

Masson, спасибо. Исправила

Код: Выделить всё

public function rules()
    {
        return [
            [['id'], 'integer'],
            [['date_from', 'date_to'], 'date', 'format' => 'dd.mm.yyyy'],
            [['title', 'description', 'type', 'file', 'params'], 'safe'],
            [['tagsAsString'], 'safe'],

        ];
    }

Код: Выделить всё

[
                'filter' => DatePicker::widget([
                    'model' => $searchModel,
                    'attribute' => 'date_from',
                    'attribute2' => 'date_to',
                    'type' => DatePicker::TYPE_RANGE,
                    'separator' => '-',
                    'pluginOptions' => ['format' => 'dd.mm.yyyy'],
                ]),
Заработало. Но время на 3 часа раньше. Где это исправить?
Ответить