Yii,在不使用隐藏字段的情况下设置模型值


Yii, set model value without using a hidden field

我想设置模型中字段的值。字段(源)在数据库中,但表单上没有用于捕获数据的字段。我想在不创建隐藏表单字段的情况下设置字段的值。这可能吗?

谢谢!

//in controller
public function actionTest()
                {
        $model=new TestForm();
        $src = 'hello';  
        $model->source($src);
        echo $model->source; // hello
        $this->render('_form',array('model'=>$model));    
                }  

然后提交表单,当然$source不在_POST中,因为没有字段可以捕获$source

然而,我已经设置了$model->source的值,但这个值似乎不会持久存在,因为它没有保存在数据库中。

我发现解决这个问题的唯一方法是使用隐藏字段并将$source的值传递给表单。

有没有一种方法可以设置$model->source,并使该值在数据库中不通过表单?

如果在显示表单时需要设置$source的值(因为例如,当您手头有所需的数据时),则创建一个隐藏的输入控件。这没什么错;您希望在模型中保留一个非默认值,而隐藏的输入元素就是实现这一点的方法。

表单必须张贴在某个地方,在Yii中,建议张贴回同一页面。

我会这样做:

public function actionUpdate($id)
    {
        $model=$this->loadModel($id);
        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);
        if(isset($_POST['NotificationLog']))
        {
            $model->attributes=$_POST['NotificationLog'];
            if($model->save())
                $this->redirect(array('admin'));
        } else {
                  // set defaults
                  $model->source = 'hello';
            }
        $this->render('update',array(
            'model'=>$model,
        ));
    }

在模型类中的规则函数中执行类似操作:

public function rules() {
    return array(
        .
        .
        .
        array('source', 'default', 'value' => 'hello'),
    );
}

在类中使用beforeSave。参考http://www.yiiframework.com/doc/blog/1.1/en/post.create#customizing-x-9x和x-11x操作