Search code examples
dateember.jsdatatablemomentjsember-cli

Using Moment.js in Ember Controller inside a computed function using data-table columns


I was wondering if it is possible to apply a Date format of MM-DD-YYYY to the valuePath of a Data-Table Column array within a controller for an Ember route.

My controller.js:

columns: computed(function() {
    return A([{
            valuePath: 'firstName',
            label: get(this, 'i18n').t('page.firstName'),
            cellClassNames: 'cell-valign-middle',
            sortable: true,
        }, {
            valuePath: "lastName",
            label: get(this, 'i18n').t('page.lastName'),
            cellClassNames: 'cell-valign-middle',
            sortable: true,
        }, {
            valuePath: "dateOfBirth",
            label: get(this, 'i18n').t('page.dateOfBirth'),
            cellClassNames: 'cell-valign-middle',
            sortable: false,
        },
    ]);
}),

template.hbs

{{#data-table 
  columns=columns 
  models=model 
  sort=sort 
  isLoading=isLoadingModels 
  responsive=true}}
{{/data-table}}

My goal is to turn valuePath for dateOfBirth to a Date format of MMDDYYYY using moment.js.

I have tried moment("dateOfBirth").format("MMDDYYYY") without success.


Solution

  • Ideally, there would be a 'format' attribute in the configuration of each column, so you can define a format method.

    Another method would be since the table will query the model for the attribute 'valuePath', you can have a computed directly in the model to return the formatted date.

    models/user.js

     formatted: Ember.computed('dateOfBirth', function () {
        const dateOfBirth = this.get('dateOfBirth');
        return moment(dateOfBirth).format('MMDDYYYY')
      })
    

    p.d.: I'm not sure which plugin for tables you are using. If you could post it here I can dig more into the documentation.