
问题:
Yii框架中不能直接给模型的%ignore_a_1%赋值。
首先看一下源码:
$menuId = isset($_GET['mId']) ? $_GET['mId'] : 0;if ($menuId) { $menu = MenuTree::model()->findByPk($menuId); if(isset($_POST['MenuTree'])){ var_dump($menu->attributes); //在这里跟踪输出的数据正常,跟表单中填写的一致 $menu->attributes = $_POST['MenuTree']; //对attributes进行赋值 var_dump($menu->attributes); //输出$menu模型中的attributes,不正常,结果并不是POST接收到的值,而是数据库原有的值 if($menu->save()){ Yii::app()->user->setFlash('success',"恭喜您,修改成功,请继续!"); $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');}
(相关文章教程推荐:yii框架)
这是一个页面的action代码,看代码中的注释可以看到出现的错误,不接受POST的赋值,试过使用setAttributes函数也一样不接受,输出的还是原数据库的值,但是用updateByPk操作就可以,跟踪了一下setAttributes函数,发现函数定义如下:
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函数代码可以看到,在对attributes赋值时进行安全检查,所以想到原因可能出现模型的rules没有对那几个表单中修改的字段设置为安全,找到原因,解决方案就出来了,在model的rules中,把想要修改的字段的属性设置为安全即可。
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... );}
更多编程相关内容,请关注创想鸟编程入门栏目!
以上就是yii中为模型的attributes赋值失败的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/95385.html
微信扫一扫
支付宝扫一扫