gridviewyii2filteringcsqldataprovider

Yii2 gridview + filtering without activerecord


I have a model (but I dont't have a table behind because I want to select information about the database itself):

namespace app\models;

use Yii;
use yii\base\Model;

class OracleTables extends Model {

    public $table_name;

    public static function getDb() {return Yii::$app->get('db_o');}
}

a controller:

namespace app\controllers;

use app\models\OracleTablesSearch;
use yii\web\Controller;
use yii\helpers\Url;
use dmstr\bootstrap\Tabs;

class OracleTablesController extends Controller {

    public function actionIndex() {
        $searchModel = new OracleTablesSearch;
        $dataProvider = $searchModel->search($_GET);

        Tabs::clearLocalStorage();

        Url::remember();
        \Yii::$app->session['__crudReturnUrl'] = null;

        return $this->render('index', [
                    'dataProvider' => $dataProvider,
                    'searchModel' => $searchModel,
        ]);
    }

}

a search model:

namespace app\models;

use Yii;
use yii\base\Model;
use app\models\OracleTables;
use yii\data\SqlDataProvider;

class OracleTablesSearch extends OracleTables {

    public function rules() {return [[['table_name'], 'safe'],];}

    public function search($params) {
        $totalCount = Yii::$app->db_o
                ->createCommand('SELECT COUNT(TABLE_NAME) FROM USER_TABLES WHERE NUM_ROWS > 0')
                ->queryScalar();

        $dataProvider = new SqlDataProvider([
            'db' => Yii::$app->db_o,
            'sql' => 'SELECT TABLE_NAME FROM USER_TABLES WHERE NUM_ROWS > 0 ORDER BY TABLE_NAME ASC',
            'totalCount' => $totalCount,
        ]);

        $this->load($params);

        return $dataProvider;
    }

}

a view file:

GridView::widget([
    'dataProvider' => $dataProvider,
    'pager' => ['class' => yii\widgets\LinkPager::className(), 'firstPageLabel' => Yii::t('app', 'First'), 'lastPageLabel' => Yii::t('app', 'Last'),],
    'filterModel' => $searchModel,
    'tableOptions' => ['class' => 'table table-striped table-bordered table-hover'],
    'headerRowOptions' => ['class' => 'x'],
    'columns' => [
        [
            'attribute' => 'TABLE_NAME',
            'contentOptions' => ['nowrap' => 'nowrap'],
            'filter' => AutoComplete::widget([
                'model' => $searchModel,
                'attribute' => 'table_name',
                'clientOptions' => [
                    'source' => [],
                    'autoFill' => true,
                    //'minLength' => 2
                ],
                'options' => ['class' => 'form-control']
            ]),
        ],
    ],
]);

it works, but without filtering, and I want filtering also. I know how to populate filter source, that's not the problem. The problem is, I can't add $sql->andFilterWhere(['like', 'table_name', $this->table_name]); to search model, because then I would need to transfer sql command outside SqlDataProvider, but then it doesn't work anymore. Look at this please (search model):

public function search($params) {
    $totalCount = Yii::$app->db_o
            ->createCommand('SELECT COUNT(TABLE_NAME) FROM USER_TABLES WHERE NUM_ROWS > 0')
            ->queryScalar();
    $sql = Yii::$app->db_o
            ->createCommand('SELECT TABLE_NAME FROM USER_TABLES WHERE NUM_ROWS > 0 ORDER BY TABLE_NAME ASC')
            ->queryColumn();

    $dataProvider = new SqlDataProvider([
        'db' => Yii::$app->db_o,
        'sql' => $sql,
        'totalCount' => $totalCount,
    ]);

    $this->load($params);

    $sql->andFilterWhere(['like', 'table_name', $this->table_name]);

    return $dataProvider;
}

if I'm doing like so, I get the following error message:

PHP Warning

preg_match() expects parameter 2 to be string, array given

in ...\vendor\yiisoft\yii2\data\SqlDataProvider.php

131 }

   $sql = $this->sql;
   $orders = [];
   $limit = $offset = null;

   if ($sort !== false) {
       $orders = $sort->getOrders();
       $pattern = '/\s+order\s+by\s+([\w\s,\.]+)$/i';
       if (preg_match($pattern, $sql, $matches)) {
           array_unshift($orders, new Expression($matches[1]));
           $sql = preg_replace($pattern, '', $sql);
       }
   }

   if ($pagination !== false) {
       $pagination->totalCount = $this->getTotalCount();
       $limit = $pagination->getLimit();
       $offset = $pagination->getOffset();

I don't find what parameter is he talking about. Or what kind of dataProvider else should I use instead? Can you please point me to the right direction? Thanks a lot!


Solution

  • I've solved it this way:

    public $table_name;
    
    public function search($params) {
        isset($_GET['wts']['table_name']) ? $table_name = $_GET['wts']['table_name'] : $table_name = "";
    
        $totalCount = Yii::$app->db_o
                ->createCommand('SELECT COUNT(TABLE_NAME) FROM USER_TABLES WHERE NUM_ROWS > 0 AND LOWER(TABLE_NAME) LIKE LOWER(:table_name)')
                ->bindValue(':table_name', '%' . $table_name . '%')
                ->queryScalar();
    
        $dataProvider = new SqlDataProvider([
            'db' => Yii::$app->db_o,
            'sql' => 'SELECT TABLE_NAME, NUM_ROWS FROM USER_TABLES WHERE NUM_ROWS > 0 AND LOWER(TABLE_NAME) LIKE LOWER(:table_name) ORDER BY TABLE_NAME ASC',
            'params' => [':table_name' => '%' . $table_name . '%'],
            'totalCount' => $totalCount,
            'pagination' => [
                'pageSize' => 15,
            ],
        ]);