Задать вопрос
@DoNetSSS

YII2 gridview filter?

Как сделать фильтр?

Контролер
public function actionIndex($nav = null)
    {
        $departments = Departments::getAll();
        $searchModel = new Payments();
        if ($nav == 'out') {
            $dataProvider = $searchModel->search(['type' => 1]);
        } else if ($nav == 'in') {
            $dataProvider = $searchModel->search(['type' => 0]);
        } else {
            $dataProvider = $searchModel->search([]);
        }
        return $this->render('index', [
            'departments' => $departments,
            'dataProvider' => $dataProvider,
            'searchModel' => $searchModel,
        ]);
    }


Модель
class Payments extends ActiveRecord
{
    public static function tableName()
    {
        return '{{%payments}}';
    }
    public function rules()
    {
        return [
            [['idexpense', 'type', 'name', 'price', 'date'], 'required'],
            [['idexpense', 'type', 'price', 'date'], 'integer'],
            [['name'], 'string', 'max' => 255]
        ];
    }
    public function search($params)
    {
        $query = Payments::find()->leftJoin(Expenses::tableName(), 'expenses.id = payments.idexpense')->leftJoin(Departments::tableName(), 'expenses.iddepartment = departments.id')->where($params);
        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'pagesize' => 50,    //Alternate method of disabling paging
            ],
            'sort' => [
                'attributes' => [
                    'name' => [
                        'asc' => ['name' => SORT_ASC,],
                        'desc' => ['name' => SORT_DESC,],
                    ],
                    'type' => [
                        'asc' => ['type' => SORT_ASC,],
                        'desc' => ['type' => SORT_DESC,],
                    ],
                    'price' => [
                        'asc' => ['price' => SORT_ASC,],
                        'desc' => ['price' => SORT_DESC,],
                    ],
                    'departments.name' => [
                        'asc' => ['departments.name' => SORT_ASC,],
                        'desc' => ['departments.name' => SORT_DESC,],
                    ],
                    'expenses.name' => [
                        'asc' => ['expenses.name' => SORT_ASC,],
                        'desc' => ['expenses.name' => SORT_DESC,],
                    ],
                    'date' => [
                        'asc' => ['date' => SORT_ASC,],
                        'desc' => ['date' => SORT_DESC,],
                    ],
                ],
            ],
        ]);

        return $dataProvider;
    }

    public function attributeLabels()
    {
        return array(
            'date' => 'Дата',
            'type' => 'Тип',
            'name' => 'Опис',
            'price' => 'Ціна',
            'departments.name' => 'Відділ',
            'expenses.name' => 'Рахунок',
        );
    }

    public function getExpenses()
    {
        return $this->hasOne(Expenses::className(), ['id' => 'idexpense']);
    }

    public function getDepartments()
    {
        return $this->hasOne(Departments::className(), ['id' => 'iddepartment'])
            ->viaTable(Expenses::tableName(), ['id' => 'idexpense']);
    }

    public static function addPayments($input, $id)
    {
        $data = new Payments();
        $data->idexpense = $id;
        $data->name = $input['name'];
        $data->date = time();
        $data->type = $input['type'];
        $data->price = $input['price'];
        $data->save();
    }
}


Вюшка
<?= GridView::widget([
                        'dataProvider' => $dataProvider,
                        'filterModel' => $searchModel,
                        'columns' => [
                            [
                                'attribute'=>'date',
                                'format' => 'date',
                                'content'=>function($data){
                                    return date('Y-m-j G:i', $data['date']);
                                },
                            ],
                            'departments.name',
                            'expenses.name',
                            [
                                'attribute'=>'type',
                                'format' => 'text',
                                'content'=>function($data){
                                    return $data['type'] == 0 ? "Надходження" : "Видатки";
                                }
                            ],
                            'name',
                            'price',
                        ],
                        'layout' => '{items}<div class="text-center">{pager}</div>',
                    ]); ?>
  • Вопрос задан
  • 6255 просмотров
Подписаться 2 Оценить 2 комментария
Пригласить эксперта
Ответы на вопрос 2
@DoNetSSS Автор вопроса
Извините за мой код ведь я только учусь.
Вот как надо было сделать.

Контролер
public function actionIndex($nav = null)
    {
        $departments = Departments::getAll();
        $searchModel = new Payments();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        return $this->render('index', [
            'departments' => $departments,
            'dataProvider' => $dataProvider,
            'searchModel' => $searchModel,
        ]);
    }


Модель
class Payments extends ActiveRecord
{
    public $nameDepartments;
    public $nameExpenses;

    public function rules()
    {
        return [
            [['nameDepartments', 'nameExpenses', 'type', 'price', 'date', 'name'], 'safe'],
        ];
    }

    public function search($params, $where = null)
    {
        $query = Payments::find()->leftJoin(Expenses::tableName(), 'expenses.id = payments.idexpense')->leftJoin(Departments::tableName(), 'expenses.iddepartment = departments.id')->where($where);
        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'pagesize' => 20,
            ],
            'sort' => [
                'attributes' => ['name', 'type', 'price', 'date',
                    'nameDepartments' => [
                        'asc' => ['departments.name' => SORT_ASC],
                        'desc' => ['departments.name' => SORT_DESC],
                    ],
                    'nameExpenses' => [
                        'asc' => ['expenses.name' => SORT_ASC],
                        'desc' => ['expenses.name' => SORT_DESC],
                    ],
                ],
            ],
        ]);

        $this->load($params);

        if (!$this->validate()) {
            return $dataProvider;
        }

        $query->andFilterWhere([
            'id' => $this->id,
            'type' => $this->type,
            'price' => $this->price,
            'date' => $this->date,
        ]);

        $query->andFilterWhere(['like', 'payments.name', $this->name]);
        $query->andFilterWhere(['like', 'departments.name', $this->nameDepartments]);
        $query->andFilterWhere(['like', 'expenses.name', $this->nameExpenses]);

        return $dataProvider;
    }

    public function attributeLabels()
    {
        return array(
            'date' => 'Дата',
            'type' => 'Тип',
            'name' => 'Опис',
            'price' => 'Ціна',
            'nameDepartments' => 'Відділ',
            'nameExpenses' => 'Рахунок',
        );
    }

    public function getExpenses()
    {
        return $this->hasOne(Expenses::className(), ['id' => 'idexpense']);
    }

    public function getDepartments()
    {
        return $this->hasOne(Departments::className(), ['id' => 'iddepartment'])
            ->viaTable(Expenses::tableName(), ['id' => 'idexpense']);
    }

    public static function addPayments($input, $id)
    {
        $data = new Payments();
        $data->idexpense = $id;
        $data->name = $input['name'];
        $data->date = time();
        $data->type = $input['type'];
        $data->price = $input['price'];
        $data->save();
    }
}


Вюшка
<?= GridView::widget([
                        'dataProvider' => $dataProvider,
                        'filterModel' => $searchModel,
                        'columns' => [
                            [
                                'attribute'=>'date',
                                'format' => 'date',
                                'content'=>function($data){
                                    return date('Y-m-j G:i', $data['date']);
                                },
                            ],
                            [
                                'attribute'=>'nameDepartments',
                                'format' => 'text',
                                'content'=>function($data){
                                    return $data['departments']['name'];
                                }
                            ],
                            [
                                'attribute'=>'nameExpenses',
                                'format' => 'text',
                                'content'=>function($data){
                                    return $data['expenses']['name'];
                                }
                            ],
                            [
                                'attribute'=>'type',
                                'format' => 'text',
                                'content'=>function($data){
                                    return $data['type'] == 0 ? "Надходження" : "Видатки";
                                }
                            ],
                            'name',
                            'price',
                        ],
                        'layout' => '{items}<div class="text-center">{pager}</div>',
                    ]); ?>
Ответ написан
Комментировать
@labunskyi
Вот как надо правильно делать: https://iportal.com.ua/vidzhet-dlya-dannyh-yii2-gr... Пошаговая инструкция.
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы