How: Two Save Buttons In A Form?

How can I have two save buttons in a create/update form? Says one button "Save" when clicked will save and render _form.php again while another button "Save & Close" when clicked will redirect user to admin cgridview. Thank you!

Currently by default, what Gii generates is something like this:


<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>

and after create/save I render again the same form like this:


<?php $this->renderPartial('_form', array('model'=>$model)); ?>

in both create.php/update.php.

Try this code

_form.php




	<div class="row buttons">

		<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>

        <?php echo CHtml::hiddenField('save_close',0);?>

        <?php echo CHtml::submitButton('Save & Close',array('class'=>'save_close_btn')); ?>

	</div>

<script type="text/javascript">

$(document).ready(function(){

    $(".save_close_btn").on("click",function(){

        $("#save_close").val(1)

    });

});

</script>    



In controller create/update action




if($model->save()){

    if(isset($_POST['form_name']['save_close'])){

      if($_POST['form_name']['save_close']==0)

        $this->redirect(array('view','id'=>$model->id));

      else

        $this->redirect(array('admin'));

    }

}



Thank you very much, mbala. I got the logic, will try to implement like you suggest. Thanks again!

You don’t need javascript for this.

The name of a button will be submitted as POST key too, so you only have to assign the button name.

Do a var_dump($_POST) to see the incoming data.

View:




...

echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save');


echo CHtml::submitButton('Save & Close',array('name'=>'save_close_btn')); 



Controller




...

//var_dump($_POST);

...

if($model->save()){

    if(isset($_POST['save_close_btn'])) //redirect only if save & close clicked

     $this->redirect($this->createUrl('admin'));

}


$this->renderPartial('_form', array('model'=>$model));

 



Beautiful! Big thank, Joblo!