How to close SP.UI.ModalDialog from button click in sharepoint?

mit picture mit · Oct 11, 2013 · Viewed 38.1k times · Source

I want to show Confirmation Dialog when user saves any document from EDITForm.aspx. So I have written following JavaScript code.

function PreSaveAction() {

 var _html = document.createElement();
 _html.innerHTML = "  <input  type=\"button\"  value=\"Submit\"    onclick ='javascript:SubmitDlg();'  />  <input  type=\"button\"  value=\"Cancel\" onclick =\"javascript:CloseDlg();\"     /> </td>           </tr>   </tbody> </table>";


 var options = {
            title: "Confirm",
            width: 400,
            height: 200,
            showClose: false,
            allowMaximize: false,
            autoSize: false,
            html: _html           
        };
        SP.UI.ModalDialog.showModalDialog(options); 

}

function SubmitDlg() { 
   SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.OK);


}

function CloseDlg() {
     SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.Cancel);
}

Now I have following queries.

  1. SubmitDlg and CloseDlg is not fired when clicking on Submit or Cancel.
  2. Is this right way to Submit form (SubmitDlg method ) and Cancel dialog (CloseDlg method) from modal dialog ?
  3. Also this modal dialog-box should be only appeared if no validation errors while saving record, means if any field-value is required and we have not put any value then it should display in-built red colored messages.

Thanks

Answer

Chaholl picture Chaholl · Mar 12, 2014

in the options for the modal dialog you need to pass a reference to your call back function like this:

var opt = SP.UI.$create_DialogOptions();
opt.width = 500;
opt.height = 200;
opt.url = url;
opt.dialogReturnValueCallback = MyDialogClosed;

SP.UI.ModalDialog.showModalDialog(opt);

Then in your callback function you can check the status:

function MyDialogClosed(result, value) {
if (result == SP.UI.DialogResult.Cancel) {
    //Cancel. Do whatever
}
else { //SP.UI.DialogResult.OK
    //User clicked OK. You can pickup whatever was sent back in 'value'    }

}

If you need to send stuff back from your dialog you can use this:

function okClicked()
{
    SP.UI.ModalDialog.commonModalDialogClose(1, someobject);
}

To make this work you'd need to hook-up a function to the OK button in your server side code using something like this:

protected override void OnLoad(EventArgs e)
    {
        if (Master is DialogMaster)
        {
            var dm = Master as DialogMaster;
            if(dm != null) dm.OkButton.Attributes.Add(@"onclick", @"return okClicked();");
        }

        base.OnLoad(e);
    }