piceaTech / ember-rapid-forms

Smart, Intuitive forms for Ember.js styled with Bootstrap, Multi layouts and Validation support.
http://piceatech.github.io/ember-rapid-forms
Apache License 2.0
58 stars 33 forks source link

Input of type "date" does not prefill when bound to ember model date-type attribute #187

Closed jzisser9 closed 6 years ago

jzisser9 commented 6 years ago

I am inserting an input element of type "date" and binding it to an attribute from the model that is also a date:

model.js

import DS from 'ember-data';

const {attr} = DS;

export default Model.extend({
  counter: attr('number'),
  submittedOn: attr('date'),
  ...
});

template using ember-rapid-forms:

{{#em-form model=model as |form|}}
    {{form.input type="date" property="submittedOn"}}
{{/em-form}}

The form element binds to the submittedOn property of the model successfully, and I can see the value changing in the Ember console as I use the date picker, but the element will not display the initial value of model.submittedOn, it only displays values I've selected using the date picker. This is not the case for, say, model.counter - the input element for that will pre-load with the current value of model.counter.

Am I doing something wrong, or is this a bug?

jzisser9 commented 6 years ago

Nevermind, found the problem - I'll leave the answer here in case it helps anyone else.

An input element of type "date" will store its value as an ISO string. An Ember model with a date attribute will, surprisingly, store it as a date. The form element can't convert a Date object into the correct format for the input to display it, so I had to do a little legwork to make the conversion.

In my case, I created a new computed property on the component that houses the rapid form. It converts the date into an ISO string (thanks to a little help from moment.js), and bound the input to that computed property:

submittedOn: Ember.computed('model.submittedOn', {
  get() {
    return moment(this.get('model.submittedOn')).utc().toISOString();
  }
});

The form input is now correctly pre-loaded with the existing model value. When I want to save the value to the model, I convert it back to a Date object when I hit the submit button:

this.set('model.submittedOn', new Date(this.get('submittedOn')));

This might actually be a larger topic about using ember-rapid-forms for CRUDs on ember models and how that can be improved.

GCorbel commented 6 years ago

Thanks for sharing your solution. I think we may do something like em-input format='date' to convert data automatically. What you think? Are you ready to do a contribution?

jzisser9 commented 6 years ago

@GCorbel I'm sure I could spend some time this weekend getting a PR together. :)