Menus

Monday, 19 December 2016

Mannually set a where condion for dataprovider in specific controller method



This code queryParams take from user index form.

public function actionIndex()
    {
        
            $searchModel = new StudentsSearch();
            $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

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

    }


To add additional where condition for data provider.


public function actionIndex()
    {            
            $ccid = Yii::$app->user->identity->ccid;
            $searchModel = new StudentsSearch();
            $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
            $dataProvider->query->andWhere('center_ccid = '.$ccid);         
        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

Usages:



$dataProvider = $searchModel->search([$searchModel->formName()=>['result_type'=>$result->result_type,'date'=>$result->date]]);
$query->andFilterWhere(['<>', 'role', $this->role]);
$dataProvider = $searchModel->search(Yii::$app->request->queryParams, $role = 'regular');
$searchModel = new ModelSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$dataProvider->query->andWhere(['lang'=>'ENG']);
$dataProvider = $searchModel->search(Yii::$app->request->queryParams+['EmployeeSearch' => ['<>', 'role' =>'regular']]);



Yii2 How to pass a range to search model


You can also use BETWEEN construction:
$query->andFilterWhere(['between', 'price', $this->min_price, $this->max_price]);

yii2 data provider default sorting


defaultOrder contain a array where key is a column name and value is a SORT_DESC orSORT_ASC 


$dataProvider->setSort([
'defaultOrder' => ['date'=>SORT_DESC,'result_type'=>SORT_ASC,'chance'=>SORT_ASC],
]);


$dataProvider = new ActiveDataProvider([
            'query'=> $query,
            'sort'=> [
                   'defaultOrder'=> ['your_column'=>SORT_ASC]]
       ]);





No comments:

Post a Comment