温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

yii中为模型中attributes赋值失败的解决方法

发布时间:2021-01-14 10:32:52 来源:亿速云 阅读:335 作者:小新 栏目:编程语言

这篇文章将为大家详细讲解有关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); //在这里跟踪输出的数据正常,跟表单中填写的一致
        $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赋值失败的解决方法”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI