Yii2 ActiveRecord has a method to automatically load a form data into a model using load()
which is very good as it safely loads the model with data, However I am not able find a equivalent method to unload the model of all the attributes.
i.e. Is there a method to unset all attributes of a model in Yii2, like the unSetAttributes()
method in Yii 1.x ?
Currently the only way to do this seems to be either
$model->setAttributes(['attribute1'=>NULL,'attribute2' => NULL ... ]);
or
foreach ($model->attributes as $attribute) {
$model->$attribute = NULL;
}
Edit: To clarify in response to Samuel Liew's answer, while at this point I only wanted to unset all attributes which I could do by reiniting the model, I would also like to control which attributes are getting reset, which unSetAttributes
provided
You could simply create a new instance of the model.
$model = new MyModel;
Or as you can see, unsetAttributes in Yii 1 is like this, you could simply implement it in your base model:
public function unsetAttributes($names=null)
{
if($names===null)
$names=$this->attributeNames();
foreach($names as $name)
$this->$name=null;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With