yii中為模型的attributes賦值失敗

yii中為模型的attributes賦值失敗

問題:

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ù)正常,跟表單中填寫的一致 ????????$menu->attributes?=?$_POST['MenuTree'];?//對attributes進行賦值 ????????var_dump($menu->attributes);?//輸出$menu模型中的attributes,不正常,結(jié)果并不是POST接收到的值,而是數(shù)據(jù)庫原有的值 ????????if($menu->save()){ ????????????Yii::app()->user->setFlash('success',"恭喜您,修改成功,請繼續(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框架

這是一個頁面的action代碼,看代碼中的注釋可以看到出現(xiàn)的錯誤,不接受POST的賦值,試過使用setAttributes函數(shù)也一樣不接受,輸出的還是原數(shù)據(jù)庫的值,但是用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ù)代碼可以看到,在對attributes賦值時進行安全檢查,所以想到原因可能出現(xiàn)模型的rules沒有對那幾個表單中修改的字段設(shè)置為安全,找到原因,解決方案就出來了,在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... ????); }

更多編程相關(guān)內(nèi)容,請關(guān)注php中文網(wǎng)yii框架欄目!

? 版權(quán)聲明
THE END
喜歡就支持一下吧
點贊9 分享