Get value from selected form in EmberJS and ember-data

I am new to Ember and I am building an application with some model relationships.

These are my models.

// models/user.js
export default DS.Model.extend({
  name: DS.attr('string'),
  role: DS.belongsTo('role')
});

// models/role.js
export default DS.Model.extend({
  name: DS.attr('string'),
  description: DS.attr('string')
});

My new user route

import Ember from 'ember';

export default Ember.Route.extend({

  model: function(){
    return Ember.RSVP.hash({
      newUser: this.store.createRecord('user'),
      roles: this.store.findAll('role'),
    });
  }
});

The idea is to get roles and choose as a choice in the form

This is my new user template.

<form {{ action "save" on="submit" }}>
  {{ input value=newApplicant.name class="form-control" }}
  <select name="role" class="form-control" value="role.value">
       {{#each model.roles as |role|}}
             <option value="{{role.id}}">{{role.name}}</option>
       {{/each}}
  </select>

While this step is all right, I have my choice with the relevant data, but I want to save. I do not know how to get the role identifier from the form and insert it to the user

This is my new controller.

import Ember from 'ember';

export default Ember.Controller.extend({

newUser: Ember.computed.alias('model.newUser'),
roles: null,
// roles: Ember.computed.alias('model.roles'),


actions: {
  save() {
    var role = this.get('role.value');
    console.log(role);
    //this.get('newUser').save().then((user) =>
    //  this.transitionToRoute('users', user.get('id'))
    //);
  },
});

I did some experiments, but nothing worked. When I click the Save button, send the null value in the role to the server JSON request.

I follow this guide http://thau.me/2014/11/ember-data-mastering-async-relationships-part-2/

But when I try to filter, I got Null.

? ?

, Ember 2 ember 2

+4
1

, .

. twiddle .

select . value="" onchange.

<select name="role" class="form-control" onchange={{action "updateValue" value="target.value"}}>
 {{#each model.roles as |role|}}
  <option value="{{role.id}}">{{role.name}}</option>
 {{/each}}
</select>

, , updateValue role.value, save

actions:{
  updateValue: function(value) {
    this.set('role.value', value);
  },
  save() {
   var role = this.get('role.value');
   console.log(role); // Now this should work
  }
}

, select value.

, , select -. ember-power-select.

+5

Source: https://habr.com/ru/post/1622976/


All Articles