3

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

谢谢!

//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 并让这个值进入数据库而不通过表单?

4

4 回答 4

1

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

于 2012-07-12T11:53:36.563 回答
0

那么表单必须在某个地方发布,并且在 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,
        ));
    }
于 2012-07-12T11:48:55.537 回答
0

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

public function rules() {

    return array(
        .
        .
        .
        array('source', 'default', 'value' => 'hello'),
    );
}
于 2013-01-07T23:57:51.377 回答
0

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

于 2013-02-05T10:06:33.083 回答