Как сделать фильтр по вычисляемому полю в GridView?

Общие вопросы по использованию второй версии фреймворка. Если не знаете как что-то сделать и это про Yii 2, вам сюда.
Ответить
ZaurK
Сообщения: 19
Зарегистрирован: 2015.01.21, 10:15

Как сделать фильтр по вычисляемому полю в GridView?

Сообщение ZaurK »

Здравствуйте! Наверное вопрос дежурный, но гугление и чтение документации мне не помогло. Пытаюсь в GridView организовать фильтр по вычисляемому полю, а точнее в модели Page есть id, page_title и id_parent. То есть при создании новой страницы можно назначать ей родительскую страницу. Подскажите, как сделать фильтрацию в колонке "Родительская страница"? У меня она ведет себя так, как будто это поле "Страница" . Прошу прощения, что привожу много кода.
Вот модель Page:

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

<?php

namespace app\models;

use Yii;
use yii\helpers\ArrayHelper;
/**
 * This is the model class for table "page".
 *
 * @property int $id
 * @property int $id_parent
 * @property string $page_title
 * @property string $page_content
 * @property int $page_num
 */
class Page extends \yii\db\ActiveRecord
{

    const STATUS_FOR_ALL = 0;
    const STATUS_FOR_ADMIN = 1;
    const STATUS_FOR_STUDENTS= 2;


    public static $humanNamesForAccess = [
      self::STATUS_FOR_ALL => 'Видно всем',
      self::STATUS_FOR_ADMIN => 'Только админ',
      self::STATUS_FOR_STUDENTS => 'Только студенты',
    ];

    public static function humanNamesForParent($id_parent)
    {
      $model = Page::find()->where(['id' => $id_parent])->one();
      return $model['page_title'];
    }

    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'page';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['id_parent', 'page_num', 'access'], 'integer'],
            [['page_title'], 'required'],
            [['page_content'], 'string'],
            [['page_title'], 'string', 'max' => 255],
            [['page_title'], 'unique'],
            [['id_parent'], 'exist', 'skipOnError' => true, 'targetClass' => Page::className(), 'targetAttribute' => ['id_parent' => 'id']],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'id_parent' => 'Родительская страница',
            'page_title' => 'Страница',
            'page_content' => 'Контент',
            'page_num' => 'Порядок',
            'access' => 'Доступ',
        ];
    }


    /**
    * @return \yii\db\ActiveQuery
    */
    public function getParent()
    {
        return $this->hasOne(Page::className(), ['id' => 'id_parent']);
    }

PageSearch:

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

<?php

namespace app\models;

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

/**
 * PageSearch represents the model behind the search form of `app\models\Page`.
 */
class PageSearch extends Page
{

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['id',  'page_num', 'access'], 'integer'],
            [['page_title', 'id_parent', 'page_content'], '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 = Page::find();

        // add conditions that should always apply here

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $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');
            return $dataProvider;
        }

        // $query->joinWith('pageBond');

        // grid filtering conditions
        $query->andFilterWhere([
            'id' => $this->id,
            // 'id_parent' => $this->id_parent,
            // 'page_title' => $this->page_title,
            'page_num' => $this->page_num,
            'access' => $this->access,
        ]);

        $query->andFilterWhere(['like', 'page_title', $this->page_title])
            ->andFilterWhere(['like', 'page_title', $this->id_parent])
            ->andFilterWhere(['like', 'access', $this->access]);

        return $dataProvider;
    }
}
Вьюшка index:

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

<?php

use yii\helpers\Html;
use yii\grid\GridView;
use app\models\Page;

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

$this->title = 'Страницы';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="page-index">

    <h1><?= Html::encode($this->title) ?></h1>
    <?php // echo $this->render('_search', ['model' => $searchModel]); ?>

    <p>
        <?= Html::a('Создать новую', ['create'], ['class' => 'btn btn-success']) ?>
    </p>


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

            'id',
            // 'id_parent',
            'page_title',

           [
               'label'=>'Родительская страница',
               'attribute'=>'id_parent',
               'content'=>function($model){
                   return get_class($model)::humanNamesForParent($model->id_parent);
               },

           ],



           [
             'attribute' => 'access',
             'label'=>'Доступ',
             'filter'=>array("0"=>"Видно всем", "1"=>"Только админ", "2"=>"Только студенты"),
             'content' => function($model){
                 return get_class($model)::$humanNamesForAccess[$model->access];
             }
           ],

            //'page_content:ntext',
            [
              'attribute' => 'page_num',
              'headerOptions' => ['width' => '100'],
              'content'=>function($model){
                  return $model->page_num;
              },
            ],

            [
            'class' => 'yii\grid\ActionColumn',
            'header'=>'Действия',
            'headerOptions' => ['width' => '10'],
            'template' => '{update} {delete}{link}',
            ],
        ],
    ]); ?>
</div>

Аватара пользователя
Alexum
Сообщения: 683
Зарегистрирован: 2016.09.26, 10:00

Re: Как сделать фильтр по вычисляемому полю в GridView?

Сообщение Alexum »

В поисковой модели запрос должен содержать связь с элиасом (т.к. поля дублируются):

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

$query = Page::find()->joinWith('parent m');
Для работы фильтра добавляем к полю элиас:

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

->andFilterWhere(['like', 'm.page_title', $this->id_parent])
Перед всеми остальными полями в методах andFilterWhere() потребуется подставить родное название таблицы модели Page, иначе будут конфликты.

В GridVIew не нужно так усложнять, достаточно использовать связь:

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

...
           [
               'label'=>'Родительская страница',
               'attribute'=>'id_parent',
               'value'=> 'parent.page_title',
           ],
...           
ZaurK
Сообщения: 19
Зарегистрирован: 2015.01.21, 10:15

Re: Как сделать фильтр по вычисляемому полю в GridView?

Сообщение ZaurK »

Alexum, спасибо, добрый человек, теперь все заработало:)
Ответить