JKLM
JKLM

Reputation: 1520

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

I need to choose a value from the radio list. If a particular value is selected then only next execution will happen other wise just update should happen.

Radio List-

<?= $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('[email protected]')
                ->setTo('[email protected]')
                ->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 its pretty easy but not finding a way to implement it

Upvotes: 4

Views: 3533

Answers (1)

Tony
Tony

Reputation: 5867

You need to check $model->status attribute for this values.

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

To make it easy I suggest to you store your values as constants. E.g.

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 controller

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

Also it will make your view more readable:

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

Upvotes: 3

Related Questions