I have this problem where I need to add a red asterisk beside a fieldLabel
when a field is marked as \"required\" (or allowBlank: false
)
In
Their are so many ways to do this and few of which you can find above, what I am suggesting is:
{
xtype : 'label',
html:'<span>First Name</span><span style="color: rgb(255, 0, 0); padding-left: 2px;">*</span>',
width:50,
}
Simply you can put both asterisk and Label text in single html property.
If you don't want to override anything, put the asterisk in the labelSeparator:
{
xtype: 'textfield',
fieldLabel: 'Name',
name: 'requestor_name',
allowBlank: false,
labelSeparator : ': <span style="color:red">*</span>'
}
I have a little bit shorter solution. I suggest to use form's 'beforeadd' event like this:
Ext.define('Ext.ux.form', {
extend: 'Ext.form.Panel',
initComponent: function() {
this.on('beforeadd', function(me, field){
if (!field.allowBlank)
field.labelSeparator += '<span style="color: rgb(255, 0, 0); padding-left: 2px;">*</span>';
});
this.callParent(arguments);
}
});
Here is demo
Extjs 4.1
When the field has a fieldLabel use:
fieldLabel: 'Name',
allowBlank: false,
afterLabelTextTpl: "<span style="color:red;font-weight:bold" data-qtip="Required">*</span>"
If the field don't have a fieldLabel use a combination of config options, the hideLabel config must be false:
//hideLabel: false
name: 'lastName',
emptyText: "Last Name",
allowBlank: false,
labelWidth: 0,
fieldLabel: '',
hideEmptyLabel: false,
afterLabelTextTpl: '<span style="color:red;font-weight:bold" data-qtip="Required">*</span>'
Also, you can mix this solution with Drasill plugin an have a easy way to customise all fields at once.
An approach that you might find more elegant is adding a css class to any field label that is marked with allowBlank=false
and style your mandatory indicator in CSS.
Ext.define('Ext.ux.form', {
extend: 'Ext.form.Panel',
listeners: {
'beforeadd': function(){
if (!field.allowBlank) {
field.labelClsExtra = 'x-required';
}
}
}
});
You can then style your field label in CSS with an :after
pseudo utility:
.x-required:after {
content: ' *';
color: red;
font-weight: bold;
}