這篇文章將為大家詳細(xì)講解有關(guān)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進(jìn)行賦值
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賦值時進(jìn)行安全檢查,所以想到原因可能出現(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)于“yii中為模型中attributes賦值失敗的解決方法”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,使各位可以學(xué)到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。
網(wǎng)站名稱:yii中為模型中attributes賦值失敗的解決方法-創(chuàng)新互聯(lián)
當(dāng)前網(wǎng)址:http://chinadenli.net/article18/hpsgp.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供建站公司、定制網(wǎng)站、搜索引擎優(yōu)化、App設(shè)計、網(wǎng)站收錄、品牌網(wǎng)站設(shè)計
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容