Search code examples
phpjqueryyii2radiobuttonlist

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


Solution

  • 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())?>