TenderloinSky
TenderloinSky

Reputation: 107

How to pass variable from controller to model after function execution Yii2

I have a function in a controller that when executed, check for existence of a record in a table and returns that record. This function is used as validation of a model inside the same controller. For example:

public function somethingValidate() {

    $someVariable = SomeTable::find()->where(['some_id' => $someVariable])->one();
    if ($model) {
        return $model;
    } else {
         return false;

Here is the validation part of controller:

public function actionSave() {
    $model = new TestModel() {
           if ($this->somethingValidate()) {
                try {
                  --- REST OF THE CODE ---

How can i now, pass $someVariable variable into a TestModel and manipulate the data either on save or beforeSave.

Any assistance is greatly appreciated.

Upvotes: 0

Views: 1088

Answers (1)

Prabowo Murti
Prabowo Murti

Reputation: 1341

For example, an Investment amount should be more or equal with the Proposal's min_investment value. Below is the beforeValidate() function in Investment model.

public function beforeValidate()
    {
        parent::beforeValidate();

        $proposal = Proposal::findOne($this->proposal_id);

        if ($this->amount < $proposal->min_investment)
        {
            $this->addError('amount', Yii::t('app', 'Minimum amount should be ' . $proposal->min_investment));
            return FALSE;
        }

        return TRUE;
    }

Is that what you're trying to achieve?

Upvotes: 1

Related Questions