Backbone ModelBinder, not filling when model is fetched - backbone.js

Maybe I'm using model binder incorrectly or maybe marionette interferes, but my view and model don't seem to be communicating and therefore not pre-filling my template fields
View
define([
'marionette',
'underscore',
'text!app/views/templates/user/form.html',
'app/models/user'
],
function (Marionette, _, Template, Model) {
"use strict"
return Marionette.ItemView.extend({
events: {
'submit .edit-user-form': 'onClickSave'
},
initialize: function(options) {
/* initiate model binder */
Backbone.ModelBinder.bind(Model, this.$el)
/* create empty model in case its a create request */
this.model = new Model()
/* if the options.id is passed then lets load an instance of the model */
if (options && options.id) {
this.model = new Model({id: options.id})
this.model.set('id', options.id)
/* set that to this so its acceptable inside the fetch */
var that = this
this.model.fetch({
/* fetch request successful */
success: function (response) {
/* set the model instance trigger a re-render */
that.model = response
that.render()
},
/* we couldn't load the model so we go back to the users list */
error: function () {
alert('User could not be loaded, redirecting you to the users list')
window.location.hash = 'users'
}
})
}
},
/* save button triggered so prevent default and trigger the model to save */
onClickSave: function (ev) {
ev.preventDefault()
this.model.save({}, {
success: function (response) {
console.log(response, 'response')
}
})
},
/* render the form */
render: function () {
var html = _.template($(Template).html(), this.model.toJSON())
this.$el.html(html)
return this
}
})
}
)
Template
<script type="text/template" id="userFormTemplate">
<div id="userForm">
<h2><img src="/img/icons/32/update.png" /> Update User</h2>
<h2><img src="/img/icons/32/create.png" /> Create New User</h2>
<form class="edit-user-form">
<fieldset name="personal" class="halfWidth left">
<legend>Personal Details:</legend>
<div class="control-group">
<label class="control-label">First name:</label>
<div class="controls">
<input type="text" name="first_name" id="first_name">
</div>
</div>
<div class="control-group">
<label class="control-label">Last name:</label>
<div class="controls">
<input type="text" name="last_name" id="last_name">
</div>
</div>
<div class="control-group">
<label class="control-label">Birthdate:</label>
<div class="controls">
<input type="date" name="birthdate" id="birthdate">
</div>
</div>
</fieldset>
<fieldset name="job" class="halfWidth right">
<legend>Job Details:</legend>
<div class="control-group">
<label class="control-label">Job Title</label>
<div class="controls">
<input type="text" name="job_title" id="job_title">
</div>
</div>
<div class="control-group">
<label class="control-label">Start Date:</label>
<div class="controls">
<input type="date" name="job_start_date" id="job_start_date">
</div>
</div>
<div class="control-group">
<label class="control-label">Probation Ends:</label>
<div class="controls">
<input type="date" name="job_probation_ends" id="job_probation_ends">
</div>
</div>
</fieldset>
<div class="clearfix"></div>
<br />
<fieldset name="personal" class="halfWidth left">
<legend>Work Details:</legend>
<div class="control-group">
<label class="control-label">Work Email</label>
<div class="controls">
<input type="email" name="work_email" id="work_email">
</div>
</div>
<div class="control-group">
<label class="control-label">Work Address:</label>
<div class="controls">
<input type="text" name="work_address" id="work_address">
</div>
</div>
<div class="control-group">
<label class="control-label">Work Phone Number:</label>
<div class="controls">
<input type="text" name="work_phone_number" id="work_phone_number">
</div>
</div>
</fieldset>
<fieldset name="personal" class="halfWidth right">
<legend>Personal Details:</legend>
<div class="control-group">
<label class="control-label">Personal Email</label>
<div class="controls">
<input type="email" name="personal_email" id="personal_email">
</div>
</div>
<div class="control-group">
<label class="control-label">Home Address:</label>
<div class="controls">
<input type="text" name="personal_address" id="personal_address">
</div>
</div>
<div class="control-group">
<label class="control-label">Home Phone Number:</label>
<div class="controls">
<input type="text" name="personal_phone_number" id="personal_phone_number">
</div>
</div>
</fieldset>
<div class="clearfix"></div>
<br />
<div class="control-group button">
<button class="btn save-form btn-success" type="submit">Create User</button>
</div>
</form>
</div>
</script>

You have to define the bindings, its not automatic.
var bindings = {
first_name: '#first_name',
last_name: '#last_name',
birthdate: '#birthdate',
job_title: '#job_title',
job_start_date: '#job_start_date',
job_probation_ends: '#job_probation_ends',
work_email: '#work_email',
work_address: '#work_address',
work_phone_number: '#work_phone_number',
personal_email: '#personal_email',
personal_address: '#personal_address',
personal_phone_number: '#personal_phone_number'
}

Related

How to get data from html form and save in database(with button) using angularJS?

I want to get data from input boxes and save it in a database with a click on the button. I'm using angular. How can I get this data from my form? Please help me.
I have this HTML code:
<form ng-submit="createUser(userForm.$valid)" name="userForm1">
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label for="database_address">User</label>
<input type="text" class="form-control1" ng-model="usernamee" placeholder="Потребителско Име..." />
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="text" class="form-control1" ng-model="passwordd"required id="password" />
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for="username">Operator</label>
<input type="text" class="form-control1" ng-model="namee" required id="username" />
</div>
</div>
</div>
<button class="btn btn-primary" ng-click="createUser();" type="submit">Add user</button>
<!--<button class="btn btn-primary" ng-disabled="userForm.$invalid" type="submit">Добавяне на нов</button>-->
</form>
And Angular code:
$scope.createUser=function()
{
//console.log($scope.activeItem);
//delete $scope.activeItem.hash_method
var objectToSave = {
username: console.log($scope.usernamee),
password: console.log($scope.passwordd),
name: console.log($scope.namee),
id: $scope.id
};
{
defaultAdapter.query('INSERT INTO users(username,password,name,id) VALUES(username = :usernamee, password = :passwordd,name = :namee WHERE id =:id)',
{ replacements: objectToSave, type: Sequelize.QueryTypes.UPDATE }
).then(projects => {
console.log(projects);
$scope.editMode = false;
$scope.activeItem = false;
$scope.refresh();
});
}
}
<form ng-submit="createUser(userForm)" name="userForm">
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label for="database_address">User</label>
<input type="text" class="form-control1" ng-model="user.usernamee" placeholder="Потребителско Име..." />
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="text" class="form-control1" ng-model="user.passwordd"required id="password" />
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for="username">Operator</label>
<input type="text" class="form-control1" ng-model="user.namee" required id="username" />
</div>
</div>
</div>
<button class="btn btn-primary" type="submit">Add user</button>
</form>
angularjs code
$scope.user={}//declare user object
$scope.createUser=function(userForm)
{
console.log($scope.user);
//for saving data in database, you'll need an API along with the backend.
}
I'm thinking in my application is using "Sequelize" method. Is it possible this method to do this connection with database ?

How to reset form data in $scope.on event?

I have a form control in some directive. I am resetting object data to its original state but it is not working in the $scope.on event. If I use it outside in some function it works.
$scope.$on('edit_view_changed', function (event, parameters) {
if (parameters.viewName === "" && parameters.editIndex === -1) {
vm.resetData();
// this reset data is not working
}
});
function resetData() {
vm.rowData = angular.copy(vm.data);
}
// works properly on cancel button click
function cancelEdit() {
vm.resetData();
$timeout(function () {
vm.editCancelProspect();
});
}
// RowData is bind to a form in a html view.
<form class="col-md-12" name="editForm" novalidate>
<div class="col-md-10">
<div class="form-group col-md-3">
<label class="col-sm-3 control-label">{{'customers.columns.companyName'|translate}}</label>
<input type="text" name="name" class="form-control" ng-model="vm.rowData.name"></input>
</div>
<div class="form-group col-md-4">
<label class="col-sm-3 control-label">{{'customers.columns.address'|translate}}</label>
<input type="text" name="adresse" class="form-control" ng-model="vm.rowData.adresse"></input>
</div>
<div class="form-group col-md-3">
<label class="col-sm-3 control-label">{{'customers.columns.contactPerson'|translate}}</label>
<input type="text" name="kontakt" class="form-control" ng-model="vm.rowData.companyContact"></input>
</div>
<div class="form-group col-md-2 ">
<label class="col-sm-3 control-label">{{'customers.columns.phone'|translate}}</label>
<input type="text" name="phone" class="form-control" ng-model="vm.rowData.phone" ng-pattern="/^\d+$/"></input>
<span ng-show="editForm.phone.$error.pattern" class="error">{{'customers.inValidPhone' | translate}}</span>
</div>
</div>
<button type="button" class="btn cancel-button" title="{{'prospects.cancelEdit'|translate}}" ng-click="vm.cancelEdit()">
{{'prospects.cancelEdit'|translate}}</button>
</form>

passing data from controller to placeholders of the view in angularjs

I'm getting set of data by calling a GET method in angularjs.
controller
$scope.edit = function (id) {
var edit_url = 'http://localhost/AwtCW2012002/api/restApiController/editQuestion.json?question_id=' + id;
$http.get(edit_url)
.success(function (data) {
console.log(data);
})
.error(function () {
})
};
Data from the GET method is like follows
How can I pass the data into respective fields in my view (into placeholders, as this view is used to edit existing data)
view
<div class="container" ng-controller="questionEditCtrl">
<form class="form-horizontal" role="form" name='quizAdd' ng-submit="submit(data)">
<div class="form-group">
<label class="control-label col-sm-2" for="question">Question:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="question" ng-model="data.question" placeholder="Enter Question">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="answer1">Answer 1:</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="answer1" ng-model="data.ans1" id="answer1" placeholder="Enter Answer 1">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="answer2">Answer 2:</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="answer2" ng-model="data.ans2" id="answer2" placeholder="Enter Answer 2">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="answer3">Answer 3:</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="answer3" ng-model="data.ans3" id="answer4" placeholder="Enter Answer 3">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="answer4">Answer 4:</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="answer4" id="answer4" ng-model="data.ans4" placeholder="Enter Answer 4">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="answer5">Answer 5:</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="answer5" id="answer5" ng-model="data.ans5" placeholder="Enter Answer 5">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="sel1">Select Correct Answer:</label>
<div class="col-sm-10">
<select class="form-control" ng-model="data.correct_ans" id="sel1">
<option>{{data.ans1}}</option>
<option>{{data.ans2}}</option>
<option>{{data.ans3}}</option>
<option>{{data.ans4}}</option>
<option>{{data.ans5}}</option>
</select>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</div>
</form>
</div>
You are getting the response in array. Use ng-repeat to render you fields. What you perform ng-repeat, you can add placeholder like,
placeholder="Write Answer {{$index}}"
Firstly, populate a $scope variable with the data from the api for it to be available for binding in the template:
$http.get(edit_url)
.success(function (data) {
$scope.data = data; //populate a scope variable
})
.error(function () {
});
Then, you can use one time expressions :: for your placeholders as follows:
placeholder="{{::data.ans1}}"
This will ensure only the default value of data.ans1 which was fetched from the api will be used as the placeholder. All subsequent changes to data.ans1 will change the value, but the placeholder will remain the same.

Loading a modal form with data in Angular

Trying to learn Angular ... and
I'm missing something really obvious here, I'm sure of it. However, all of the examples, fiddles or plunkers I'm finding deal with validating create forms, not update forms.
My application is creating a modal form to add/edit client data. If a valid clientId is passed in, the form is opened as an edit and the data is loaded into the form.
When I load the values, I'm only assigning the value to the modal's property. Since its only a value, it doesn't have an $invalid function or any of the other nice form methods. Without that, the validation doesn't work. What's the proper way to load data into a form in Angular so that it can be validated? Thanks!
angular.module('app').controller("clientController",
function ($scope, $modalInstance, dataService, clientId) {
$scope.clientForm = {}
$scope.clientForm.clientId = clientId;
$modalInstance.opened.then(function () {
if (clientId > 0) {
dataService.getClient(clientId).then(function (clientData) {
$scope.clientForm.name = clientData.Name;
$scope.clientForm.address1 = clientData.Address1;
$scope.clientForm.address2 = clientData.Address2;
$scope.clientForm.city = clientData.City;
$scope.clientForm.stateId = clientData.StateId;
$scope.clientForm.zip = clientData.Zip;
$scope.clientForm.email = clientData.Email;
});
};
});
$scope.ok = function () {
$scope.clientForm.$submitted = true;
if ($scope.clientForm.$valid) {
$modalInstance.close($scope.clientForm);
}
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
}
)
And for the form:
<script type="text/ng-template" id="ClientEdit.html">
<div class="modal-header">
<h3 class="modal-title"><span>Client</span></h3>
</div>
<div class="modal-body col-md-12">
<form name="clientForm" novalidate>
<div class="form-group col-md-12">
<label class="col-md-2 control-label text-right" for="txtclientName">Name: </label>
<div class="col-md-6"><input class="form-control input-sm" id="txtclientName" type="text" ng-model="clientForm.name" required /></div>
<p ng-show="clientForm.name.$invalid">Name is required.</p>
</div>
<div class="form-group col-md-12">
<label class="col-md-2 control-label text-right" for="txtAddressLine1">Address 1: </label>
<div class="col-md-6"><input class="form-control input-sm" id="txtAddressLine1" type="text" ng-model="clientForm.address1" /></div>
</div>
<div class="form-group col-md-12">
<label class="col-md-2 control-label text-right" for="txtAddressLine2">Address 2: </label>
<div class="col-md-6"><input class="form-control input-sm" id="txtAddressLine2" type="text" ng-model="clientForm.address2" /></div>.
</div>
<div class="form-group col-md-12">
<label class="col-md-2 control-label text-right" for="txtCity">City: </label>
<div class="col-md-2"><input class="form-control input-sm" id="txtCity" type="text" ng-model="clientForm.city" /></div>
<label class="col-md-1 control-label text-right" for="txtZip">Zip: </label>
<div class="col-md-2"><input class="form-control input-sm" id="txtZip" type="text" ng-model="clientForm.zip" /></div>
</div>
<div class="form-group col-md-12">
<label class="col-md-2 control-label text-right" for="txtEmail">Email: </label>
<div class="col-md-6"><input class="form-control input-sm" id="txtEmail" type="email" ng-model="clientForm.email" /></div>
</div>
</form>
</div>
<div class="modal-footer">
<button class="btn btn-primary" ng-click="ok()" ng-disabled="clientForm.$invalid">Save</button>
<button class="btn btn-warning" ng-click="cancel()">Cancel</button>
</div>
</script>

Send input data from a bootstrap form into a script

I'm new to angularJS and bootstrap, I already made a bootstrap form to input details but i having trouble getting the data from the form into a Javascript file, so that i can use the data.
<div id="collapseOne" class="panel-collapse collapse">
<div class="panel-body">
<form class="form-horizontal">
<fieldset>
<!-- Text input-->
<div class="control-group">
<label class="control-label" for="db_short_Name">Database Short Name</label>
<div class="controls">
<input size="40" id="db_short_Name" name="db_short_Name" placeholder="Enter database short name" class="input-xlarge" type="text">
</div>
</div>
<div class="control-group">
<label class="control-label" for="db_display_Name">Database Display Name</label>
<div class="controls">
<input size="40" id="db_display_Name" name="db_display_Name" placeholder="Enter database display name" class="input-xlarge" type="text">
</div>
</div>
<div class="control-group">
<label class="control-label" for="db_max_Size">Database Max Size</label>
<div class="controls">
<input size="80" id="db_max_Size" name="db_max_Size" placeholder="Enter maxiumun size" class="input-xlarge" type="number">
</div>
</div>
</br>
<!-- Button -->
<div class="control-group">
<div class="controls">
<button id="button1_Create" name="button1_Create" class="btn btn-primary">Create</button>
<button id="button2_View" name="button2_View" class="btn btn-default">View</button>
</div>
</div>
</fieldset>
</form>
</div>
More info: Using this form a user will be able to create a browser database using Websql. the main components of creating a DB is:
var shortName= 'ABC';
var version = '0.1';
var displayName = 'DATABASE'
var maxSize = 65536;
db = openDatabase(shortName, version, displayName, maxSize);
For now i just want to display what the user inputs using alert().
Please see here : http://jsfiddle.net/BL6QP/
View:
<div id="collapseOne" class="panel-collapse collapse" ng-app="app">
<div class="panel-body" ng-controller="myCtrl">
<form class="form-horizontal">
<fieldset>
<!-- Text input-->
<div class="control-group">
<label class="control-label" for="db_short_Name">Database Short Name</label>
<div class="controls">
<input size="40" id="db_short_Name" name="db_short_Name" placeholder="Enter database short name" class="input-xlarge" type="text" ng-model="mymodel.shortname">
</div>
</div>
<div class="control-group">
<label class="control-label" for="db_display_Name">Database Display Name</label>
<div class="controls">
<input size="40" id="db_display_Name" name="db_display_Name" placeholder="Enter database display name" class="input-xlarge" type="text" ng-model="mymodel.displayname">
</div>
</div>
<div class="control-group">
<label class="control-label" for="db_max_Size">Database Max Size</label>
<div class="controls">
<input size="80" id="db_max_Size" name="db_max_Size" placeholder="Enter maxiumun size" class="input-xlarge" type="number" ng-model="mymodel.maxsize">
</div>
</div>
</br>
<!-- Button -->
<div class="control-group">
<div class="controls">
<button id="button1_Create" name="button1_Create" class="btn btn-primary" ng-click="create()">Create</button>
<button id="button2_View" name="button2_View" class="btn btn-default">View</button>
</div>
</div>
</fieldset>
</form>
<pre>{{mymodel | json}}</pre>
</div>
</div>
JS:
var app = angular.module('app',[]);
app.controller('myCtrl', function($scope){
$scope.mymodel = {};
$scope.create = function(){
alert($scope.mymodel);
}
});

Resources