b1tch2c0d3


YUI Datatable – Custom Parser Example
May 23, 2009, 5:57 pm
Filed under: yui | Tags: , ,

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).

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 somone 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 - argh!
    // 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);
Advertisement

Leave a Comment so far
Leave a comment



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s



Follow

Get every new post delivered to your Inbox.