Reputation: 628
I have an ActiveDataProvider
which includes several models. Now I need to remove one of these models. Let's say my ActiveDataProvider
called $allproducts
has 6 models. Now I need to remove model 4 from $allproducts
. How can I achieve this?
I am trying to loop in the ActiveDataProvider and in case of some condition, remove the model. In my example Model 4 (item Nr. 4) is marked for deleting.
foreach ($allproducts as $key => $product){
if ($value == 'delete') { // model 4, $value = 'delete'
unset($allproducts[$key]);
}
}
But I think this is not a proper way. Is there a specific way in yii2 to remove a model from an ActiveDataProvider
object?
What is the right procedure?
Upvotes: 1
Views: 1632
Reputation: 4607
Some may ask why doing this? why not just filter the data in query and then pass it to dataProvider? Here is why, some times you need to check something that is not MySQL related, maybe you want to call a model function to get a property that is not in the database. In that case, the best option would be something like my example:
if($dataProvider->count > 0){
$me = Yii::$app->user->id;
$models = $dataProvider->models;
foreach($models as $k => $model){
if(!in_array($me, $model->audienceUsers)){
unset($models[$k]);
}
}
$dataProvider->setModels($models);
}
Remember that you cannot directly unset a model from $dataProvider->models
Upvotes: 0
Reputation: 3008
You have two options:
1) change query adding necessary condition, for example:
$query = Model::find()->andWhere(['<>', 'value', 'deleted']);
$dataProvider = new \yii\data\ActiveDataProvider([
'query' => $query
]);
2) get all models from ActiveDataProvider with $dataProvider->model, cycle returned array and remove unwanted item, such as:
$models = $dataProvider->models;
for($k=0;$k<count($models);$k++)
{
if($models[$k]->value == 'deleted')
{
unset($models[$k]);
}
}
I prefer the first, because it is more clear.
Upvotes: 1