Sencha Inc. | HTML5 Apps

Form FAQ

Published Sep 17, 2010 | The Sencha Dev Team | FAQ | Medium
Last Updated Jul 11, 2011

This FAQ is most relevant to Ext JS, any version.

This article is currently due for review
We suspect that this article may be out-of-date or contain incorrect information.
But we are constantly editing articles, so we promise we will get to this one soon.

Field labels are not displayed

A Field's labels are rendered by the FormLayout layout manager. The Container in which the Fields are located must be configured with layout: 'form'

What is the basic thing to keep in mind about forms?

  • A BasicForm is not a layout managing Container. It exists solely to manage a collection of Ext.form.Field objects. Those Fields need to be rendered.
  • You need to add Fields to an Ext.form.FormPanel which is a Container which manages child Components, rendering them and sizing them where configured.
  • A FormPanel owns a BasicForm which is used to perform submissions and loads.
  • In order to render Fields correctly with labels, the container they are in (no matter what kind of Panel it is) must have layout:'form'. This is because it is the layout manager that actually renders child items. Only the FormLayout class knows how to render form Fields with all their extra wrappings.

Using a JsonReader with a Form?

If using JSON as the transport, do not use a Reader in a Form. Forms understand JSON natively.

How can I hide form or checkbox fields and their labels?

  • Use textfield.hide on a TextField to hide only the textfield
  • Use checkbox.hide to hide only the checkbox.

Options to hide the label, semicolon and the TextField:

  • set the labelStyle:'display:none', or labelSeparator:' ' or ' '
  • apply a class
new Ext.form.TextField({
    fieldLabel: elem<i>.label,
    name: elem<i>.id,
    itemCls : 'invisible'
})
var f = form.findField('yourField');
f.container.up('div.x-form-item').hide();

How to do overall form validation at onSubmit

How are responses handled when using forms versus say ajax requests?

First of all, there is a difference between Ajax.request and Form.submit.

  • Ajax.request is more "raw" while Form.submit does more processing. Ajax.request calls success and failure functions with 2 arguments: response and options. response contains headers and other properties including responseText. responseText is raw text returned from server. You must decode it to an object and analyze.
    • Function failure is called if and only if there is a error communicating with server (e.g. page not found, timeout, etc.)
    • Here is an example of Ajax.request call, together with an error handler
var o = {
             url:this.url
            ,mode:'post'
            ,params:{
                 cmd:'removeUserFromGroup'
                ,uid:uid
                ,gid:gid
            }
            ,scope:this
            ,success:function(response, options) {
                this.setLoading(false);
                var o = {};
                try {o = Ext.decode(response.responseText);}
                catch(e) {
                    this.showError(response.responseText);
                    return;
                }
                if(true !== o.success) {
                    //error occurred, act accordingly
                }
                else {
                    // do your success processing here
                }
            }
            ,failure:function(response, options) {
                this.setLoading(false);
            }
        }; // end of o setup
        this.setLoading(true);
        Ext.Ajax.request(o);

In the above: success:true, error:'msg' are arbitrary in this case. The code above is general in that it describes the logic.

  • Form.submits are handled differently.
    • success and failure functions are called with 2 arguments: form, action.
    • action.result contains already decoded json response from server and success is called only and only if server returns {"success":true}.
    • failure is called also if client validation fails and form is not submitted to the server at all in that case.

How can I hide form fields and their labels?

See this thread or this thread

Focus a field

  • To make sure the field is rendered:
editFormWindow.on('activate', function () {
   ragionesociale.focus(true,100);
});

Using Enter to Tab through Form

See this thread

Change field based on value of another field

  • Changing "to" date based on value in "from" date (+10 days):
dateFrom.on('change', function(f, value) {
   dateTo.setValue(value.add(Date.DAY, 10));
});

Change textfield config options with listeners

  • For example, if you make a selection on combobox, have it check if the value = 1. If so then textfield allowBlank: false else textfield allowBlank: true.
myCombo.on('select', function(cmb, rec) {
  var val = rec.get('someField');
  myTextfield.allowBlank = (val == 1);
  myTextfield.validate();//to force validation.
});

Standard Submit

  • You may need to use this to set the action:
PANEL.getForm().getEl().dom.action = 'URL'

Get all form fields

  • To pass the entire contents of the form as params, use:
store.reload({
    params: formPanel.getForm().getValues(false)
});

Fieldset Checkbox Toggle State

  • To alter the checked/unchecked state of the fieldset dynamically, try:
//where 'images-view' is the id for the fieldset
Ext.getCmp('images-view').toggleCollapse();
 
//To check the value of the checkbox on the fieldset
Ext.getCmp('images-view').checkbox.dom.checked

Error Message after a load action

Ext.override(Ext.form.BasicForm, {
    load: function(options){
        //default load options
        var _options = {
            //define failure method
            //use handleResponse method of Action.Submit as a guide
            failure: function(form, action){
                if (form.errorReader) {
                    var rs = form.errorReader.read(action.response);
                    var errors = [];
                    if (rs.records) {
                        for (var i = 0, len = rs.records.length; i < len; i++) {
                            var r = rs.records<i>;
                            errors<i> = r.data;
                        }
                    }
                    if (errors.length < 1) {
                        errors = null;
                    }
                    action.result = {
                        success: rs.success,
                        errors: errors
                    };
                }
                else {
                    action.result = Ext.decode(action.response.responseText);
                }
            }
        }
        //specific load options
        Ext.apply(_options, options);
 
        //do the load
        this.doAction('load', _options);
        return this;
    }
});

Modifying a date in a form to send to back end

  • Option 1: Use this plugin with your FormPanel to allow you to specify a getSubmitValue() method which you can then customize to your heart's content.
  • Option 2:
/*  
 * An example of modifying the format of a date field in a form
 * in order to pass the the date in mysql format
 */
Ext.onReady(function(){
 
    Ext.QuickTips.init();
 
 
    //modify date to different format
    function getDateValue(obj, format){
        var strReturn = '';
        try {
            strReturn = obj.getValue().format(format).trim();
        } 
        catch (err) {
            strReturn = '';
        }
        return strReturn;
    }
 
    var formPlan = new Ext.FormPanel({
        labelWidth: 75,
        frame: true,
        title: 'New Plan',
        waitMsgTarget: true,
        monitorValid: true,
        width: 350,
        defaults: {
            width: 210,
            msgTarget: 'side'
        },
        defaultType: 'textfield',
 
        items: [new Ext.form.DateField({
            fieldLabel: 'Start',
            id: 'date_start', // give id so can refer to this field more easily
            name: 'date_start',
            format: 'F j, Y',
            allowBlank: false
        })],
 
        buttons: [{
            text: 'New',
            formBind: true,
            handler: function(){
                formPlan.form.submit({
                    url: 'ajax/plan.php',
                    method: 'POST',
                    params: {
                        action: 'new',
                        //modify date
                        date_value1: getDateValue(Ext.get('date_start'), 'Ymd')
                    },
                    waitMsg: 'Saving Data...',
                    success: function(form, action){
                        Ext.MessageBox.alert('Message', 'Plan saved.');
                    },
                    failure: function(form, action){
                        Ext.MessageBox.alert('Message', 'Save failed');
                    }
                });
            }
        }, {
            text: 'Cancel',
            handler: function(){
                formPlan.form.reset();
            }
        }]
    });
 
    formPlan.render('plan');
});

Set height for TextArea component

Hide Form Fields

HTML in forms

  • if you just want to add text to a form panel like you mentioned, you may use a label as below:
Ext.getCmp("formpanel_container").add({
    xtype: "label",
    name: "rotate",
    id: 'label_id',
    text: "Your text goes here",
    cls: 'x-form-item-label x-form-item' /*apply ext styles*/
});
  • or if you would like to insert proper HTML (div, span, etc....), you may use:
Ext.getCmp("formpanel_container").add({
    xtype: "box",
    autoEl: {
        tag: 'div',
        id: id,
        children: [{
            tag: 'div',
            style: 'margin:0 0 4px 0',
            html: 'Your HTML bits here'
        }]
    }
});

Forms across multiple tabs

My Combobox in a tab, or card layout does not assume the correct width

Containers which are rendered hidden should be configured with

hideMode: 'offsets'

So that they are able to perform size calculations.

Textfield background color

items:{
  xtype:'textarea',
  style:'background-color:yellow; background-image: none;'
}

So that they are able to perform size calculations.

Set allowBlank dynamically

myField.allowBlank = true;
myField.validateValue(myField.getValue()); //force update

Set fieldLabel dynamically

Ext.override(Ext.form.Field, {
    setFieldLabel: function(text) {
        if (this.rendered) {
            var labelSeparator = this.labelSeparator;
 
            if (typeof labelSeparator == 'undefined') {
                if (this.ownerCt && this.ownerCt.layout && typeof this.ownerCt.layout.labelSeparator != 'undefined')
                    labelSeparator = this.ownerCt.layout.labelSeparator;
                else
                    labelSeparator = '';
            }
 
            var formItem = this.el.up('.x-form-item', 10);
 
            if (formItem) {
                var label = formItem.child('.x-form-item-label');
 
                if (label)
                    label.update(text + labelSeparator);
            }
        } else
            this.fieldLabel = text;
    }
});

DateField

To have an event which will fire immediately after a value is entered in the date field try this override:

Ext.override(Ext.form.DateField, {
    menuListeners : {
        select: function(m, d){
            this.fireEvent('select', this, d);
            this.setValue(d);
        },
        show : function(){ // retain focus styling
            this.onFocus();
        },
        hide : function(){
            this.focus.defer(10, this);
            var ml = this.menuListeners;
            this.menu.un("select", ml.select,  this);
            this.menu.un("show", ml.show,  this);
            this.menu.un("hide", ml.hide,  this);
        }
    }
});

autoCreate

http://extjs.com/forum/showthread.php?p=204155#post204155

Share this post:
Leave a reply

Written by The Sencha Dev Team

1 Comment

amininaNock

3 years ago

http://www.internetmarketingarticles.org/unlock-iphone-4-effectively-minutes/
Hello, I currently bought a computer and i installed all the anti-virus and other software. I want my internet to work but when i go to my hardware files. Ethernet Controller and Bus Controller and 2 other software have a question mark next to them. It says that there is errors installing it. Yes, i uninstalled it and installed it back but it wont work. i still cant go on the internet. btw, i bought the computer in different parts. Like i have HP Procesor and BenQ Monitor. Does this change anything? Please Help me solve this problem Thank you, Bakhti Mirzo

Leave a comment:

Commenting is not available in this channel entry.