Reputation: 852
I would like to add an aggregating option ("All options" in the example) to a dropdown filter in grid, that covers all other options, and looks like this:
All options
Option1
Option2
Option3
...
I have tried this way:
grid:
'filter' => ['All options', yii\helpers\ArrayHelper::map(app\models\RelatedModel::find()->all(), 'id', 'name'),]
ModelSearch:
if ($this->RelatedModelId == 'All options') {
$query->andFilterWhere(['in', 'RelatedModelId', \yii\helpers\ArrayHelper::getColumn(RelatedModel::find()->all(), 'id')]);
} else {
$query->andFilterWhere(['RelatedModelId' => $this->RelatedModelId ,]);
};
It works (maybe not the most beautiful solution of the world, but it's okay for me at the moment). The only thing that's disturbing me, is this 0
(or 1 sometimes, depending on how I change code) in the dropdown list:
All options
0
Option1
Option2
Option3
...
And I know it's because of the brackets []
in filter ('filter' => [...]
), but at the moment this is the only way I could achieve the functionality I need. I have no idea how to make it work witout the brackets. Is there a simple way (to put an additional tiny little option somwhow, somewhere maybe) not to show this 0
or do I have to do it completely different? It's not really a big problem that is looks like this, but would be better not to see it. Or can I put this All
into the map
function?
'filter' => yii\helpers\ArrayHelper::map(array_merge(['All options', app\models\RelatedModel::find()->all()]), 'id', 'name'),
I've also tried array_merge()
but without a success.
Any ideas? Thanks in advance!
Upvotes: 0
Views: 2861
Reputation: 33548
This:
'filter' => \yii\helpers\ArrayHelper::map(\app\models\RelatedModel::find()->all(), 'id', 'name'),
will already render empty option (with no text) for resetting choice in this drop-down list.
For search just set:
$this->andWhere(['your_field_id' => $this->your_field_id]);
in your search model and you ready to go.
Also don't forget to add this attribute as safe attribute in rules
section:
public function rules()
{
return [
['your_field_id', 'safe'],
],
}
You can see an example in CRUD generator.
If you want to customize shown text, append prompt
option to existing yii\grid\DataColum $filterInputOptions:
'filterInputOptions' => ['class' => 'form-control', 'id' => null, 'prompt' => 'All'],
Also by putting this in view you are violating MVC principle:
\yii\helpers\ArrayHelper::map(\app\models\RelatedModel::find()->all(), 'id', 'name'),
Either call this in a controller and pass as parameter to view or wrap in some getList()
method.
Upvotes: 2