Search code examples
ember.jsember-cli

How to access the variable of a Route from a template in ember


I am trying to do form validation in ember using ember actions.

Below is my add.js(route):

    export default Route.extend({
    errorMessage: '',
    model() {
        return this.store.createRecord('contact');
    },
    actions: {
        saveContact(contact) {
            if (contact.get('firstname') === undefined || contact.get('lastName') === undefined || contact.get('mobile') === undefined) {
                this.set('errorMessage', `Some Fields are blank!!`);
            } else {
                this.set('hasBlank', false);
                this.set('errorMessage', "");
                contact.save().then(() => {
                    this.transitionTo("contacts")
                })
            }
        }
    }
});

This is my template code:

<h1>Add Contact</h1>
<div class="full-width">
    <div>{{input class="form-tag half-width" type="text" placeholder="Enter firstName" value=model.firstName}}</div>
    <div>{{input class="form-tag half-width" type="text" placeholder="Enter lastName" value=model.lastName}}</div>
    <div>{{input class="form-tag half-width" type="number" placeholder="Enter mobile Number" value=model.mobile}}</div>
    <button class="form-button half-width" {{action 'saveContact' model}}> Add </button>
{{#if errorMessage}}
     <div class="form-tag half-width">{{errorMessage}}</div>
{{/if}}
</div>

In this template errorMessage field is not showing when there is blank form fields.But it is showing up if I am logging it in my console.

Can Somebody help me out?



Thanks in Advance


Solution

  • errorMessage and your action saveContact should be on the corresponding controller rather than the route. If you haven't created the corresponding controller, you can do so with ember generate controller <controller-name>. Your controller name should correspond to the name of your route.

    BTW, you will need to use transitionToRoute rather than transitionTo when you make that call from a controller action.