In the application development, there are instances when we have to indicate a mandatory form field by showing a red asterisk next to the field label.
The code here overrides the private function of the Ext.form.FormLayout and works with a custom property required. I chose the form layout as the rendering of the labels is taken care by this layout. Another option was to use the allowBlank property but just to keep things simple I have used the custom config required.
For ExtJS version 2.2.x
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
Ext.override(Ext.layout.FormLayout, { renderItem : function(c, position, target){ if(c && !c.rendered && c.isFormField && c.inputType != 'hidden'){ var labelSep = typeof c.labelSeparator == 'undefined' ? this.labelSeparator : c.labelSeparator; if (c.required) labelSep += '<span style="color: rgb(255, 0, 0); padding-left: 2px;">*</span>'; var args = [ c.id, c.fieldLabel, this.getLabelStyle(c.labelStyle), this.elementStyle||'', labelSep, (c.itemCls||this.container.itemCls||'') + (c.hideLabel ? ' x-hide-label' : ''), c.clearCls || 'x-form-clear-left' ]; if(typeof position == 'number'){ position = target.dom.childNodes[position] || null; } if(position){ this.fieldTpl.insertBefore(position, args); }else{ this.fieldTpl.append(target, args); } c.render('x-form-el-'+c.id); }else { Ext.layout.FormLayout.superclass.renderItem.apply(this, arguments); } } }); |
For ExtJs version 3.0.x
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
Ext.override(Ext.layout.FormLayout, { getTemplateArgs: function(field) { var noLabelSep = !field.fieldLabel || field.hideLabel; var labelSep = (typeof field.labelSeparator == 'undefined' ? this.labelSeparator : field.labelSeparator); if (field.required) labelSep += '<span style="color: rgb(255, 0, 0); padding-left: 2px;">*</span>'; return { id: field.id, label: field.fieldLabel, labelStyle: field.labelStyle||this.labelStyle||'', elementStyle: this.elementStyle||'', labelSeparator: noLabelSep ? '' : labelSep, itemCls: (field.itemCls||this.container.itemCls||'') + (field.hideLabel ? ' x-hide-label' : ''), clearCls: field.clearCls || 'x-form-clear-left' }; } }); |
Following is a typical usage:
1 2 3 4 5 6 |
{ fieldLabel: 'Patient Id', xtype: 'textfield', name:'patientId', required: true } |