updating template with response in Ember after create/update action - ember.js

I am working on a simple CRUD app using ember js. I have a template with a input form which sends data to the server and server responds with success response.
input form data: "user": {"id": 1, "name": "John"};
server response: {"message":"Created successfully", "nextId": 2}.
I want to display the success message on the same template(one with the input form). Because template refers to the user model and user model does not have a message attribute. How can it be done? Please help.
Here is my code:
var Manager = Ember.Application.create();
Manager.Router.map(function() {
this.resource('users');
this.resource('user', {path: '/users/:user_id'});
this.resource('home', {path: '/'});
});
Manager.UserRoute = Ember.Route.extend({
model: function(params) {
return jQuery.getJSON("http://localhost:8085/users/"+ params.user_id);
},
actions :{
insert : function(){
var user = this.modelFor("User");
$.ajax({
url: "http://localhost:8085/Users",
data: JSON.stringify(user),
type: "POST",
contentType: "application/json",
})
.done(function(data){
//set data.message to display on UI
})
}
}
});
and my template looks like this:
<script type="text/x-handlebars" data-template-name="user">
<form class="form-horizontal" role="form" {{action "insert" on="submit"}}>
<div class="form-group">
<label for="userId" class="control-label col-xs-2">User Id</label>
<div class="col-xs-4 input-group">
{{input type="number" value=_id class="form-control" id="userId" placeholder="Identity"}}
</div>
</div>
<div class="form-group">
<label for="name" class="control-label col-xs-2">Name</label>
<div class="col-xs-4 input-group">
{{input type="text" value=name class="form-control" id="name" placeholder="Name"}}
</div>
</div>
{{#if message}}
<div class="alert alert-success input-group" role="alert">{{message}}</div>
{{/if}}
<div class="form-group button-center">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</form>
</script>

Set the message property on your controller to the response that comes back.
actions :{
insert : function(){
var user = this.modelFor("User");
var self = this;
$.ajax({
url: "http://localhost:8085/Users",
data: JSON.stringify(user),
type: "POST",
contentType: "application/json",
})
.done(function(data){
//set data.message to display on UI
self.controllerFor('user').set('message', data.message);
})
}
}

Related

Loading data that isnt on the route?

I have a dropdown setup on a form but how do i set it up if my data isnt in the route? I am trying to load in a list of territories on a new dealer form. I have added ember-power-select add on but I cant figure out how to load the data to the add on to display the available options. Do I need to create a service or controller?
New to ember just trying to work through the basics.
Router.map(function() {
this.route('login');
this.route('admin', function() {
this.route('territory', function() {
this.route('new');
this.route('edit', { path: '/:territory_id/edit'});
this.route('view', { path: '/:territory_id/view'});
});
this.route('dealer', function() {
this.route('view', { path: '/:dealer_id/view'});
this.route('new');
});
});
});
This is my form I am using on creating a new item.
<div class="well">
<form class="form-horizontal">
<fieldset>
<legend>New Dealer</legend>
<div class="form-group">
<label for="inputFirstName" class="col-lg-2 control-label">Name</label>
<div class="col-lg-4">
{{input type="text" value=model.dealerName class="form-control" placeholder="Dealer Name"}}
</div>
</div>
<div class="form-group">
<label for="inputFirstName" class="col-lg-2 control-label">Territory</label>
<div class="col-lg-4">
{{#power-select selected=dealer options=dealer onchange=(action "chooseDestination") as |dealer|}}
{{dealer.dealerName}}
{{/power-select}}
</div>
</div>
<div class="form-group">
<div class="col-lg-10 col-lg-offset-2">
{{#link-to 'admin.dealer' class="btn btn-default"}}Cancel{{/link-to}}
<button type="submit" class="btn btn-primary" {{action 'saveDealer' model}}>Submit</button>
</div>
</div>
</fieldset>
</form>
</div>
Just because a route is the new action for a territory or the view action for a dealer, doesn't mean that you can't load other data there.
For example, in the territory/view route, you could load all the dealers.
import Ember from 'ember';
export default Ember.Route.extend({
model(params) {
return Ember.RSVP.hash({
territory: this.store.find('territory', params.territory_id),
dealers: this.store.findAll('dealer')
})
}
});
Then in your controller and templates, you would have access to model.territory and model.dealers

Does Making an AJAX call make a DJANGO form Invalid?

I make an ajax call to my server using the change event on a select widget. Does this cause the Django Form to be invalid? Here is an example of the code.
JAVASCRIPT
<form class="form-horizontal" action="{% url 'accountSelections' %}" method="post">
{% csrf_token %}
<div class="form-group">
<div class="row">
<div class="col-md-4">
{{ account_selection_form|crispy }}
<input class="btn btn-primary" id="button" type="Submit" value="Next >>">
</div>
<div class="col-md-4">
</div>
<div class="col-md-4">
<div id="grid"></div>
</div>
</div>
</div>
</form>`
$( document ).ready(function() {
$("#id_excludeClassification").SumoSelect();
var token = $('input[name="csrfmiddlewaretoken"]').prop('value');
$( "#id_acctFilterName" ).change(function() {
var data = "";
$.ajax({
type:"GET",
url : "../filter",
data : "id="+$(this).val(),
csrfmiddlewaretoken: token,
success : function(response) {
$("#grid").kendoGrid({
data: response,
height: 550,
groupable: true,
sortable: true,
columns: [
{
field: "acctCd",
title: "Code"
}, {
field: "shortName",
title: "Account Name"
}]
});
var grid = $("#grid").data("kendoGrid");
dataSource = new kendo.data.DataSource({
data: response
});
grid.dataSource = dataSource;
dataSource.read();
grid.refresh();
data = response;
return response;
},
error: function() {
alert('Error occured');
}
});
});
});
Does a form submit after cause this to make the form invalid?
My understanding is that you can submit multiple times with the same CSRF token, so it shouldn't be a problem.
you put your csrfmiddlewaretoken variable out data object that you send to your server then it can't work.
Here is what you have to do :
data : {
id : $(this).val(),
csrfmiddlewaretoken: token,
}

On submit can't get data from checkbox selection

Hi in my apps I have a form with checkbox group, and I can't retrived selected at submit.
Here is some code
The form content from declare.handlebars:
<form class="declare">
<div class="hidden-fields" style="display:none">
{{view Ember.TextField valueBinding="declaration_type" class="form-control half" type="text"}}
</div>
<fieldset>
...
</fieldset>
<fieldset>
<div class="form-group">
<label>Type de support</label>
<p>
{{render 'publication/declaration_support_types' Sampick.supportTypes}}
</p>
</div>
...
</fieldset>
<div class="actions-bottom">
<button {{action "sendDeclaration" content}} class="button button-select"><i class="icon-download"></i> Confirm</button>
</div>
</form>
The handlebars code for the render of publication/declaration_support_types:
{#each }}
<label class="checkbox-inline">
{{input type="checkbox" name="publication_declaration_support_type" checked=isChecked}} {{ description }}
</label>
{{/each}}
Then I have the following controller for the render 'publication/declaration_support_types':
Sampick.PublicationDeclarationSupportTypesController = Ember.ArrayController.extend({
sortProperties: ['description'],
sortAscending: false,
itemController: 'publicationDeclarationSupportType',
selected: Ember.computed.filterBy('[]', 'isChecked', true),
selectedItems: Ember.computed.mapBy('selected', 'description')
});
Sampick.PublicationDeclarationSupportTypeController = Ember.ObjectController.extend({
isChecked: false,
toggle: function() {
this.toggleProperty('isChecked');
}
});
and finaly the route for the previous html
Sampick.PublicationDeclareRoute = Ember.Route.extend({
actions: {
sendDeclaration: function(content) {
var self = this;
if (content.get("prints") == 1) {
self.validateRecipient(content);
} else {
self.submitDeclaration(content);
}
}
}
});
My issue is that in my sendDeclaration action I can't get the selected checkbox from declarationSupportTypes using the selectedItems propertie define in the controller.
Thanks for your helps
Working fiddle: http://emberjs.jsbin.com/legozucega/1/
There was a typo in IndexRoute, action=>actions.

Ember - Bind fail when transition back to login view

When i first go the my login url, the inputs are correctly binded to the properties on my controller.
Then a press logout and what it does is transition back to the login page.
When i try to login again, it fails, because the input values arent binded to the controller, additionally i get this error:
Uncaught Error: Assertion Failed: Attempted to register a view with an id already in use: login
If i refresh the page it works.
Some of my code for references:
LoginRoute
export
default Ember.Route.extend({
setupController: function(controller) {
controller.reset();
},
beforeModel: function() {
if (!Ember.isEmpty(this.controllerFor('sessions.login').get('token'))) {
this.transitionTo('promotions');
}
}
});
LogoutRoute
export
default Ember.Route.extend({
beforeModel: function() {
this.controllerFor('sessions.login').reset();
this.transitionTo('sessions.login');
}
});
LoginAction on Controller
loginUser: function() {
var _this = this;
var login = this.get("login");
var pass = this.get("password");
Login Form
<form role="form" {{action 'loginUser' on='submit'}}>
<div class="form-group">
{{input type="text" class="form-control" id="login" placeholder="Login" value=login autofocus="autofocus"}}
{{input type="password" class="form-control" id="password" placeholder="Password" value=password}}
</div>
<div class="form-group">
<span class="input-group-btn">
<button class="btn btn-default" type="submit" ><span>Entrar</span></button>
</span>
</div>
</form>
After testing some more, i saw that the textFields are duplicating when i transition back to this page.
I really can't figure out, why

Ember - displaying model value in form field

I have a user settings form like so:
<script type="text/x-handlebars" data-template-name="settings">
<form class="form-horizontal user-form" {{action "update" on="submit"}}>
<div>
<label>First Name</label>
{{input type="text" value=firstName placeholder="First Name"}}
{{error.firstName}}
</div>
<div>
<label>Last Name</label>
{{input type="text" value=lastName placeholder="Last Name"}}
{{error.lastName}}
</div>
<div>
<label>Email Address *</label>
{{input type="text" value=email placeholder="Email Address"}}
{{error.email}}
</div>
</form>
</script>
In my route for this page, I define the model:
App.SettingsRoute = Ember.Route.extend({
model: function() {
return this.store.find('user', 1);
}
});
If things are left like this, the form will automatically populate with the values retrieved from the model. However, if I add a controller:
App.SettingsController = Ember.Controller.extend({
actions: {
update: function() {
// Do something
}
}
});
...They won't. So how do I use my model in conjunction with this controller to set the properties?
The way you defined your controller was as a regular Ember.Controller and not an Ember.ObjectController so the controller is not proxying the model. If you modify it to be like this:
App.SettingsController = Ember.ObjectController.extend({
actions: {
update: function() {
// Do something
}
}
});
Then it should still automatically populate with the values from the model.