Magento – Add confirmation pop-up to admin form “Save” button

adminadminformform-validationformsjavascript

I have custom module which adds admin form. There is a button "Save" in the form container that saves the entire form and adds some data to the database.

enter image description here

I would like to avoid situation that user accidentally clicks the button.
How to add a javascript to the button that would display (on button click) a pop-up window with text like:

"Are you sure you want save? Yes/No"?

If user clicks "Yes", then the default action for the "Save" button will be triggered and form will be submitted. If user clicks "No" then nothing happens. This will prevent accidentally saving the form.

Is there anything like this available in magento admin forms? If not, how to add this feature to my form?

class Super_Awesome_Block_Adminhtml_Example_Edit extends Mage_Adminhtml_Block_Widget_Form_Container
{
    public function __construct()
    {
        parent::__construct();

        $this->_blockGroup = 'awesome';
        $this->_controller = 'adminhtml_example';

        $this->_addButton(
            'my_button_save',
            array(
                'label' => Mage::helper('adminhtml')->__('Save'),
                'class' => 'save',
            ),
            100
        );
    }
}

Best Answer

Something like this may help you

 $base_fieldset->addField(
                'your_btn', 'button', array(
            'name' => 'your_btn',
            'label' => Mage::helper('testmodule')->__(
                    'Click on folowing link to test popup Dialog:'
            ),
            'value' => $this->helper('testmodule')->__('Test popup dialog >>'),
            'class' => 'form-button',
            'onclick' => 'javascript:openMyPopup()'
                )
        );
        $form->setUseContainer(true);
        $this->setForm($form);
        parent::_prepareForm();

Then in layout file

<?php echo $this->getFormInitScripts() ?>
<script type="text/javascript">
    function openMyPopup() {
        var url = '<?php echo $this->getUrl('adminhtml/dashboard/index') ?>?';
        if ($('browser_window') &amp;&amp; typeof(Windows) != 'undefined') {
            Windows.focus('browser_window');
            return;
        }
        var dialogWindow = Dialog.info(null, {
            closable:true,
            resizable:false,
            draggable:true,
            className:'magento',
            windowClassName:'popup-window',
            title:'Test popup Dialog',
            top:50,
            width:300,
            height:150,
            zIndex:1000,
            recenterAuto:false,
            hideEffect:Element.hide,
            showEffect:Element.show,
            id:'browser_window',
            url:url,
            onClose:function (param, el) {
                alert('onClose');
            }
        });
    }
    function closePopup() {
        Windows.close('browser_window');
    }
</script>