Reputation: 436
I am using yii2 gridview application, which gives search option by default. griview search gives results if entries "contains" given values.That is if we type "ab" in search box then it will give results which contains "ab".
<?php
$query->andFilterWhere(['like', 'name', $this->name])
->andFilterWhere(['like', 'alias', $this->alias])
->andFilterWhere(['like', 'company_mail', $this->company_mail])
?>
what I want is to search for starting with "ab" ? how to do this?
Upvotes: 1
Views: 1115
Reputation: 133400
A gridview display data for dataProvider
as you can see in a tipical gridview related action like actionIndex
you can see that the dataProvider is build usig a search model as a new class for YourmodelSearc() with method search()
public function actionIndex()
{
$searchModel = new YourModelSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
and a search function tipically contail the find() and AndFliter() function for build dinamically the query for dataProvider
public function search($params)
{
$query = YourModel::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
if (!($this->load($params) && $this->validate())) {
return $dataProvider;
}
$query->andFilterWhere([
'your_numeric_col1' => $this->your_col1,
'your_numeric_col2' => $this->your_col2,
......
'id' => $this->id,
]);
$query->andFilterWhere(['like', 'your_string_colx', $this->your_string_colx])
->andFilterWhere(['like', 'your_string_coly', $this->your_string_coly])
.......
->andFilterWhere(['like', 'your_string_coln', $this->your_string_coln]);
return $dataProvider;
}
So extending, redefining or manipulating the search() or build a new customSeach() you apply multiple filter or chainging the default behavior for query filter
for the like
operator when the yii2 filtering default is not what you need you could try using the andWhere in string format.
do the fact that andFilterWhere don'k allow the use of literal conditition you can add a simple andWhere testing for null value the bottom of the query building code
$query->andFilterWhere(['like', 'your_string_colx', $this->your_string_colx])
.......
->andFilterWhere(['like', 'your_string_coln', $this->your_string_coln]);
if (isset($this->your_string_coly)){
$query->andWhere('your_string_coly like concat("%", :param1)',
[':param1'=> $this->your_string_coly])
}
return $query;
Upvotes: 1