Multiple submit buttons in a CActiveForm

I have a CForm with three submit buttons:




    'buttons'=>array(

        'preview'=>array(

            'type'=>'submit',

            'label'=>yii::t('core','Show preview'),

        ),

        'draft'=>array(

            'type'=>'submit',

            'label'=>yii::t('core','Save draft'),

        ),

        'submit'=>array(

            'type'=>'submit',

            'label'=>yii::t('core','Submit'),

        ),

        CHtml::link(yii::t('core','Cancel'),yii::app()->homeUrl),

    ),



The ‘submitted’ CForm method allows me to distinguish which button was used and conduct actions accordingly, as you can see from this controller action:




class CreateAction extends CAction

{

    public function run()

    {

        /**

         * @var string the default layout for the view.

         */

        $this->controller->layout='column1';


        $model = new Post;

        $form = new CForm('application.forms.post.userForm', $model);


        // Uncomment the following line if AJAX validation is needed

        //$this->controller->performAjaxValidation($model);


        if ($form->submitted('preview') && $form->validate())

        {

            // Show the post preview and the form

            $model->attributes=$_POST['Post'];

            $this->controller->render('create',array('model'=>$model,'form'=>$form));

        }

        elseif(($form->submitted('submit') || $form->submitted('draft')) && $form->validate())

        {

            // Save the model

            $model->setScenario('create');

            $model->attributes=$_POST['Post'];

            $model->user_id = Yii::app()->user->id;


            // Set status

            if($form->submitted('submit'))

                $model->status=Post::STATUS_PROPOSED;

            else

                $model->status=Post::STATUS_DRAFT;


            if($model->save())

            {

                $this->controller->redirect(Yii::app()->homeUrl);

            }

        }

        else

            $this->controller->render('create',array('form'=>$form));

    }

}



So far so good. Now for the challenge: I want to turn this CForm into a CActiveForm. The problem is that it has no ‘submitted’ method, e.g. $form->submitted(‘preview’) does not work anymore. What would be the way to do this?

You can do it the "old" way…

give to every submit a unique name like


<input type="submit" name="preview"...>

and in the code you can check if that button is clicked by using


if(isset($_POST['preview']))

LOL! That was too easy. Why didn’t I think of that?!? :unsure:

Thanks for the help!