Christian Fazzini
Christian Fazzini

Reputation: 19723

How should I get the value of this input field?

I am using a subexpression at {{input value=(cents-to-dollars model.amountInCents)}}. It is using a custom helper to convert the value from cents to dollars. My API returns cents.

However in the controllers save action, console.log(this.get('model.amountInCents')); returns undefined. Am I missing something? Maybe name or valueBinding in the input helper?

If I remove the subexpression. console.log(this.get('model.amountInCents')); outputs fine.

// Routes
import Ember from 'ember';

export default Ember.Route.extend({
  model: function(params) {
    return this.store.find('product', params.product_id);
  }
});

// Controller
export default Ember.Controller.extend({
  actions: {
    save: function() {
      console.log(this.get('model.amountInCents')); // returns undefined
      var _this         = this;
      var dollars       = this.get('model.amountInCents');
      var amountInCents = dollars / 100;

      this.get('model').set('amountInCents', amountInCents);

      this.get('model').save().then(function(product){
        _this.transitionToRoute('admin.products.show', product);
      }, function() {
        // Need this promise, so we can render errors, if any, in the form
      });

      return false;
    },
    cancel: function() {
      this.transitionToRoute('products.show', this.get('model'));
    }
  }
});

// Template
<form {{action "save" on="submit"}}>
  <p>
    <label>Name:
      {{input value=model.name}}
    </label>
  </p>

  <p>
    <label>Amount in cents:
      {{input value=(cents-to-dollars model.amountInCents)}}
    </label>
  </p>

  <input type="submit" value="Save"/>
  <button {{action "cancel"}}>Cancel</button>
</form>

Upvotes: 2

Views: 1267

Answers (1)

Kalman
Kalman

Reputation: 8131

First of all, (at least in version 1.9.1) what you are proposing doesn't really work (see here - the value appears outside of the input field). The real problem, I think, is that you are not binding to a property and instead are binding to a string returned from a helper (which is not what you want).

So, what can you do?

You can set up a dollars computed property as follows:

App.IndexController = Ember.ObjectController.extend({
  dollars: function(key, value){
    if (arguments.length > 1) {
      var dollars = value;
      this.set('amountInCents', parseInt(dollars) * 100);
    }

    return this.get('amountInCents') / 100;
  }.property('model.amountInCents')
});

Full working example here

Upvotes: 2

Related Questions