简体   繁体   中英

How can I update a value in a view in Yii Framework?

Hi I have a question about yii Framework.I want to update a value in view.php and I use the following code in BilgiformuController

public function actionView($id)
    {
        $this->loadModel($id)->okunma=1;
        $this->render('view',array(
            'model'=>$this->loadModel($id),

        ));
    }

But the code, I used not working.How can I update "okunma" value in actionView.Thanks

This code:

    $this->loadModel($id)->okunma=1;
    $this->render('view',array(
        'model'=>$this->loadModel($id),

    ));

retrieves the model (object), changes the okunma property and throws it away (because the return value of loadModel() call is not being stored anywhere) and the other loadModel() call simply retrieves the model again.

I think what you meant was:

    $model = $this->loadModel($id);
    $model->okunma=1;
    $this->render('view',array(
        'model' => $model,
    ));

this way the retrieved object is stored in a variable, allowing you to modify it and pass it to render() once modified.

And if you want this change to propagate to database as well, you need to save() the model:

    $model = $this->loadModel($id);
    $model->okunma=1;
    $model->save();

You shouldn't perform update operation in views. I think you want to set model attribute and show this on view - then solution presented by @Liho is correct. If you want to save data to DB, you should assing $_POST attributes to your model:

$model = $this->loadModel($id);
$model->okunma=1;
if(isset($_POST['yourModelName'))
{
    $model->attributes = $_POST['yourModelName']);
    if($model->validate())
    {
       $model->save(false);
       // other operations, eg. redirect
    }
}
$this->render('view',array(
    'model' => $model,
));
$model = YourModel::model()->findByPk($id);
$model->okunma=1;
$model->save(false);
$this->render('view',array(
    'model' => $model,
));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM