• 技术文章 >php框架 >YII

    yii中为模型的attributes赋值失败

    王林王林2020-02-26 17:14:24原创1642

    问题:

    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...
        );
    }

    更多编程相关内容,请关注php中文网编程入门栏目!

    以上就是yii中为模型的attributes赋值失败的详细内容,更多请关注php中文网其它相关文章!

    声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。
    专题推荐:yii attributes
    上一篇:yii2服务器500错误 下一篇:自己动手写 PHP MVC 框架(40节精讲/巨细/新人进阶必看)

    相关文章推荐

    • yii2高级版如何初始化• xampp怎么安装yii• yii中如何让主键自动增加• yii2服务器500错误
    1/1

    PHP中文网