Failed to assign the model's attributes in yii.

01-28-2024

Question:

Attributes of the model cannot be assigned directly in the Yii framework.

First look at the source code:

$menuId = isset($_GET['mId']) ? $_GET['mId'] : 0; if ($menuId) { $menu = MenuTree::model()->findByPk($menuId); if(isset($_POST['MenuTree'])){ var_dump($menu->attributes); //The data tracked here is normal, which is consistent with that filled in the form. $menu->attributes = $_POST['MenuTree']; //Assign a value to attributes var_dump($menu->attributes); //The output of attributes in the $menu model is abnormal, and the result is not the value received by POST, but the original value of the database. if($menu->save()){ Yii:: app ()-> user-> setflash ('success'), "Congratulations, the modification is successful, please continue!" ); $this->redirect(Yii::app()->createUrl('menu/contentEdit',array('mId'=>$menuId))); }else{ Thrownnewcexception ("Modification failed!" ); } } $this->render("contentEdit", array('menu' => $menu)); } else { throw new CHttpException('404'); }

(Related article tutorial recommendation: yii framework)

This is the action code of a page. Look at the comments in the code and you can see the errors. You don't accept the assignment of POST, and you don't accept it if you try to use the setAttributes function. The output is still the value of the original database, but you can use the updateByPk operation. After tracking the setAttributes function, you find that the function definition is as follows:

public function setAttributes($values,$safeOnly=true) { if(! is_array($values)) return; $attributes=array_flip($safeOnly ? $this->getSafeAttributeNames() : $this->attributeNames()); foreach($values as $name=>$value) { if(isset($attributes[$name])) $this->$name=$value; else if($safeOnly) $this->onUnsafeAttribute($name,$value); } }

By analyzing the code of the setAttributes function, we can see that the security check is carried out when assigning the attributes, so we think that the reason may be that the fields modified in those forms are not set as security in the rules of the model. If we find the reason, the solution will come out. In the rules of the model, just set the properties of the fields to be modified as security.

public function rules() { // NOTE: you should only define rules for those attributes that // will receive user inputs. return array( // more code ... array('field1 , field2 ,field3', 'safe'), //Modify the fields in here // more code ... ); }

For more programming related content, please pay attention to the gxlsystem.com Programming Introduction column!

Copyright Description:No reproduction without permission。

Knowledge sharing community for developers。

Let more developers benefit from it。

Help developers share knowledge through the Internet。

Follow us