How to make and display a form in a Dijit Dialog programmatically?

Devdatta Tengshe picture Devdatta Tengshe · Feb 21, 2013 · Viewed 13k times · Source

I've been trying to figure out how to create and display a form inside of a Dialog using Dojo 1.7.

I want my dialog to look something like this:

enter image description here

All the samples I have seen do it using Markup, but none using AMD

Answer

Frode picture Frode · Feb 21, 2013

When you create a dialog, you can use a widget (e.g. a form) as content. So, for example, you could do:

require([
    "dijit/Dialog", 
    "dijit/form/Form", 
    "dijit/form/TextBox", 
    "dijit/form/Button", 
    "dojo/domReady!" 
], function(Dialog, Form, TextBox, Button) 
{
    var form = new Form();

    new TextBox({
        placeHolder: "Name"
    }).placeAt(form.containerNode);

    new Button({
      label: "OK"
    }).placeAt(form.containerNode);

    var dia = new Dialog({
        content: form,
        title: "Dialog with form",
        style: "width: 300px; height: 300px;"
    });
    form.startup();
    dia.show();
});//~require

require() is provided by Dojo. It loads the dependencies (Form, Dialog etc) and then runs the given function which creates the widgets. However, because we include domReady! among the dependencies, Dojo makes sure the DOM is fully loaded and ready first.

Because I have dia.show() in that function too, the dialog will actually be shown as soon as the page is opened. Let's say you wanted to show the dialog when some button on your page is clicked instead:

require([
    "dijit/Dialog", 
    "dijit/form/Form", 
    "dijit/form/TextBox", 
    "dijit/form/Button",
    "dojo/on",      // Added this!
    "dojo/domReady!" 
], function(Dialog, Form, TextBox, Button, onEvent) 
{
    // ... as above, we create the dialog and form when the page loads
    // but it remains hidden until we call dia.show() ...
    form.startup();
    // dia.show();  Commented out this!

    onEvent(document.getElementById("someButtonOnYourPage"), "click", 
        function()
        {
            dia.show();
        });
});//~require