I just had the requirement to mark required fields in a ExtJS form. I started with the code from Jason (Thanks!) and extended it a bit.
Now you may customize how the field marker would look like by assigning a CSS class to a requiredFieldCls
property. I also added a descriptive tooltip for the marker.
Here’s the code:
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.onReady(function(){ Ext.QuickTips.init(); Ext.form.Field.prototype.msgTarget = 'under'; Extensive.components.RequiredFieldInfo.prototype.requiredFieldText = 'These are really important things'; var panel = new Ext.FormPanel({ frame: true, labelWidth: 130, width: 350, items: [{ xtype: 'textfield', fieldLabel: 'This you might tell me', anchor: '100%' }, { xtype: 'textfield', fieldLabel: 'This I have to know', allowBlank: false, anchor: '100%', blankText: 'As said, I have to know this!' }, { xtype: 'reqFieldInfo' }] }); var element = Ext.query('script[src$=required-field.js]')[0]; var renderElement = element.parentNode; panel.render(renderElement); }); |
Dont’ forget to also include these necessary modifications to Ext.layout.FormLayout
:
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 |
Ext.ns('Extensive.components'); Ext.apply(Ext.layout.FormLayout.prototype, { originalRenderItem: Ext.layout.FormLayout.prototype.renderItem, renderItem: function(c, position, target){ if (c && !c.rendered && c.isFormField && c.fieldLabel && !c.allowBlank) { c.fieldLabel = c.fieldLabel + " <span " + ((c.requiredFieldCls !== undefined) ? 'class="' + c.requiredFieldCls + '"' : 'style="color:red;"') + " ext:qtip=\"" + ((c.blankText !== undefined) ? c.blankText : "This field is required") + "\">*</span>"; } this.originalRenderItem.apply(this, arguments); } }); Extensive.components.RequiredFieldInfo = Ext.extend(Ext.form.Label, { constructor: function(config){ Extensive.components.RequiredFieldInfo.superclass.constructor.call(this, Ext.apply({ html: "<span " + ((this.requiredFieldCls !== undefined) ? 'class="' + this.requiredFieldCls + '"' : 'style="color:red;"') + '>*</span> ' + ((this.requiredFieldText !== undefined) ? this.requiredFieldText : 'Required field') }, config)); } }); Ext.reg('reqFieldInfo', Extensive.components.RequiredFieldInfo); |
From know on you can find this code and all my other ExTJS components bundled in a library called ‘extensive’ – hosted at Google Code. Feel free to support the project by participating.