Yii2: How to use switch value in controller for further execution?

I need to select a value from a list of radio stations. If a specific value is selected, then only the next execution will be executed, but another must happen.

List of radio stations -

<?= $form->field($model, 'status')->radioList(array('Approved'=>'Approved','Digital'=>'Digital','CDP'=>'CDP','Print'=>'Print','Other Process'=>'Other Process','Packing'=>'Packing','Dispatch'=>'Dispatch'),['class' => $model->status ? 'btn-group' : 'btn btn-default'],['id'=>'radioButtons'] );   

      

Controller -

public function actionCreate()
    {
        $model = new Status();


        if ($model->load(Yii::$app->request->post())) 
        {
               if(radio button value is approved or dispatch below code should execute )
              {
                Yii::$app->mailer->compose()
                ->setFrom('abc@gmail.com')
                ->setTo('qwer@hotmail.com')
                ->setSubject('Message subject')
                ->setTextBody('Plain text content')
                ->setHtmlBody('<b>HTML content</b>')
                ->send();
                }
                  else{ 
                         (just update the form )
                    }

                $model->save();
            return $this->redirect(['view', 'id' => $model->id]);
        } 
        else 
        {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

      

I know it quite easily, but haven't found a way to implement it

+3


source to share


1 answer


The attribute must be checked for these values $model->status

.

if($model->status == 'Approved' || $model->status == 'Dispatch')
{
    //do stuff
}

      

To keep things simple, I suggest you store your values ​​as constants. For example.

class MyActiveRecord extends \yii\db\ActiveRecord
{
    const STATUS_APPROVED = 1;
    const STATUS_DISPATCH = 2;
    //and so on

    public static function getStatusList()
    {
         return [
             self::STATUS_APPROVED => 'Approved',
             self::STATUS_DISPATCH => 'Dispatch',
             //other values
         ];
    }
}

      



And then in the controller

if($model->status == MyActiveRecord::STATUS_APPROVED ||
   $model->status == MyActiveRecord::STATUS_DISPATCH)
{
    //do stuff
}

      

It will also make your view more readable:

<?= $form->field($model, 'status')->radioList($model->getStatusList())?>

      

+1


source







All Articles