#ember-power-select, How to set a preselected value in ember-power-select custom-search-action

There must be a value set in “selected” attribute before typing in search parameter".Can anyone help me to sort this out ? #ember-power-select.

It is working with normal action-handling by setting a value for “destination” in js and assigning “destination” to “selected”. Have a look at here for such examples http://www.ember-power-select.com/docs/action-handling.

But can’t assign a value for custom-serach-action http://www.ember-power-select.com/docs/custom-search-action.

  • model

hpqualifcation.js

import DS from 'ember-data';
export default DS.Model.extend({
 type_name: DS.attr('string'),
 hoprofile: DS.belongsTo('hoprofile')
});

hoprofile.js

import DS from 'ember-data';
export default DS.Model.extend({
  name: DS.attr('string'),
  hpqualification: DS.hasMany('hpqualification')
});
  • routes
import Ember from 'ember';
model: function(params){
 return Ember.RSVP.hash({
  hpqualifications: this.store.query('hpqualification', {username: params.username}),
  …
  …
 });
}
  • data from API side
    "hpqualification": [
        {
            "id": 1,
            "type_name": "UG",
            "hoprofile": 1
        },
        {
            "id": 1,
            "type_name": "PG",
            "hoprofile": 2
        }
    ],
    "hoprofile": [
        {
            "id": 1,
            "name": "silicon guy",
            "hpqualifications": [1]
        },
        {
            "id": 2,
            "name": "power star",
            "hpqualifications": [2]
        }
    ]
}
  • templates

Used ember-power-select custom-search-action, where the request will be sent to API side for typing each letter and the data returned will be displayed in select box options http://www.ember-power-select.com/docs/custom-search-action.

{{#each model.hpqualifications as |hpqualification|}}
{{#power-select
  selected=hpqualification.hoprofile.name
  search=(action "hoProfile")
  onchange=(action (mut hpqualification.hoprofile.name))
  as |repo|
}}
  {{repo.name}}
{{/power-select}}
{{/each}}
  • components
import Ember from 'ember';
export default Ember.Component.extend({
actions: {
  hoProfile(term){
    if (Ember.isBlank(term)) { return []; }
    const url = `//localhost:3000/betaweb/filters/hoprofiles?  name=${term}`;
    return Ember.$.ajax({ url }).then(json => json.hoprofiles);
  }
}
});
  • data returned for power-select action
    "hoprofiles": [
        {
            "id": 7,
            "name": "silicon guy"
        },
        {
            "id": 14,
            "name": "power star"
        }
    ]
}

Everything is working fine. But in ember-power-select the preselected value is not getting selected. The select box is blank before typing in search parameter . normally using the below code the value is visible

{{#each model.hpqualifications as |hpqualification|}}
 <label>HO Profile Name<label>
 <li> {{input value=hpqualification.hoprofile.name}} </li>
{{/each}}

It displays all the data that is returned from API side.

HO Profile Name
- silicon guy
- power star 

But when i use ember-power-select the data is not getting preselected in select box. I have tried many ways but it didn’t sort me out. Can anyone please get me a solution or an alternate way to do this using power-select ?

1 Like

+1 , I had a similar issue with ember-power-select. Exactly in async search with belongsto / HasMany relationship.

Posted an issue in github see the issue here

If you got some working example code , please share with me. I am plucking my hair for a couple of days. Thanks in advance.

yeah got it solved. I modified my js in the following way:

Change your request from,

hoProfile(term){
    if (Ember.isBlank(term)) { return []; }
    const url = `//localhost:3000/betaweb/filters/hoprofiles?  name=${term}`;
    return Ember.$.ajax({ url }).then(json => json.hoprofiles);
}

to the following way,

hoProfile(term){
  if (Ember.isBlank(term)) { return []; }
    return this.get('store').query('hoprofile', {name: term});
}

The problem is in search action. Because it is returning regular json objects, and when assigning them with the (mut) action, it wont really change the reference, it will just rename existing object. So i tried querying the data using “store.query” method.

Finally it got worked !

i still have issue, could you please share me the template file and controller file with those corresponding actions. I guess i could pick it up from there. , okay i use json api adapter , some customization needed for me.

Any way let me try once more.

Thanks for urgent help

And meanwhile i am glad to hear there are ember devs in chennai. i am from kochi, i thought there wont be any job opportunities in india for ember. Does ember have a chance in india? how do you feel in chennai? Still feeling demand? The company i works (its a startup) scold me every day for choosing ember for a big project. I am now responsible to fix these kind of bugs. Well have a good day.

Try changing the "selected "attribute by setting the value “orderitem.productname”

For example:

{{#each orderitems  as |orderitem|}}
{{#power-select
  search=(action "searchProduct")
  selected=orderitem.productname
  onchange=(action "selectOrderitem" orderitem.id)
  as |repo|
}}
  {{repo.attributes}}
{{/power-select}}
{{/each}}

Could you provide the response data from your API side for the below request ?

searchProduct(term) {
  if (Ember.isBlank(term)) { return []; }
  const url = `/products?direction=asc&page=1&productname=${term}`;
  return this.get('ajax').request(url).then(json=>json.data);
}

By the way , here we started up our company and We are building our own product. Even we are new to Ember.js and struggling in some parts, since there are no proper guide.

Thanks,

could you please give a sample action for “selectOrderitem” action?

The response i get from api is

{"data":{"id":"35","type":"orderitems","attributes":{"product":{"id":1,"itemcode":"itemonecode","productname":"Select Product","initialstocklevel":100,"initialcostprice":100,"buyprice":200,"retailprice":250,"supplier_id":1,"producttype_id":1,"productbrand_id":1},"quantity":1,"total":null,"orderitemstatus":null},"relationships":{"order":{"data":{"id":"1","type":"orders"}},"product":{"data":{"id":"1","type":"products"}}}}}

and instead of selected=orderitem.productname , i have to set orderitem.product.productname

bcoz my model relationships are like this

The models have a relationship like this

//models/order.js.js
orderitems: DS.hasMany('orderitem' ,{embedded: 'always', async:true}),
//models/orderitems.js
 order: DS.belongsTo('order' ,{async:true}),
product: DS.belongsTo('product' ,{async:true}),
//models/product.js
itemcode: DS.attr('string'),
productname: DS.attr('string'),

========================================================================

Test Results 1:


After trying these codes

{{#power-select
  search=(action "searchProduct")
  selected=orderitem.product.productname
  onchange=(action (mut orderitem.product.productname))
  as |repo|
}}
  {{repo.attributes.productname}}
{{/power-select}}
  searchProduct(term) {
            if (Ember.isBlank(term)) { return []; }
            const url = `/products?direction=asc&page=1&productname=${term}`;
            return this.get('ajax').request(url).then(json=>json.data);
          },

Result:

i got the product name changing , but it doesn’t change the corresponding product of the orderitem.

Any clue?

==========================================================================

Test Result 2:


{{#power-select
      search=(action "searchProduct")
      selected=orderitem.product.productname
      onchange=(action (mut orderitem.product.productname))
      as |repo|
    }}
      {{repo.productname}}
    {{/power-select}}
  searchProduct(term) {
            if (Ember.isBlank(term)) { return []; }
            return this.get('store').query('product', {productname: term});
          },

Result:

1)I got the product name changing but it changes for all the orderitems in the list simultaneously . 2)Even the product name changes , it doesn’t change the product object itself.

Is there any way to change the “orderitem.product” with a custom action rather than (action (mut orderitem.product.productname))?

try the below code. I have changed the attribute name for #each to avoid confusion.

{{#each orderitems  as |order|}}
{{#power-select
  search=(action "searchProduct")
  selected=order.product
  onchange=(action "selectOrderitem" order)
  as |repo|
}}
  {{repo.attributes.product.productname}}
{{/power-select}}
{{/each}}
searchProduct(term) {
  if (Ember.isBlank(term)) { return []; }
  const url = `/products?direction=asc&page=1&productname=${term}`;
  return this.get('ajax').request(url).then(json=>json.data);
}
selectOrderitem(order, selected){
  return this.store.findRecord('orderitem', selected.id).then(product => order.set('orderitem', product));
}

Even try querying the data using “store.query” method. Similar to this,

searchProduct(term) {
  if (Ember.isBlank(term)) { return []; }
  return this.get('store').query('yourmodelname', {name: term});
}

Thanks brother ! It worked great

But now the product name text is not changing. Since we are not using the mut function to change the text. Any solutions?
But i could change the corresponding object now

1)if we go with

selected=orderitem.product
onchange=(action(mut orderitem.product.productname)

The text is changing , but the object wont

  1. if we go with
      selected=orderitem.product
      onchange=(action "selectOrderitem" orderitem)

the object will change but the text wont.

is there a way to change the object and the text simultaneously?

    {{#power-select
      search=(action "searchProduct")
      selected=orderitem.product.productname
      onchange=(action "selectOrderitem" orderitem)
      as |repo|
    }}
      {{repo.attributes.productname}}
    {{/power-select}}
  selectOrderitem( orderitem , selected){
    return this.store.findRecord('product', selected.id).then(function(product){
      orderitem.set('product',product);
    });
  },

  searchProduct(term) {
            if (Ember.isBlank(term)) { return []; }
            // return this.get('store').query('product', {productname: term});

            const url = `/products?direction=asc&page=1&productname=${term}`;
            return this.get('ajax').request(url).then(json=>json.data);
          },

Thanks again. I was plucking hair for days.

Would you mind referring me some useful articles or books you found better

No luck in changing the text and object simultaneously

Did you tried changing the request to this type ?

searchProduct(term) {
  if (Ember.isBlank(term)) { return []; }
  return this.get('store').query('yourmodelname', {name: term});
}

yes,

i tried like this

searchProduct(term) {

         return this.get('store').query('product', {productname: term});
          },

    {{#power-select
      search=(action "searchProduct")
      selected=orderitem.product.productname
      onchange=(action  "selectOrderitem" orderitem)
      as |repo|
    }}
       {{repo.productname}}
    {{/power-select}}

but still not getting the product name selected.

Will the product name changes without using mut function?

as you can see, the objects are gettting selected , but product name not changing.

change

selected = orderitem.product

insted of

selected = orderitem.product.productname
searchProduct(term) {
  return this.get('store').query('product', {productname: term});
}
    {{#power-select
      search=(action "searchProduct")
      selected=orderitem.product
      onchange=(action  "selectOrderitem" orderitem)
      as |repo|
    }}
       {{repo.productname}}
    {{/power-select}}

Hi,

Thanks for giving me a hand so far,

It’s now setting the product name and object , No problem ,

But now the issue is , after setting the first product , when i search for the second product , the first one gets reset to default value. Any idea why this is happening.

This occurs when i starts type in the search bar for the next product .

Sorry for troubling.


    {{#power-select
      search=(action "searchProduct" )
      selected=orderitem.product
      onchange=(action  "selectOrderitem" orderitem)
      as |repo|
    }}
       {{repo.productname}}
    {{/power-select}}
  selectOrderitem( orderitem , selected){
    return this.store.findRecord('product', selected.id).then(product => orderitem.set('product', product));
  },

  searchProduct(term) {
          if (Ember.isBlank(term)) { return []; }
           return this.get('store').query('product', {productname: term});
        },

I think the problem may be with your json format. I’m unfamiliar with JSONAPIadapter. Try changing the response data