Top Banner

of 20

ExtJS Forms

Apr 03, 2018

Download

Documents

Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
  • 7/28/2019 ExtJS Forms

    1/20

    Ext JS 3 Forms GuideDavid FeinbergCopyright 2011 Sencha, Inc. All rights reserved.

  • 7/28/2019 ExtJS Forms

    2/20

    iii

    Table of Contents6. Forms ................................................ ........................................................ ................. 1

    Overview ....................................................... ........................................................ .. 1Simple Form Layout ................................................................................................. 1Multi Column Form Layout ....................................................................................... 3Form Validation ....................................................... ................................................ 5Form Submission ..................................................................................................... 8Loading Form Data ..................................................... ........................................... 12Additional Form Resources ................................................................................. ... 17

  • 7/28/2019 ExtJS Forms

    3/20

    iv

    List of Figures6.1. Simple Form Layout .................................................................................................. 16.2. Multi-Column Form Layout ............................. ....................................................... ..... 3

  • 7/28/2019 ExtJS Forms

    4/20

    1

    FormsOverview

    This guide provides examples covering the full life cycle of building form based interfaces withExt JS components. Topics include; form layout, validation, submission and data re-population.Each example introduces core Ext JS concepts and components designed for creating formbased application interfaces.

    Simple Form LayoutTo get started creating forms with Ext JS we'll layout a simple contact form inside aExt.form.FormPanel . Using FormPanel is the recommended approach for creating formsbecause it provides built-in integration with two important classes for working with forms(Ext.layout.FormLayout ) and ( Ex.form.BasicForm ). To help make it easier to position formlabels and fields Ext.form.FormPanel uses Ext.layout.FormLayout as the default layout

    manager. This example demonstrates some of the built-in FormLayout configuration optionsand methods you can use to control form components.

    Figure 6.1. Simple Form Layout

    Ext.onReady( function () {

    new Ext.form.FormPanel({ // 1width: 400,height: 300,frame: true,bodyStyle: 'padding:10px' , // 2

    http://dev.sencha.com/deploy/dev/docs/?class=Ext.form.BasicFormhttp://dev.sencha.com/deploy/dev/docs/?class=Ext.layout.FormLayouthttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.FormPanel
  • 7/28/2019 ExtJS Forms

    5/20

    Forms

    2

    title: 'Simple Form Layout' ,defaults: {width: '100%' }, // 3labelAlign: 'top' , // 4items:[{

    xtype: 'textfield' , // 5fieldLabel: 'First Name' ,

    name: 'firs tName'},{

    xtype: 'textfield' ,fieldLabel: 'Last Name' ,name: 'lastName'

    },{

    xtype: 'textfield' ,fieldLabel: 'Email' ,name: 'email'

    },{

    xtype: 'textarea' , // 6 fieldLabel: 'Message' ,name: 'message'height: 65

    }],renderTo: Ext.getBody()

    });});

    1. A new Ext.form.FormPanel is created to hold the form elements. FormPanel extendsExt.Panel so it uses many of the same configuration options in addition to a handful ofoptions designed specifically for forms.

    2. A CSS string is passed to bodyStyle to add 10 pixels of padding to the inside body area ofthe FormPanel. This improves the readability of the form and keeps form components fromdisplaying right up against the edge of the FormPanel.

    3. Setting the defaults config option of the FormPanel with a width of 100 pixels willautomatically apply this width value to all components added to the FormPanel eitherthrough the items configuration option (as shown here) or the add and insert methods.

    4. The labelAlign option is changed from the default value of left to top to demonstrate how thisconfiguration option changes the position of field labels. Here we're displaying the labelsabove the form fields to help make the form easier to scan.

    5. Three text form fields are configured by specifying the textfield xtype which automaticallycreates an instance of Ext.form.TextField and displays a label using the value set for thefieldLabel configuration option. The value set for the name config option is used in theunderlying HTML and passed to the server when the form is submitted. All the widths ofthese fields are automatically set to 100% because of the defaults configuration option seton the FormPanel.

    6. A multi-line text field is displayed using the textarea xtype which generates an instance ofExt.form.TextArea . Although the width is automatically set to 100% because of the defaults

    http://dev.sencha.com/deploy/dev/docs/?class=Ext.form.TextAreahttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.TextAreahttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.BasicForm&member=inserthttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.BasicForm&member=inserthttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.BasicForm&member=addhttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.BasicForm&member=itemshttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.FormPanel&member=defaultshttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.FormPanel
  • 7/28/2019 ExtJS Forms

    6/20

    Forms

    3

    config option set on the FormPanel the height of the field is set here using the height configoption of Ext.form.TextArea.

    This example showed a simple FormPanel created using xtypes to generate single and multi-line text fields. The FormLayout automatically arranged the fields vertically inside the Panelwhile changing the default value of labelAlign from left to top displayed form labels neatlyabove each field.

    Multi Column Form LayoutThis example demonstrates how to display a form using a familiar column style layout toorganize form fields. It also shows some of the different form components bundled with Ext JSincluding an Ext.form.RadioGroup, Ext.form.CheckboxGroup and Ext.form.HtmlEditor.

    Figure 6.2. Multi-Column Form Layout

    Ext.onReady( function () {

    new Ext.form.FormPanel({width: 430,height: 330,frame: true,bodyStyle: 'padding:5px' ,title: 'Multi-Column Form Layout' ,labelAlign: 'top' ,items:[{

    layout: 'column' , // 1border: false,items:[{

    columnWidth: .5, // 2layout: 'form' ,

  • 7/28/2019 ExtJS Forms

    7/20

    Forms

    4

    border: false,bodyStyle: 'padding-right:10px' ,defaults: {width: '100%' },items: [{

    xtype: 'textfield' ,fieldLabel: 'First Name' ,

    name: 'firstName'},{xtype: 'c heckboxgroup' , // 3fieldLabel: 'Product Edition' ,columns: 3,items: [

    {boxLabel: 'Lite' , name: 'product-edition' },{boxLabel: 'Pro' , name: 'product-edition' }

    ]}]

    },{columnWidth: .5,layout: 'form' ,

    border: false,defaults: {width: '100%' },items: [{

    xtype: 'textfield' ,fieldLabel: 'Last Name' ,name: 'lastName'

    },{xtype: 'radiogroup' , // 4fieldLabel: 'Preffered Contact Method' ,columns: 3,items: [

    {boxLabel: 'Email' , name: 'contact-method' , checked:true},{boxLabel: 'Phone' , name: 'contact-method' }

    ]}]

    }]},{

    xtype: 'htmleditor' , // 5fieldLabel: 'Message' ,width: '100%' ,height: 150,enableSourceEdit: false,enableFont: false

    }],renderTo: Ext.getBody()

    }); });

    1. At first glance it might appear the first item added to the Ext.form.FormPanel is aExt.layout.ColumnLayout but it's actually an Ext.Panel with its layout set to column . Thishappens because the default xtype for most components including FormPanel is panel .It's possible to override this by explicitly setting the defaultType configuration option of the

    http://dev.sencha.com/deploy/dev/docs/?class=Ext.layout.ColumnLayouthttp://dev.sencha.com/deploy/dev/docs/?class=Ext.layout.ColumnLayouthttp://dev.sencha.com/deploy/dev/docs/?class=Ext.Panelhttp://dev.sencha.com/deploy/dev/docs/?class=Ext.layout.ColumnLayouthttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.FormPanel
  • 7/28/2019 ExtJS Forms

    8/20

    Forms

    5

    FormPanel to another value although in the case using panel is appropriate. The border config option is set to false which along with the other default Panel settings hides anyvisual indicators a Panel is being in the form. This Panel along with the two nested inside ofit are all used soley for layout purposes.

    2. This sets up the first of the two nested Panels containing the form components. ThecolumnWidth configuration property is used by the parent panel 's Ext.layout.ColumnLayout .From the documentation The columnWidth property is always evaluated as a percentage,and must be a decimal value greater than 0 and less than 1. Setting columnWidth here to.5 tells the parent Panel to split its available space equally among the two nested Panels.To control the visual aspects of this Panel border is set to false and some padding is addedto the right side of the Panel's body to provide spacing between the edge of this Panel andthe one next t o it. The layout is set to fo rm to control the layout of the form component scontained within this Panel. Finally the defaults configuration option is used to set the widthto 100% for all form components inside this Panel.

    3. This sets up an Ext.form.CheckboxGroup which provides functionality to make workingwith Ext.form.Checkbox component s more convenient. The columns property is set to 3 to distribute the available space into 3 columns. Even though there are only 2 checkboxesusing 3 columns here produces a cleaner result. Reading the API documentation forExt.form.Checkbox reveals the items configuration property is designed to accept an arrayof existing Checkbox instances or Checkbox configuration objects as we're doing here.

    4. The Ext.form.RadioGroup component works similar to Ext.form.CheckboxGroup providingconvenient features to work with Ext.form.Radio fields. RadioGroup automatically takescare of making sure only one Radio field in the group can be checked at a given time. Inthis example the first Radio field is checked by default by setting it's checked configurationoption to true .

    5. The last component added to the form is an Ext.form.HtmlEditor component whichprovides a lightweight WYSWYG style html editor. Unlike the previous fields the HtmlEditorcomponent is configured directly inside the main FormPanel. Setting its width to "100%"allows it to span the full width of the FormPanel. In this exam ple a few items in th eHtmlEditor have been disabled to save space and show how quickly this component can betailored to suit your application requirements.

    Note

    Whenever a specific xtype is left out of the component configuration code its agood idea to refer to the API documentation for that component to understand thedefault xtype being used.

    Note

    Ext.Panel components were us ed in this example to bring attention to defau ltxtypes . Since the Pane ls were only used for layo ut it would have been more

    efficient to use Containers instead.

    This example explored how you can create a column style form layout usingExt.layout.ColumnLayout along with nested Panels inside a single main Ext.form.FormPanel .

    Form ValidationThis example provides an introduction to validating form input using Ext JS. Form validationcan be achieved with Ext JS using a few different approaches from simple configurat ion

    http://dev.sencha.com/deploy/dev/docs/?class=Ext.layout.ColumnLayouthttp://dev.sencha.com/deploy/dev/docs/?class=Ext.layout.ColumnLayouthttp://dev.sencha.com/deploy/dev/docs/?class=Ext.layout.ColumnLayouthttp://dev.sencha.com/deploy/dev/docs/?class=Ext.layout.ColumnLayouthttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.FormPanelhttp://dev.sencha.com/deploy/dev/docs/?class=Ext.Panelhttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.HtmlEditorhttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.RadioGrouphttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.RadioGrouphttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.RadioGrouphttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.Checkboxhttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.CheckboxGrouphttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.CheckboxGrouphttp://dev.sencha.com/deploy/dev/docs/?class=Ext.layout.ColumnLayouthttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.FormPanelhttp://dev.sencha.com/deploy/dev/docs/?class=Ext.layout.ColumnLayouthttp://dev.sencha.com/deploy/dev/docs/?class=Ext.Panelhttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.HtmlEditorhttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.Radiohttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.RadioGrouphttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.Checkbox?member=itemshttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.Checkboxhttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.CheckboxGrouphttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.Checkboxhttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.CheckboxGrouphttp://dev.sencha.com/deploy/dev/docs/?class=Ext.layout.ColumnLayout
  • 7/28/2019 ExtJS Forms

    9/20

  • 7/28/2019 ExtJS Forms

    10/20

    Forms

    7

    fieldLabel: 'Email Address' ,name: 'email' ,allowBlank: false,vtype: 'email' , // 4vtypeText: 'Invalid email format must be [email protected]'

    },{

    xtype: 'textfield' ,fieldLabel: 'Subject' ,name: 'subject' ,maskRe: /[a-z0-9_]/i,regex: /^[a -zA-Z0-9 _]+$/,, // 5regexText: 'Only alphanumeric characters allowed'

    }],buttons: [{

    text: 'Save'}, {

    text: 'Cancel'}],renderTo: Ext.getBody()

    }); });

    1. Initialzes a global instance of Ext.QuickTips . The default form validation messages aredisplayed as tooltip messages using Ext.QuickTips. Initializing QuickTips here ensures thevalidation messages display correctly above the form fields.

    2. The allowBlank configuration option is a convenient way to to make sure the form fieldcontains user input. Setting it to false here will display the default error message "This field is required." if the "First Name" field is left blank.

    3. The second form fiel d labeled " Last Name" demonstrates combining six different validationoptions to validate a single field. Using blankText with allowBlank allows you display acustom message when the field is left blank. Setting minLength and maxLength allows youto enforce boundaries for the minimum and maximum length of user input allowed in theform field. Combining these two options along with minLeng thText and maxLengthText allows you to display custom messages informing users of the boundaries you set for thefield.

    4. The "Email Address" field specifies a vtype to handle input validation. Ext.form.VTypes is a singleton object that provides an extensible way of using a function, input mask andvalidation message to validate form field input. Ext.form.VTypes includes a set of built-infunctions that can be used as a starting point for creating your own vtypes . In this examplethe email address is validated using the email method of Ext.form.VTypes. We also set

    vtypeText to demonstrate overriding the default validation message provided by the vtype function with a custom one.

    5. The last field "Subject" combines the regex , regexText and maskRe configuration optionsto demonstrate another way of achieving the same result as validating with the built-inalphaNum method of Ext.form.VTypes. Setting maskRe prevents the field from acceptingkey strokes not matching the regular expression. Then the regular expression set forregex is used to validate the user input for the field. If any input gets by the input mask anddoesn't match the regular expression set with regex the message you set for regexText automatically displays. Unless there is a specific reason not to do so its better to use a vtype

    http://dev.sencha.com/deploy/dev/docs/?class=Ext.form.VTypes&member=alphaNumhttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.TextField&member=allowBlankhttp://dev.sencha.com/deploy/dev/docs/?class=Ext.QuickTipshttp://dev.sencha.com/deploy/dev/docs/?class=Ext.QuickTipshttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.VTypes&member=alphaNumhttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.VTypes&member=emailhttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.VTypes#Ext.form.VTypes-methodshttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.VTypes#Ext.form.VTypes-methodshttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.VTypeshttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.TextField&member=vtypehttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.TextField&member=maxLengthhttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.TextField&member=maxLengthhttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.TextField&member=maxLengthhttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.TextField&member=minLengthhttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.TextField&member=allowBlankhttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.TextField&member=allowBlankhttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.TextField&member=allowBlankhttp://dev.sencha.com/deploy/dev/docs/?class=Ext.QuickTips
  • 7/28/2019 ExtJS Forms

    11/20

    Forms

    8

    which enables the same functionality and the option to re-use your validation code withother fields.

    This example demonstrated a number of the different validation techniques you can use tovalidate user input in form components. In addition to the techniques shown above you'll alsowant to become familiar with the API documentation for other useful validation options (listed

    here for convenience). validateOnBlur Toggles whether the field is validated as soon as it loses focus (defaults to

    true).

    validationDelay Time in milliseconds from when user input begins until validation is initiated(defaults to 250).

    validationEvent The event that should initiate field validation (defaults to 'keyup').

    validator A custom validation function to be called during field validation (defaults to null).

    Form SubmissionThis example will show you how to submit an Ext JS powered form to your server sideapplication. We use the layout and validation techniques described in previous examples tolayout form elements and validate user input before submitting the form. Buttons are addedto the bottom of the form allowing users trigger a form submission or clear all the form fields.Once the submit action is triggered we display a MessageBox message to let users know theform has been submitted. Then we display another MessageBox to indicate the success orfailure of the form submission.

    Ext.onReady( function () {

    Ext.QuickTips.init();

    new Ext.form. FormPanel({width: 320,height: 170,frame: true,bodyStyle: 'padding:5px' ,title: 'Form Submission' ,

    http://dev.sencha.com/deploy/dev/docs/?class=Ext.form.TextField&member=validationDelayhttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.TextField&member=validatorhttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.TextField&member=validationEventhttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.TextField&member=validationDelayhttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.TextField&member=validateOnBlur
  • 7/28/2019 ExtJS Forms

    12/20

    Forms

    9

    defaults: {width: '100%' },method: 'POST' , // 1url: 'formtester.php' , // 2

    Note

    Although not listed in API documentation for Ext.form.FormPanel , the FormPanelclass accepts all of the configuration options needed to configure its internalinstance of Ext.form.BasicForm .

    1. The method configuration option sets the HTTP request method of Ext.form.BasicForm toPOST the form data.

    2. The url option sets the location where the form data will be posted.

    items: [{xtype: 'textfield' ,fieldLabel: 'Subject' ,name: 'subject' , // 3maskRe: /[a-z0-9_ ]/i,regex: /^[a-zA-Z0-9_ ]+$/,regexText: 'Only alphanumeric characters allowed'

    },{xtype: 'textfield' ,fieldLabel: 'Name' ,name: 'name' ,allowBlank: false,blankText: 'Custom validation message.' ,minLength: 2,minLengthText: 'Please enter more than 2 characters.' ,

    maxLength: 20,maxLengthText: 'Please enter less than 20 characters.'},{

    xtype: 'textfield' ,fieldLabel: 'Email' ,name: 'email' ,allowBlank: false,vtype: 'email' ,vtypeText: 'Invalid email format must be [email protected]'

    }],

    This block sets up the array of form components displayed in the FormPanel. The form fields

    are similar to the ones previously covered in the validation example.

    3. The value set for the name configuration option of each field corresponds to the nameattribute in the underlying HTML for each of the form fields. This will included in the datapacket that gets post ed to th e server.

    buttonAlign: 'center' ,buttons: [{

    text: 'Submit' ,

    http://dev.sencha.com/deploy/dev/docs/?class=Ext.form.BasicForm&member=methodhttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.TextField&member=namehttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.BasicForm&member=urlhttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.BasicForm&member=methodhttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.BasicFormhttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.FormPanel
  • 7/28/2019 ExtJS Forms

    13/20

    Forms

    10

    handler: function (btn, eventObj) { // 4 var formPanel = btn.findParentByType( 'form' ); // 5 var form = formPanel.getForm(); // 6 if (form.isValid()) { // 7

    form.submit({ // 8 clientValidation: true,

    failure: failureNotice,success: successNotice,waitMsg: 'processing form submission' ,waitTitle: 'Status'

    });}

    }

    This adds a "Submit" Button to the bottom of the FormPanel which is wired up with a handler

    function to submit the form when the Button's click event is fired.4. The handler config option provides a convenient way to execute a function when the

    Button's click event is fired. The function is passed two parameters the Button that wasclicked and the click event.

    5. Since the Button object is contained by the FormPanel you can use the findParentByType method of the Button instance to find the FormPanel by its xtype value form .

    6. With a reference to the FormPanel you can use its getForm method to gain a reference toits internal instance of Ext.form.BasicForm .

    7. Before actually submitting the form we call the isValid method of Ext.form.BasicForm toensure all the user input has passed the client-side validation that was configured for

    each field. We use the boolean returned from isValid to determine if the form should besubmitted.

    8. When the form input has been validated and we're ready to submit it to the server we callthe submit method on the instance of Ext.form.BasicForm we got from the FormPanel. Thesubmit method automatically creates an instance of Ext.form.Action.Submit which acceptsa number of configuration options to provide control over how the form is submitted.

    clientValidation - ensures the form doesn't get submitted unless all the fields pass client-sidevalidation checks.

    http://dev.sencha.com/deploy/dev/docs/?class=Ext.form.Action.Submithttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.BasicFormhttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.BasicForm&member=submithttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.BasicForm&member=isValidhttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.BasicFormhttp://dev.sencha.com/deploy/dev/docs/?class=Ext.FormPanel&member=getFormhttp://dev.sencha.com/deploy/dev/docs/?class=Ext.Button&membrer=findParentByType
  • 7/28/2019 ExtJS Forms

    14/20

    Forms

    11

    failure - sets the callback function if the submit fails.

    success - sets the callback function for a successful submission.

    waitMsg - automatically creates an instance of Ext.MessageBox.wait while the form is beingsubmitted and diplays the message set here inside the MessageBox.

    waitTitle - title used for the Ext.MessageBox.wait displayed during form submission.

    text: 'Reset' , // 9handler: function (btn, eventObj) {

    btn.findParentByType( 'form' ).getForm().reset();

    9. This sets up a text Button labeled "Reset". We create an anonymous handler functionthat executes when the Button's click event is fired. Using the passed in reference to theButton object we're able to find the Ext.form.FormPanel containing this Button. Then we usegetForm to get a reference to it's internal Ext.form.BasicForm object in order to call the reset method of the Ext.form.BasicForm instance which automatically clears all the input from itsform fields.

    function successNotice(form, action) { // 10Ext.Msg.alert( 'Confirmation' , 'Success!' );

    }

    function failureNotice(form, action) { // 11Ext.Msg.show({

    title: 'Error' ,msg: 'An unknown error has occured' ,buttons: Ext.Msg.OK,

    icon: Ext.MessageBox.ERROR,width: 275});

    10.Here we create the implementation of the s uccessNotice function that we set for the valueof the success configuration option of Ext.form.Action.Submit . Upon a successful form

    http://dev.sencha.com/deploy/dev/docs/?class=Ext.MessageBox&member=waithttp://dev.sencha.com/deploy/dev/docs/?class=Ext.MessageBox&member=waithttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.Action.Submithttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.BasicForm&member=resethttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.BasicFormhttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.FormPanel&member=getFormhttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.FormPanelhttp://dev.sencha.com/deploy/dev/docs/?class=Ext.MessageBox&member=waithttp://dev.sencha.com/deploy/dev/docs/?class=Ext.MessageBox&member=wait
  • 7/28/2019 ExtJS Forms

    15/20

    Forms

    12

    submission this function will execute and display a simple Ext.Msg.alert box to let the userknow the form was successfully submitted.

    11.We implement the failureNotice function that we set as the value for the failure config optionof Ext.form.Action.Submit . This function executes if an error occurs during form submission.It displays an Ext.MessageBox configured to show an error message and display an erroricon informing the user of the error.

    By default Ext.form.Action.Submit is designed to accept a JSON response back from theserver. The response needs to contain at least one key labeled success with it's value set totrue or false . You can also pass back an errors object containing additional server side errorinformation your client code can take action on.

    {success: false,errors: {

    email: "Client not found matching that email address."}

    }

    Note

    In this example we expect the server to respond back with JSON. You can alsorespond with XML. See the Ext.form.Action.Submit API docs for a sample XMLresponse.

    This example demonstrated the form submission process and how you can provide feedbackto users in the form of an Ext.MessageBox during each step of the form submission process.In a real-world application you'll most likely want take additional actions upon a successful form

    submission such as closing or collapsing the FormPanel and maybe updating a GridPanelcontaining the newly added data record. In the event of a failure condition you can usethe Ext.form.Action object (passed into your failure handler function) to access additionalinformation including the failureType and result data.

    Loading Form DataReal-world applications usually provide a way for users to update existing information. Thisexample demonstrates how you can support this use case by populating a client-side Ext JS

    http://dev.sencha.com/deploy/dev/docs/?class=Ext.form.Action&member=resulthttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.Action&member=failureTypehttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.Actionhttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.Action.Submithttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.Action.Submithttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.Action.Submithttp://dev.sencha.com/deploy/dev/docs/?class=Ext.MessageBox&member=alert
  • 7/28/2019 ExtJS Forms

    16/20

    Forms

    13

    form with data from your server and allowing the user to edit that data before submitting itback.

    We'll start off by taking a look at a screenshot of what the form looks like when the data fromthe server has been loaded into it. Then we'll take a look at the JavaScript we used to generatethe empty form.

    var formPanel = new Ext.form.FormPanel({width: 430,height: 330,frame: true,bodyStyle: 'padding:5px' ,title: 'Loading Form Data' ,url: '/forms/formSubmit.php' , // 1method: 'POST' ,labelAlign: 'top' ,items:[{

    xtype: 'container' ,layout: 'column' ,border: false,

    This code block sets up a FormPanel with the same multi-column layout we used in previousexamples to demonstrate form layout techniques.

    1. The URL specified here is the URL that the form data will be posted to after its been edited.In this example the URL is different from where the data will be retrieved.

  • 7/28/2019 ExtJS Forms

    17/20

    Forms

    14

    items:[{columnWidth: .5,xtype: 'container' ,layout: 'form' ,border: false,style: 'padding-right:10px' ,

    defaults: {width: '100%' },items: [{xtype: 'textfield' ,fieldLabel: 'First Name' ,name: 'firstName' // 2

    },{xtype: 'checkboxgroup' ,fieldLabel: 'Product Edition' ,columns: 3,items: [

    {boxLabel: 'Lite' , name: 'productEdition[0]' , inputValue: 'lite' }, // 3{boxLabel: 'Pro' , name: 'productEdition[1]' , inputValue: 'pro' }

    ]

    }]

    2. The name configuration option set here will be referenced in the data that we load from theserver. The Ext.form.Action.Load class uses this key to match the field with the correct datavalue returned from the server.

    3. Notice the name configuration option being used for the two Ext.form.Checkbox items in theExt.form.CheckboxGroup . The approach being used here is slightly different than traditionalHTML forms where we might use the name productEdition[] without numbers inside thearray brackets. In order for Ext.form.Action.Load to automatically populate checkbox fieldswith the correct values we need to explicitly number each checkbox in the array. This issomething that you'll need to take into acco unt for your server sid e data if you want these

    values to auto-loaded by Ext.form.Action.Load .If that approach doesn't work for your situation you could alternatively set a u nique name foreach checkbox (productEdition-1, productEdition-2, etc). Another option would be to use theempty bracket naming convention (productEdition[]) and then manually populate the valuesfrom the server by looping th rough your server sid e data and manually matching it with thecorrect Ext generated checkboxes.

    columnWidth: .5,xtype: 'container' ,layout: 'form' ,border: false,defaults: {width: '100%' },items: [{

    xtype: 'textfield' ,fieldLabel: 'Last Name' ,name: 'lastName'

    },{xtype: 'radiogroup' ,fieldLabel: 'Preferred Contact Method' ,columns: 3,items: [

    http://dev.sencha.com/deploy/dev/docs/?class=Ext.form.Action.Loadhttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.Checkboxhttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.Action.Loadhttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.Action.Loadhttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.CheckboxGrouphttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.Checkboxhttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.Action.Load
  • 7/28/2019 ExtJS Forms

    18/20

    Forms

    15

    {boxLabel: 'Email' , name: 'contactMethod' , inputValue: 'email' , checked:tru{boxLabel: 'Phone' , name: 'contactMethod' , inputValue: 'phone' }

    ]}]

    4. Here we can use the same name for both Ext.form.Radio fields since only one of these we'llever be set at a time. Ext.form.Action.Load will use both the name and inputValue to matchthe correct field with the server supplied data.

    xtype: 'htmleditor' ,fieldLabel: 'Message' ,name: 'message' ,width: '100%' ,height: 150,enableSourceEdit: false,enableFont: false

    This last block sets up the Ext.form.HtmlEditor . Since the HtmlEditor component generat esHTML markup the user entered input from this componen t will automatically be encoded whenthe form is submitted and decoded when it's loaded back in. You'll need to make sure the datais also correctly encoded before it's sent back over the wire from your server to be loaded backinto the HtmlEditor by Ext.form.Action.Load . We'll see an example of this when we look at howthe server side data packet is prepared.

    formPanel.getForm().load({ // 5method: 'GET' , // 6 url: '/forms/formData.php' ,failure: function () { // 7

    Ext.Msg.alert( 'Error' , 'Unable to load form data' );},waitMsg: 'Retrieving form data' , // 8 waitTitle: 'Loading...'

    });

    After configuring the Ext.form.FormPanel we call the load method of the Ext.form.BasicForm contained by the FormPanel. This method configures an instan ce of the Ext.form.Action.Load class to to populate the form with data from our server response. In this example we initiate thecall inside Ext.onReady() just after the FormPanel is created. Alternatively you could also placethis code inside an event listener that executes when the FormPanel's render event is fired.

    5. Calls the load method of Ext.form.BasicForm to initiate loading data into the empty form.

    6. Configures the HTTP method used to access the URL that's set on the next line.

    7. We setup an anonymous function to execute if a failure condition occurs. Here we justdisplay an simple Ext.Msg.alert box.

    8. The waitMsg and waitTitle configuration options provide a convenient way to automaticallydisplay a MessageBox to our users w hile the data is being retrieved and loaded into theform.

    http://dev.sencha.com/deploy/dev/docs/?class=Ext.form.Action.Loadhttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.FormPanelhttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.BasicFormhttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.HtmlEditorhttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.Action.Loadhttp://dev.sencha.com/deploy/dev/docs/?class=Ext.MessageBox&member=alerthttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.BasicFormhttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.FormPanel&member=renderhttp://dev.sencha.com/deploy/dev/docs/?class=Ext&member=onReadyhttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.Action.Loadhttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.BasicFormhttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.FormPanelhttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.Action.Loadhttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.HtmlEditorhttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.Action.Loadhttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.Radio
  • 7/28/2019 ExtJS Forms

    19/20

    Forms

    16

    After going through the example you can see it doesn't take much code to actually load datainto the form using Ext.form.Action.Load . Next we'll take a look at how to prepare the datapacket on the server side.

    In the code sample above we set the URL configuration option to /forms/formData.php. TheformData.php file is a simple PHP script that creates a JSON data packet with the correct keyvalue pairs needed to smoothly loa d data into our form.

    $resultSet = Array ();$resultSet[ "firstName" ] = "Rob" ; // 1$resultSet[ "lastName" ] = "Dobalina" ;$resultSet[ "contactMethod" ] = "email" ;$resultSet[ "productEdition[0]" ] = "lite" ; // 2$resultSet[ "productEdition[1]" ] = "pro" ;$resultSet[ "message" ] = 'Test message created with the html editor. This

    echo '{"success":true, "data":' .json_encode($resultSet). '}' ; // 4

    The PHP script creates an array to mimic what a database result set might look like.

    1. We go through and set array keys to match the name configuration option we set for each ofour Ext JS form field components so Ext.form.Action.Load correctly matches the data to ourform fields.

    2. You'll notice we explicitly set array indices for productEdition . It's done manually in this scriptfor simplicity, in a real-world application you would use a loop.

    http://dev.sencha.com/deploy/dev/docs/?class=Ext.form.Action.Loadhttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.Action.Loadhttp://dev.sencha.com/deploy/dev/docs/?class=Ext.form.Action.Load
  • 7/28/2019 ExtJS Forms

    20/20

    Forms

    3. The message value is plain HTML. In a real-world application you might need to employsome string conversion to safely store HTML in your data store.

    4. On the last line we assemble the JSON packet. Setting success to true confirms theunderlying Ext JS Ajax call was successfully executed on the server side. The data keyis set to the JSON encoded value of the PHP array containing the data for our form.Ext.form.Action.Load will use the data values to populate the client-side form components.

    This guide demonstrated the typical life cycle of an Ext JS powered form. Visit the links belowfor more form related resources.

    Additional Form Resources Ext JS Form Examples

    Ext.form.FormPanel API Documentation

    http://dev.sencha.com/deploy/dev/docs/?class=Ext.form.FormPanelhttp://dev.sencha.com/deploy/dev/examples/#sample-11http://dev.sencha.com/deploy/dev/docs/?class=Ext.form.Action.Load