SharePoint 2010: JavaScript error when creating Modal Dialog?

Moon picture Moon · Jun 8, 2011 · Viewed 32.3k times · Source

For some reason, my SharePoint's modal dialog doesn't work properly. The error I get is this:

  • In Firefox: SP.UI.$create_DialogOptions is not a function
  • In IE: Object doesn't support this property or method

Here is my code:

var options = SP.UI.$create_DialogOptions();
options.width = 525;
options.height = 300;
options.url = '/_layouts/mywork/richtexteditor.aspx';
options.dialogReturnValueCallback = Function.createDelegate(null, function (result, value)
{
    alert(result + value);
});

SP.UI.ModalDialog.showModalDialog(options);

Interestingly, when I inspect the SP.UI in Firebug, I don't see all the methods and properties.

NOTE: I am using standard Webpart (not visual) and not an application page.

Answer

user166390 picture user166390 · Jun 8, 2011

The problem is that the required SharePoint JavaScript "Library" hasn't been loaded. (The SharePoint 2010 JS is a good bit of a mess and namespaces/etc. come from all over -- the matter is further complicated with the new "on demand" loading).

The library that needs to be loaded to use SP2010 Modal Dialog interface (including the $create_DialogOptions and showModalDialog) is "sp.js".

To ensure "sp.js" is loaded:

ExecuteOrDelayUntilScriptLoaded(function () {
  // do modal dialog stuff in here (or in another function called from here, etc.)
}, "sp.js")

The call-back function is only invoked after "sp.js" (including the SP.UI.ModalDialog stuff) is guaranteed to be loaded (and it may never be called if there is a loading error).

This could also likely be solved with using a <ScriptLink> to sp.js with OnDemand specified, but I can't guarantee it: (I think there may have been issues with this approach, but I can't recall why it's not used in the project I just looked at.)

<SharePoint:ScriptLink runat="server" Name="sp.js" OnDemand="true" Localizable="false" />

See SPSOD for some more details/information.

Happy coding.