DisplayField - How to format for date?

John Gordon picture John Gordon · Dec 7, 2010 · Viewed 16.8k times · Source

I need to display a read only view of data. I've chosen the DisplayField component to do this. My problem is that I would like an easy way to call BasicForm.setValues(values) and have a date string automagically render correctly in one of the displayFields. I haven't found anything that will do this for me (e.g. a renderer function), and am about to just format the date string manually prior to calling setValues(values). Is there some slick way to do this?

Thanks!

Answer

Bruce picture Bruce · Dec 15, 2010

Ok if you are using a direct form load then you need to listen for the form's BasicForm 'actioncomplete' event. When this event fires the handler is supplied two arguments. The first is the BasicForm and the second argument is an Ext.form.Action object. We are specifically looking for an Ext.form.Action.Load object. From here we get access to the action's result.data object and we can massage the data values before this handler returns and the values are loaded into the form.

function fmtDate(sf, rec) {
  if ( rec[sf] ) {
    var dt = new Date(); dt.setTime(rec[sf] * 1000); return dt.format('l j F Y');
  }
};

myForm.getForm().on({
  actioncomplete: function(form, action) {
    if (action.type === 'load') {
      if (action.result.success) {
        var data = action.result.data;
        data.someFormattedDate = fmtDate('myDateTS', data);
      } else {
        //handle an error here
      }
    }
  }
});

Now all you need in your form is a displayField named 'someFormattedDate' and Bob's your uncle (Aussie slang for it's all good). You can also achieve exactly the same thing by providing a 'success:' function to your myForm.getForm().load() call. See the ExtJS docs for Ext.form.Action.Load. Cheers, t00bs.