php - Yii2 GridView 与 ArrayDataProvider 搜索

标签 php yii2

我需要有关 ArrayDataProvider 搜索模型的帮助。假设我有一个数组:

$cities = [
    ['city' => "Chicago", 'year' => 1984],
    ['city' => "Washington", 'year' => 2001],
    ['city' => Manchester", 'year' => 1997],
    //and so on...
];

我创建了一个 ArrayDataProvider:
$provider = new \yii\data\ArrayDataProvider([
    'allModels' => $catalog,
    'sort' => [
        'attributes' => ['city', 'year'],
    ],
]); 

然后我创建一个 GridView:
echo \yii\grid\GridView::widget([
        'dataProvider' => $provider,
        'filterModel' => (new LibrarySearchModel()),
        'columns' => $columns,
        'showHeader' => true,
        'summary' => false,
    ]);

一切正常,但我需要在 GridView 中进行过滤。没有使用 ActiveDataProvider 的选项,我找不到任何关于如何在 ArrayDataProvider 中过滤数据的教程。
有人可以帮助我编写过滤器模型的代码或为我的案例推荐文档吗?

最佳答案

这是如何使用 ArrayDataProvider 的示例在 GridView 中带有过滤器.

让我们创建简单的 Action 。

public function actionExample()
{
    $data = new \app\models\Data();
    $provider = $data->search(Yii::$app->request->get());

    return $this->render('example', [
        'provider' => $provider,
        'filter' => $data,
    ]);
}

这是 GridView 的经典 Yii 2 方法,所以我不会解释它(您可以在上面链接的指南中找到详细信息)。

现在的观点。
<?php

echo \yii\grid\GridView::widget([
    'dataProvider' => $provider,
    'filterModel' => $filter,
    'columns' => [
        'name',
        'code',
    ],
]);

同样,与 ActiveDataProvider 方法没有什么不同。正如你在这里看到的,我们期待两列:namecode - 这些将在下面定义。
Data模型。

准备将处理数据源的模型。注释中给出了解释。
<?php

namespace app\models;

use yii\base\Model;

/**
 * Our data model extends yii\base\Model class so we can get easy to use and yet 
 * powerful Yii 2 validation mechanism.
 */
class Data extends Model
{
    /**
     * We plan to get two columns in our grid that can be filtered.
     * Add more if required. You don't have to add all of them.
     */
    public $name;
    public $code;

    /**
     * Here we can define validation rules for each filtered column.
     * See http://www.yiiframework.com/doc-2.0/guide-input-validation.html
     * for more information about validation.
     */
    public function rules()
    {
        return [
            [['name', 'code'], 'string'],
            // our columns are just simple string, nothing fancy
        ];
    }

    /**
     * In this example we keep this special property to know if columns should be 
     * filtered or not. See search() method below.
     */
    private $_filtered = false;

    /**
     * This method returns ArrayDataProvider.
     * Filtered and sorted if required.
     */
    public function search($params)
    {
        /**
         * $params is the array of GET parameters passed in the actionExample().
         * These are being loaded and validated.
         * If validation is successful _filtered property is set to true to prepare
         * data source. If not - data source is displayed without any filtering.
         */
        if ($this->load($params) && $this->validate()) {
            $this->_filtered = true;
        }

        return new \yii\data\ArrayDataProvider([
            // ArrayDataProvider here takes the actual data source
            'allModels' => $this->getData(),
            'sort' => [
                // we want our columns to be sortable:
                'attributes' => ['name', 'code'],
            ],
        ]);
    }

    /**
     * Here we are preparing the data source and applying the filters
     * if _filtered property is set to true.
     */
    protected function getData()
    {
        $data = [
            ['name' => 'Paul', 'code' => 'abc'],
            ['name' => 'John', 'code' => 'ade'],
            ['name' => 'Rick', 'code' => 'dbn'],
        ];

        if ($this->_filtered) {
            $data = array_filter($data, function ($value) {
                $conditions = [true];
                if (!empty($this->name)) {
                    $conditions[] = strpos($value['name'], $this->name) !== false;
                }
                if (!empty($this->code)) {
                    $conditions[] = strpos($value['code'], $this->code) !== false;
                }
                return array_product($conditions);
            });
        }

        return $data;
    }
}

本例中的过滤由 array_filter 处理功能。两列都过滤“数据库 LIKE”样式 - 如果列值包含搜索字符串 data数组行不会从源中删除。

让它像 and 一样工作ActiveDataProvider 中的条件我们将每列检查的 bool 结果放入 $conditions数组并在 array_filter 中返回该数组的乘积.
array_product($conditions)相当于写 $conditions[0] && $conditions[1] && $conditions[2] && ...
这一切都会产生具有两列的可过滤和可排序的 GridView 小部件。

关于php - Yii2 GridView 与 ArrayDataProvider 搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49073640/

相关文章:

php - 选择2个标签按功能设置值

javascript - PHP/SQL 上的无效表名错误

javascript - 根据下拉选择显示字段集 yii 2

yii2 - 如何更改标准 Yii2 应用程序名称 ("My Application")?

php - Yii2 中的 $with 和 $joinWith 有什么区别以及何时使用它们?

php - Mailgun API 仅适用于一封电子邮件

php - 如何让我的网站与下载管理器一起工作?

php - 如何识别网络中的节点集群

php - 向 Yii2 导航栏添加图标

Yii2:我可以使用场景为不同的 Action 指定不同的模型字段集吗?