I have a component that I call from a for
loop in a template and use just to display a model values:
# templates/holiday_hours.hbs
<form {{action "updateHolidayHours" on="submit"}}>
{{#each model as |holidayHour|}}
{{holiday-row holiday=holidayHour}}
{{/each}}
...
Like this, I display several rows with values to update. I’d like to make it possible to a create a new row and reuse the same component template.
Here is the template code
<form {{action "updateHolidayHours" on="submit"}}>
{{#each model as |holidayHour|}}
{{holiday-row holiday=holidayHour}}
{{/each}}
{{#if isAddingHoliday}}
<form {{action "createHoliday" on="submit"}}>
{{#holiday-row holiday=model}}
<div class="form-check sm-2">
<button type="button" type="submit" class="btn btn-success btn-sm">
<span class="oi oi-plus"></span>
{{t 'buttons.add'}}
</button>
</div>
<div class="form-check ml-sm-2">
<button type="button" class="btn btn-danger btn-sm" onclick={{action "cancelAddHoliday"}}>
<span class="oi oi-x"></span>
{{t 'buttons.cancel'}}
</button>
</div>
{{/holiday-row}}
</form>
{{else}}
<button type="button" class="btn btn-success btn-sm mb-2" onclick={{action "addHoliday"}}>
<span class="oi oi-plus"></span>
{{t 'buttons.new.language'}}
</button>
{{/if}}
<div class="float-right">
<button type="submit" class="btn btn-success">{{t 'buttons.save'}}</button>
</div>
</form>
isAddingHoliday
is a just a flag to flip to indicate if I should display a new row with empty fields or not. Here is how it is triggered in the corresponding controller:
# controllers/holiday-hours.js
import Controller from '@ember/controller';
import { inject as service } from '@ember/service';
export default Controller.extend({
currentShop: service('current-shop'),
isAddingHoliday: false,
actions: {
addHoliday() {
this.set('isAddingHoliday', true);
this.set('model', this.store.createRecord('holiday-hour'));
},
cancelAddHoliday() {
this.set('isAddingHoliday', false);
}
}
});
I tried to call
this.set('model', this.store.createRecord('holiday-hour'));
But it erased my previously loaded model values.
Here is how it looks before clicking on New holiday
button:
Here is what it looks like after clicking on New holiday
button:
Here is what it looks like after clicking on Cancel
button:
The model
hook in the route handler is very basic:
#routes/holiday-hours.js
...
model() {
return this.store.query('holiday-hour', { shop_id: this.get('currentShop.shop').get('id')});
},
What is the right way to do that ? Thank you.