問(wèn)題:
Yii框架中不能直接給模型的attributes賦值。
首先看一下源碼:
$menuId = isset($_GET['mId']) ? $_GET['mId'] : 0; if ($menuId) { $menu = MenuTree::model()->findByPk($menuId); if(isset($_POST['MenuTree'])){ var_dump($menu->attributes); //在這里跟蹤輸出的數(shù)據(jù)正常,跟表單中填寫(xiě)的一致 $menu->attributes = $_POST['MenuTree']; //對(duì)attributes進(jìn)行賦值 var_dump($menu->attributes); //輸出$menu模型中的attributes,不正常,結(jié)果并不是POST接收到的值,而是數(shù)據(jù)庫(kù)原有的值 if($menu->save()){ Yii::app()->user->setFlash('success',"恭喜您,修改成功,請(qǐng)繼續(xù)!"); $this->redirect(Yii::app()->createUrl('menu/contentEdit',array('mId'=>$menuId))); }else{ throw new CException("修改失敗!"); } } $this->render("contentEdit", array('menu' => $menu)); } else { throw new CHttpException('404'); }
(相關(guān)文章教程推薦:yii框架)
這是一個(gè)頁(yè)面的action代碼,看代碼中的注釋可以看到出現(xiàn)的錯(cuò)誤,不接受POST的賦值,試過(guò)使用setAttributes函數(shù)也一樣不接受,輸出的還是原數(shù)據(jù)庫(kù)的值,但是用updateByPk操作就可以,跟蹤了一下setAttributes函數(shù),發(fā)現(xiàn)函數(shù)定義如下:
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); } }
分析setAttributes函數(shù)代碼可以看到,在對(duì)attributes賦值時(shí)進(jìn)行安全檢查,所以想到原因可能出現(xiàn)模型的rules沒(méi)有對(duì)那幾個(gè)表單中修改的字段設(shè)置為安全,找到原因,解決方案就出來(lái)了,在model的rules中,把想要修改的字段的屬性設(shè)置為安全即可。
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... ); }