20 January 2010

ExtJS Helper Functions - GetValue / SetValue

This is my first (of several planned) functions to increase the functionality of the ExtJs functionality.

These methods extend the container object and make it easier to set and retrieve values from the controls within the container.  A great benefit is that the search will go into all the nested containers as well.

// Shortcut for adding methods to the prototype
Function.prototype.method = function (name, func) {
this.prototype[name] = func;
return this;

// Works on all containers (windows, formformpanels, etc.) and will
// even search subcontainers. The control must have an identifiable id
// and a setValue method.
// In this method c is the control id and v is the value to be set.
Ext.Container.method('setValue', function (c, v) {

// Works on all containers as above. The control must have an identifiable
// id  and a getValue method.
// In this method, c is the control id of the value to be retrieved.
Ext.Container.method('getValue', function (c) {
return this.findById(c).getValue();

Using these functions on the container saves a tremendous amount of code devoted to looking up and setting values. Just create a variable for the container and then use the getValue retrieve the value or setValue to set the value.

For instance, if you have a window object named 'win' and a textbox with an id of 'txtName', you can merely use:
win.setValue('txtName', 'Michael'); 
Doing so will set the TextBox value to Michael, even if it is deeply nested in a form panel and several columns.