简体   繁体   中英

How to pass variable from controller to model - Yii

I am currently trying to pass a variable from the controller to my model. From a previous view I was passed $id in a button.

<a class="btn btn-info" type="button" href="index.php?r=recipient/index&id=<?php echo $data->id; ?>">Manage</a>  

From there, I have accessed $id inside my controller and used it. However, now I am creating a function in the model that needs to use that $id. I can't pass it in as a argument because it is the function beforeSave (which updates my database before I've saved a new entry) This looks like this in the model Recipient.php

// before you save the function here are the things you should do
public function beforeSave()
{
    if($this->isNewRecord)
    {

        // updates the list_id of the individual with the selected ListId

        $this->list_id = Recipient::model()->getListId;


    }
    return parent::beforeSave();
} 

Finally, I am trying to create the function getListId in the same model.

public function getListId()
{
    // my code here 
}

Is there a simple way to pass a variable from the controller to the model to use? Or, is there a way for a function in the model to access a variable passed to the controller?

Add a property to your model and set that property in your controller.

class Model
{
    public $var;
    ... more code ...
}

actionIndex($idList)
{
    $model = Model::model()->find(...);
    $model->var = $idList;
    ... more code ...
}

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