Thursday, June 17, 2010

XPages: Code snippet for Multi Value Custom Converter

I got a question regarding how to work around the buggy multi-value implementation in XPages. I use a custom converter for my multi value fields.

var Converters = {  
multivalue: {
// separator: String or RegExp
getAsObject: function( valuesString, separator ){
try {
separator = separator || ',';
var values = valuesString.split( separator );

// Trims empty values
var trimmedValue, trimmedValues = [];
for( var i = 0; i < values.length; i++ ){
trimmedValue = values[i];
// Removes leading and trailing white-space
if( trimmedValue ){
trimmedValues.push( trimmedValue.replace( /^\s+|\s+$/g, '' ) );
}
}
return trimmedValues;
} catch( e ){ /* Exception handling */ }
},
getAsString: function( values, separator ){
try {
if( values.constructor !== Array ){ values = [ values ]; }
separator = separator || '\n';

return values.join( separator );
} catch( e ){ /* Exception handling */ }
}
}
}
Put the above code snippet inside a script library. Add a custom converter to the multi value field.

In getAsObject -> Converters.multivalue.getAsObject( value, separator );
In getAsString -> Converters.multivalue.getAsString( value, separator );

getAsObject is the conversion of the submitted value to the stored value.
getAsString is the conversion of the stored value to a displayable string value.

Examples:
// Split on comma, semi colon and any white space 
Converters.multivalue.getAsObject( value, /,|;|\s/ );

// Show values comma separated
Converters.multivalue.getAsObject( value, "," );
value is a global variable that's available in the conversion. For getAsObject it's the submitted string. For getAsString, it's the stored value.

4 comments:

Erik Brooks said...

You rock, Tommy.

Is there an SPR tracking this bug with mult-value fields from IBM?

Tommy Valand said...

Why, thank you! :)

SPR EGLN7YMLYD

Paul S Withers said...

Thanks, Tommy, a great post. And a good example of how to create and implement a converter. I'm sure I'll use this converter as well as using the method you describe for creating a converter

Gary J. Morin said...

Thanks! This was a great help to me with a mulivalue number field that was misbehaving. This along with the explanation of customer converters on the Designer wiki (http://www-10.lotus.com/ldd/ddwiki.nsf/dx/converters-on-an-xpage.htm) solved my problem.