PDA

View Full Version : Dynamically set labels from record



JSimko
14 Jan 2013, 3:26 PM
Is it possible to use a record to dynamically populate labels in the same way that it can populate fields in a Ext.form.Panel?

e.g. The following but with a label instead of a text input field:

panel.loadRecord(record):
items: [
{
xtype: 'textfield',
name: 'firstName',
fieldLabel: 'First Name:'
}


My use case is that I am trying to create two versions of a form:

The user is in edit mode and can alter fields and save.
The user is in view mode and can only read the data.

This is where I would like to use xtype: label to display. Ideally I want to avoid setting each field manually.

Stormseeker
15 Jan 2013, 9:29 AM
panel.loadRecord is really just calling Ext.form.Basic.setValues(record.data) method. You can try and use this method as a template and create a new function to set the labels instead of the values for each field.

Original setValues() method:



setValues: function (values) {
var me = this,
v, vLen, val, field;


function setVal(fieldId, val) {
var field = me.findField(fieldId);
if (field) {
field.setValue(val);
if (me.trackResetOnLoad) {
field.resetOriginalValue();
}
}
}


if (Ext.isArray(values)) {
// array of objects
vLen = values.length;


for (v = 0; v < vLen; v++) {
val = values[v];


setVal(val.id, val.value);
}
} else {
// object hash
Ext.iterate(values, setVal);
}
return this;
}

JSimko
15 Jan 2013, 3:33 PM
Thanks,

I think that will have to do the trick for now. Here is the function I created; I've only tested it with a couple specific use cases and it probably can't handle much outside of that.

values: An array or map of values
form: Container w/ label objects that have itemId matched to the values.



setLabels: function( values, form )
{
var me = form,
v, vLen, val, field;


function setVal(labelId, val) {
var label = me.down('#' + labelId );
if ( label ) {
if ( label.setText !== undefined )
{
label.setText(val);
}
}
}


if (Ext.isArray(values)) {
// array of objects
vLen = values.length;


for (v = 0; v < vLen; v++) {
val = values[v];


setVal(val.id, val.value);
}
} else {
// object hash
Ext.iterate(values, setVal);
}
return form;
}

Stormseeker
15 Jan 2013, 3:59 PM
Not sure if this is the recommended way, but if you wanted to add it to the Ext.form.Basic class, you could try something like this:



Ext.define('Ext.form.BasicOverride', {
override: 'Ext.form.Basic',

setLabels: function( values )
{
var me = this,
v, vLen, val, field;

function setVal(labelId, val) {
var label = me.down('#' + labelId );
if ( label ) {
if ( label.setText !== undefined )
{
label.setText(val);
}
}
}


if (Ext.isArray(values)) {
// array of objects
vLen = values.length;


for (v = 0; v < vLen; v++) {
val = values[v];


setVal(val.id, val.value);
}
} else {
// object hash
Ext.iterate(values, setVal);
}

return me;
}
})