YUI Datatable – Custom Parser Example

For entry, with my validator, I am validating that no matter what a user types in for a height, I convert it to a float to store in the database (5.10). In retrospect, I should convert it to the inches value, but this example isn’t doing that.

For display, with my formatter, I am standardizing the format to display as a proper height (5′ 10″).

All that is left is to get the column sort to not think someone that is 22′ tall is shorter than someone that is 3′ tall. For numbers to sort numerically, the type must be a Number, not a String. This could be easily accomplished with YAHOO.widget.DataTable.formatNumber, but I was hoping to be able to fix my problem of 5.10 changing to 5.1 here. I was not able to do that, as you can see by the commented out line below, so I took care of it in the validator (kinda).

Due to the lack of me finding, quickly, an example of a custom parser, I am posting this anyway, even though it is not really needed.

The parser is an object property defined in the array of objects defining the fields for the datasources responseSchema (assuming JSON).

STWPT.parseHeight = function (oData)
{
    oData = parseFloat(oData);    // convert to number (float)
 
    // force decimal precision (5.1 > 5.10)
    // this converts it back to a string
    // oData = oData.toFixed(2);     
 
    return oData;
}

The following is a snippet out of a larger script that shows just the pieces that connect the datatable creation to the custom parser shown above.

var myDataSource = new YAHOO.util.DataSource('/path/to/datasource');
myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
myDataSource.connMethodPost = true;
myDataSource.responseSchema = {
    resultsList: 'athletes',
    fields: [
        { key: 'first_name', parser: 'string' },
        { key: 'last_name', parser: 'string' },
        { key: 'height', parser: STWPT.parseHeight }
    ]
};
 
var myDataTable = new YAHOO.widget.DataTable('athletes-datatable', myColumnDefs, myDataSource);

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">