Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set a where condition for dataprovider in specific controller method

I am looking to set a condition only for a single action in the controller, so I don't want to change my search model.

My code looks like this:

public function actionRoles()
    {
        $searchModel = new EmployeeSearch();
        //$searchModel->query()->where('role <> regular');
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

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

The commmented row shows my condition ($searchModel->query()->where('role <> regular');), it's pretty straightforward but I have not found a solution that works online.

For reference I tried those:

  • Yii2 how does search() in SearchModel work?
  • Yii2 Modify find() Method in Model search()
  • https://github.com/yiisoft/yii2/issues/5668
  • criteria Active data provider in Yii 2
like image 651
Spurious Avatar asked Jul 31 '15 08:07

Spurious


3 Answers

You can try this way

$searchModel = new EmployeeSearch();
$searchModel->role = 'regular';
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);

In Search model :

$query->andFilterWhere(['<>', 'role', $this->role]);

Second way pass second parameter like :

$dataProvider = $searchModel->search(Yii::$app->request->queryParams, $role = 'regular');

In search model

if($role == 'regular') {
    $query->andWhere(['<>', 'role', $this->role]);
}

Another way pass other parameter like but problem in filter time:

$dataProvider = $searchModel->search(Yii::$app->request->queryParams+['EmployeeSearch' => ['<>', 'role' =>'regular']]);
like image 139
Hiren Bhut Avatar answered Sep 28 '22 00:09

Hiren Bhut


Ok, I got it done, it works this way for me:

public function actionRoles()
{
    $searchModel = new EmployeeSearch();

    $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
    $dataProvider->sort = ['defaultOrder' => ['role'=>SORT_ASC, 'fullname'=>SORT_ASC]];
    $dataProvider->query->where('employee.role <> \'regular\'');

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

Certainly a bit complicated and doing it in the model would probably be better, but I only want it to use it in this action and have a bunch of other actions with the same searchmodel but different conditions.

like image 15
Spurious Avatar answered Nov 01 '22 05:11

Spurious


You can do it this way in the Controller

$searchModel = new ModelSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$dataProvider->query->andWhere(['lang'=>'ENG']);
like image 11
Kirill Ryzhkov Avatar answered Nov 01 '22 07:11

Kirill Ryzhkov