Tuesday, June 1, 2010

Ext 2.2 RadioGroup getValue()/setValue()

There seems to be issues with the getValue() and setValue() methods of the Ext.form.RadioGroup class in the 2.2 API version. The methods do not seem to work the way they are supposed to. If you have to use these methods, you need to override them. Here's the override script and some sample code on how to use the RadioGroup class.

Override code:
Ext.override(Ext.form.RadioGroup, {
  getName: function(){
    return this.items.first().name;
  },
  getValue: function(){
    var v;
    if (this.rendered) {
      this.items.each(function(item){
      if (!item.getValue())
        return true;
      v = item.getRawValue();
      return false;
      });
    }
    else {
      for (var k in this.items) {
        if (this.items[k].checked) {
          v = this.items[k].inputValue;
          break;
        }
      }
    }
    return v;
  },
  setValue: function(v){
    if (this.rendered){
      this.items.each(function(item){
        item.setValue(item.getRawValue() == v);
      });
    }
    else {
      for (var k in this.items) {
        this.items[k].checked = this.items[k].inputValue == v;
      }
    }
  }
});

RadioGroup:
{
  xtype: 'radiogroup',
  fieldLabel: 'Male/Female',
  id:'rg1',
  items: [
    {boxLabel: 'Male', name: 'gender', inputValue: 1},
    {boxLabel: 'Female', name: 'gender' ,inputValue: 2, checked: true}
  ]
}

Ext.getCmp('rg1').setValue(1);
Ext.getCmp('rg1').getValue();

Hope it helps!!

1 comment:

Aparna Jain said...

Great! This really helped me!!

I also found that in addition to the override you mentioned for setValue() and getValue() to work, if one needs to use the 'change' and 'blur' events on radiogroup, you need to add another override -

afterRender: function() {
var group = this;
this.items.each(function(field) {
// Listen for 'check' event on each child item
field.on("check", function(self, checked) {

// if checkbox is checked, then fire 'change' event on RadioGroup container
if(checked)
// Note, oldValue (third parameter in 'change' event listener) is not passed,
// because is not easy to get it
group.fireEvent('change', group, self.getRawValue());

});
});

Ext.form.RadioGroup.superclass.afterRender.call(this)
}