PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, January 27, 2022

[FIXED] Yii2: ActiveRecord How to unload / unset a model of all(some) attributes?

 January 27, 2022     activerecord, yii, yii2     No comments   

Issue

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


Solution

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;
}


Answered By - Samuel Liew
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home
View mobile version

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing