Invalid attributes sent to model. Validation issues - javascript

I'm using the validation service from https://gist.github.com/basco-johnkevin/8436644 and currently having some issues upon submission of my data. It seems like maybe the validation service doesn't like NaN values or I'm possibly missing something. Any ideas?
My form:
<div class="container">
<form action="/standardplacement/create" method="POST" role="form">
<div class="row-fluid">
<h2 class="form-signin-heading">Create a <em>Standard Media</em> placement</h2>
<% if (req.session.flash && req.session.flash.error) { %>
<% var errors = req.flash('error') %>
<div class="alert alert-danger">
<button type="button" class="close" aria-hidden="true" data-dismiss="alert">×</button>
<ul>
<% Object.keys(errors).forEach(function(error) { %>
<% Object.keys(errors[error]).forEach(function(error_message) { %>
<% Object.keys(errors[error][error_message][0]).forEach(function(error_message_res) { %>
<li><%- errors[error][error_message][0][error_message_res] %></li>
<% }); %>
<% }); %>
<% }); %>
</ul>
</div>
<% var t_results = req.flash('temp_results'); %>
<% if(t_results[0]){ %>
<%
t_results = t_results[0];
sails.log.info("Results Restored");
%>
<% } %>
<% } %>
</div>
<div class="row-fluid">
<div class="form-group">
<label for="pName">Placement Name</label>
<input type="text" name="name" id="pName" class="form-control" required="required" title="Name" placeholder="12/27 Homepage 300x250 Banner" />
</div>
</div>
<div class="row-fluid">
<blockquote>
<p class="lead">General Specifications</p>
</blockquote>
</div>
<div class="row-fluid">
<div class="form-group row">
<div class="col-xs-4">
<label for="pWidth">Width</label>
<div class="input-group">
<input type="integer" name="width" id="pWidth" class="form-control" title="Width (in PX)" placeholder="300" />
<div class="input-group-addon">px</div>
</div>
</div>
<div class="col-xs-4">
<label for="pHeight">Height</label>
<div class="input-group">
<input type="integer" name="height" id="pHeight" class="form-control" title="Height (in PX)" placeholder="250" />
<div class="input-group-addon">px</div>
</div>
</div>
</div>
</div>
<br/>
<div class="row-fluid">
<div class="form-group">
<button type="submit" class="btn btn-lg btn-primary" type="submit">Create Placement</button>
<input type="hidden" name="_csrf" value="<%= _csrf %>" />
</div>
</div>
</form>
</div>
My controller:
create: function(req, res){
StandardPlacement.create( req.params.all() ).exec( function (error, placement) {
sails.log( req.params.all() );
if(error) {
sails.log(error);
sails.log(error.ValidationError);
if(error.ValidationError) {
error_object = ValidationService.transformValidation(StandardPlacement, error.Validation);
sails.log.warn(error_object);
res.send({result: false, errors: error_object});
}
}
// After successfully creating the placement
// redirect the user to the show action
res.redirect('/standardplacement/show/' + placement.id);
});
},
My model:
module.exports = {
attributes: {
name: {
type: 'string',
minLength: 2,
required: true
},
width: {
type: 'integer',
required: true
},
height: {
type: 'integer',
required: true
}
},
validation_messages: {
name: {
required: 'You must supply a valid name for the placement. If you do not have a specific name, make up one.',
minLength: 'The name must be more than one character long.'
},
width: {
required: 'You must supply a width value in pixels.'
},
height: {
required: 'You must supply a height value in pixels.'
},
}
};
The service in api/services/ValidationService.js:
/**
* Takes a Sails Model object (e.g. User) and a ValidationError object and translates it into a friendly
* object for sending via JSON to client-side frameworks.
*
* To use add a new object on your model describing what validation errors should be translated:
*
* module.exports = {
* attributes: {
* name: {
* type: 'string',
* required: true
* }
* },
*
* validation_messages: {
* name: {
* required: 'you have to specify a name or else'
* }
* }
* };
*
* Then in your controller you could write something like this:
*
* var validator = require('sails-validator-tool');
*
* Mymodel.create(options).done(function(error, mymodel) {
* if(error) {
* if(error.ValidationError) {
* error_object = validator(Mymodel, error.Validation);
* res.send({result: false, errors: error_object});
* }
* }
* });
*
* #param model {Object} An instance of a Sails.JS model object.
* #param validationErrors {Object} A standard Sails.JS validation object.
*
* #returns {Object} An object with friendly validation error conversions.
*/
exports.transformValidation = function(model, validationError) {
sails.log.info("Validating Submission");
var validation_response = {};
var messages = model.validation_messages;
validation_fields = Object.keys(messages);
validation_fields.forEach(function(validation_field) {
if(validationError[validation_field]) {
var processField = validationError[validation_field];
processField.forEach(function(rule) {
if(messages[validation_field][rule.rule]) {
if(!(validation_response[validation_field] instanceof Array)) {
validation_response[validation_field] = new Array();
}
var newMessage = {};
newMessage[rule.rule] = messages[validation_field][rule.rule];
validation_response[validation_field].push(newMessage);
}
});
}
});
sails.log.info("Validation Complete!");
return validation_response;
};
The error:
error: Sending 500 ("Server Error") response:
TypeError: Cannot read property 'width' of undefined
at /Users/me/Sites/specs/api/services/ValidationService.js:49:22
at Array.forEach (native)
at Object.exports.transformValidation (/Users/me/Sites/specs/api/services/ValidationService.js:47:21)
at /Users/me/Sites/specs/api/controllers/StandardPlacementController.js:34:39
at bound (/usr/local/lib/node_modules/sails/node_modules/lodash/dist/lodash.js:957:21)
at applyInOriginalCtx (/usr/local/lib/node_modules/sails/node_modules/waterline/lib/waterline/utils/normalize.js:416:80)
at wrappedCallback (/usr/local/lib/node_modules/sails/node_modules/waterline/lib/waterline/utils/normalize.js:326:16)
at _normalizeCallback.callback.error (/usr/local/lib/node_modules/sails/node_modules/waterline/node_modules/node-switchback/lib/normalize.js:42:31)
at _switch (/usr/local/lib/node_modules/sails/node_modules/waterline/node_modules/node-switchback/lib/factory.js:33:28)
at /usr/local/lib/node_modules/sails/node_modules/waterline/lib/waterline/query/dql/create.js:51:22 [TypeError: Cannot read property 'width' of undefined]

After talking to some folks in #sailsjs, I figured it out. Ended up removing the create method from the controller. Updated api/responses/badRequest.js with the following.
In badRequest.js:
var referringView = req.header('Referer').replace(req.protocol + "://" + req.host + ":" + req.port + '/', '');
var errors = data.invalidAttributes;
var error_object = {};
if(errors) {
error_object = ValidationService.transformValidation(StandardPlacement, errors);
return res.view(referringView, {result: false, errors: error_object});
}
In View (read/show the errors):
<% if (res.locals && res.locals.errors) { %>
<% var errors = res.locals.errors; %>
<div class="alert alert-danger">
<button type="button" class="close" aria-hidden="true" data-dismiss="alert">×</button>
<ul>
<% Object.keys(errors).forEach(function(error) { %>
<% Object.keys(errors[error]).forEach(function(error_message) { %>
<% sails.log(errors[error][error_message]); %>
<% Object.keys(errors[error][error_message]).forEach(function(error_message_res) { %>
<li><%- errors[error][error_message][error_message_res] %></li>
<% }); %>
<% }); %>
<% }); %>
</ul>
</div>
<% var t_results = req.flash('temp_results'); %>
<% if(t_results[0]){ %>
<%
t_results = t_results[0];
sails.log.info("Results Restored");
%>
<% } %>
<% } %>

Simply add below line of code to see the response of your error
SomeModel.create({}).then(function(){
}).catch(function(err){
console.log(err.ValidationError);
})

Related

.save() function not working to update database

I have this working for a different Schema (I can show this code if needed) but when I tried to recreate it for another, it won't update my DB. It's connected to a MongoDB database and this functionality works with another Schema but this one does not
I've hit a dead end and have no idea a this point... Any help would be appreciated!!
Here is the POST controller
console.log("post");
const userId = req.body.userId;
const updatedName = req.body.name;
const updatedPassword = req.body.password;
const updatedEmail = req.body.email;
const updatedSkype = req.body.skype;
const updatedDepartment = req.body.department;
const updatedJobtitle = req.body.jobtitle;
const updatedLinemanager = req.body.linemanager;
const updatedNinumber = req.body.ninumber;
// const updatedJoinDate = req.body.joindate;
// console.log(req.body);
User.findById(userId)
.then((user) => {
isadmin = user.isadmin;
name = updatedName;
password = updatedPassword;
email = updatedEmail;
skype = updatedSkype;
department = updatedDepartment;
jobtitle = updatedJobtitle;
linemanager = updatedLinemanager;
ninumber = updatedNinumber;
joindate = user.joindate;
return user.save();
})
.then((result) => {
console.log("User EDITED!");
res.redirect("/staffdir");
})
.catch((err) => console.log(err));
};
The User model
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const userSchema = new Schema({
isadmin: {
type: Boolean,
required: true,
},
name: {
type: String,
required: true,
},
password: {
type: String,
required: true,
},
email: {
type: String,
required: true,
},
skype: {
type: String,
required: true,
},
department: {
type: String,
required: true,
},
jobtitle: {
type: String,
required: true,
},
linemanager: {
type: String,
required: true,
},
ninumber: {
type: String,
required: true,
},
joindate: {
type: Date,
required: true,
},
});
module.exports = mongoose.model("User", userSchema);
The Routes
router.get("/add-user", adminController.getAddUser);
router.get("/edit-user/:userId", adminController.getEditUser);
router.get("/edit-user-list", adminController.getEditUserList);
//POST USER
router.post("/add-user", adminController.postAddUser);
router.post("/edit-user/edit-user", adminController.postEditUser);
router.post("/edit-user", adminController.postEditUser);
router.post("/destroy-user", adminController.postDeleteUser);
And the HTML/EJS file
<%- include('../includes/head.ejs') %>
<link rel="stylesheet" href="/css/admin.css" />
<link rel="stylesheet" href="/css/add-user.css" />
<body>
<img src="pozzani.png" alt="pozzani logo" class="pozzanilogo" />
<div class="mainbackground">
<div class="leftcolumn">
<%- include('../includes/signout.ejs') %>
<%- include('../includes/nav.ejs') %>
<%- include('../includes/useful.ejs') %>
</div>
<div class="admin-column">
<h2 class="importanttitle">EDIT USER</h2>
<div class="update-container">
<h3 class="admin-title">Welcome to the USER edit tool</h3>
<p class="admin-content">Please edit forms below to make change. <b>ALL EDITS ARE FINAL!</b></p>
<form class="user-form" action="edit-user" method="POST">
<div class="form-section">
<label for="isadmin">Is Admin?</label>
<select id="isadmin" name="isadmin">
<% if (!user.isadmin) { %>
<option value="false" selected>False</option>
<option value="false">False</option>
<option value="false">False</option>
<option value="false">False</option>
<option value="false">False</option>
<option value="false">False</option>
<option value="true">True - ARE YOU SURE? USER WILL BE ABLE TO EDIT USERS AND UPDATES</option>
<% } else { %>
<option value="true" selected>True - ARE YOU SURE? USER WILL BE ABLE TO EDIT USERS AND UPDATES</option>
<% } %>
</select>
</div>
<div class="form-section">
<label for="name">Name</label>
<input type="text" name="name" id="name" value="<%= user.name %>" >
</div>
<div class="form-section">
<label for="password">Password</label>
<input type="text" name="password" id="password" value="<%= user.password %>">
</div>
<div class="form-section">
<label for="email">Email</label>
<input type="email" name="email" id="email" value="<%= user.email %>">
</div>
<div class="form-section">
<label for="skype">Skype</label>
<input type="text" name="skype" id="skype" value="<%= user.skype %>">
</div>
<div class="form-section">
<label for="department">Department</label>
<input type="text" name="department" id="department" value="<%= user.department %>">
</div>
<div class="form-section">
<label for="jobtitle">Job Title</label>
<input type="text" name="jobtitle" id="jobtitle" value="<%= user.jobtitle %>">
</div>
<div class="form-section">
<label for="linemanager">Line Manager</label>
<input type="text" name="linemanager" id="linemanager" value="<%= user.linemanager %>">
</div>
<div class="form-section">
<label for="ninumber">National Insurance Number</label>
<input type="text" name="ninumber" id="ninumber" value="<%= user.ninumber %>">
</div>
<!-- <div class="form-section">
<label for="joindate">Join Date</label>
<input type="date" name="joindate" id="joindate" value="<%= user.joindate %>">
</div> -->
<input type="hidden" value="<%= user._id %>" name="userId">
<button class="admin-btn" type="submit"><% userId = user._id %>Edit User</button>
</form>
</div>
</div>
</div>
</body>
</html>
Please use findByIdAndUpdate() function instead of findById() and save()
for example;
User.findByIdAndUpdate(userId, {
isadmin: user.isadmin,
name: updatedName,
...
})
.then((result) => {
console.log("User EDITED!");
res.redirect("/staffdir");
})
.catch((err) => console.log(err));

Express-validator throwing error with valid fields

I'm relatively new to node and express, and have come across a problem I can't seem to solve.
So I came across with the problem trying to validate a create product form, that when I introduce correct values into the fields express-validator throws error.
This is my routes code:
router.post('/create', [
check('name').isLength({ min: 5 }).withMessage("Invalid Value"),
check('description').isLength({ min: 20 }).withMessage("Invalid Value")
] , upload.any() , productosController.guardarCreado);
This is my productosController code:
guardarCreado: (req, res, next) => {
let errors = validationResult(req);
if(errors.isEmpty()){
db.Product.create({
name: req.body.nombre,
description: req.body.descripcion,
size: req.body.talle,
price: req.body.precio,
category_id: 2,
img_url: req.files[0].filename
})
res.redirect('/productos');
}else{
db.Category.findAll()
.then(function(categorias){
return res.render('crearProductos', { categorias: categorias, errors: errors.errors });
})
}
}
And my form code is from Bootstrap and the names of the form fields are the same as the names on the 'check' from my routes code:
<div class="col-md-3 mb-3">
<label for="validationDefault03">Nombre del Producto</label>
<input name="name" id="nombre" type="text" class="form-control" placeholder="Ej: Remera River Plate" >
</div>
<div class="col-12">
<label for="description" class="form-label">Descipción:</label><br>
<textarea name="description" id="description" class="form-input"></textarea>
</div>
Error display on the the form via EJS:
<% if (typeof errors != 'undefined') { %>
<p style= "color: red">ERROR</p>
</div>
<ul>
<% for(let i = 0; i < errors.length; i++) { %>
<li>
<%= errors[i].msg %>
</li>
<% } %>
</ul>
<% } %>

Node js jquery ajax

I have the following the code on aap.js with a route to '/bio_post'. I'm trying to post some text based on my website using jquery ajax. The problem I'm having is that jquery picks up the objects that come from '/bio_post' as undefined. I was wondering if you guys can point me in the right direction. Thank you for your time and effort.
app.post('/bio_post', function (req, res) {
// Get user input value
let update_bio = req.body.user_bio;
// Check if the input isn't empty
if(update_bio !== "") {
// Connect to mysql database
mysql_connection.query("UPDATE users SET user_bio = ? WHERE id = ?", [update_bio, session_id], function (err, rows) {
if (err) {
let obj_error = {err: err};
res.send(obj_error.err);
} else {
// Check if the post was successfully inserted into the database
if (rows.changedRows === 1) {
let id = {id: session_id};
res.redirect("/profile/" + JSON.stringify(id.id));
console.log("bio post id is: " + JSON.stringify(id.id));
/*let msg_success = {id: session_id, success_msg: 'Bio successfully inserted!'};
res.send(msg_success);*/
} else {
let id = {id: session_id};
let msg_error = {msg_err: 'No changes were made to your bio.'};
res.send(JSON.stringify(msg_error.msg_err));
console.log("bio post id is: " + JSON.stringify(id.id));
}
}
});
}else{
//res.render("settings", {u_id: session_id, logged_in_user: session_username, bio: '', bio_msg: "Bio field cannot be empty."});
res.send("Bio field is empty");
}
});
Below is the code for jquery.
/**Set up URL route variable**/
let url = '/bio_post';
/**Set up Ajax callback**/
$.ajax({
url: url,
type: 'POST',
data: {user_bio: user_bio.val()},
success: function (data) {
if(data.msg_err){
success_bio_handler.hide();
error_bio_handler.fadeIn().text(data.msg_err).delay(5000).fadeOut();
} else {
error_bio_handler.hide();
//success_bio_handler.fadeIn().text(data.success_msg).delay(5000).fadeOut();
//window.location.href = '/profile/' + data.id;
console.log(data.id); /***COMES OUT AS UNDEFINED****/
}
}
});
Then lastly, is the html file.
<!--ADD OR UPDATE BIO-->
<div id="add_update_bio_title"><strong>Add or Update Bio</strong></div>
<div id="add_update_bio_panel">
<form id="frm_add_update_bio" action="/bio_post" method="post"><br />
<div class="py-5 w-100">
<div class="row">
<div class="col-md-4"></div>
<div class="col-md-4">
<p id="error_bio_handler" class="alert-danger collapse">Error</p><!--jQuery error handler-->
<p id="success_bio_handler" class="collapse" style="background-color: #00AA88; color: white;"></p><!--jQuery success handler-->
<form class="">
<div class="form-group">
<!--Check if user has entered a bio-->
<div class="alert-danger"><%= typeof bio_msg !== 'undefined' ? bio_msg : '' %></div><br />
<% if (bio){%>
<textarea class="form-control" rows="5" id="user_bio" name="user_bio" placeholder="Write a little something about yourself"><%- bio%></textarea>
<%} else{%>
<textarea class="form-control" rows="5" id="user_bio" name="user_bio" placeholder="Write a little something about yourself"></textarea>
<%}%>
</div>
<div class="form-group"></div>
<div class="form-group"></div>
<button id="btnSubmitBio" type="button" class="btn btn-primary">Add or Update Bio</button>
</form>
</div>
<div class="col-md-4"></div>
</div>
</div>
</form>
</div>
<!--END ADD OR UPDATE BIO-->

Looking For Advice On Paginating AJAX Results

I currently am working on a feature for a web app that allows users to dynamically search and filter a list of cards. I've accomplished the filtering and search, but as the search results grow, I end up with either an incredibly slow page, or a very large number of results to sift through. I thought pagination might be a solution given the maximum number of results are in the thousands, and eventually I'd like to have very broad filter buttons, as well as text-based search.
A screenshot of it in action:
The code is as follows:
deckbuilder.js
document.addEventListener("turbolinks:load", function() {
$(document).on("click", ".deck-adjust-button", adjustDeck)
$(document).on("click", "#decklist-submit", submitDecklist)
$(document).on("input", "#list-search", updateMiniList)
})
function adjustDeck(e) {
card_name = $(this).parents('tr').data("name")
card_name_sanitized = card_name.replace(/\s+/g, '-').replace(/,/g, '').replace(/'/g, '').toLowerCase();
num_cards = $(this).parents('tr').find("#num-cards").val()
deck = $(this).text().toLowerCase() + "-deck"
console.log(card_name + "|" + num_cards + "|" + deck)
deck_div = $("#" + deck)
deck_div.find("#" + card_name_sanitized).remove()
if (parseInt(num_cards) > 0) {
deck_div.append("<div id=" + card_name_sanitized + ">" + num_cards + "x " + card_name + "</div>")
}
}
function submitDecklist(e) {
e.preventDefault()
deck_divs = $(".deck")
decklist_decks = []
decklist_name = $('#name').val()
decklist_description = $("#description").val()
deck_divs.each(function(div) {
deck = $(deck_divs[div])
deck_name_raw = deck.find('div').attr("id")
deck_name = deck_name_raw.split("-")[0]
deck_name = deck_name.charAt(0).toUpperCase() + deck_name.slice(1)
deck_div = deck.find('#' + deck_name_raw)
cards_array = []
deck_div.children().each(function() {
card_text = $(this).text().trim()
card_name = card_text.substr(card_text.indexOf(' ')+1)
card_num = parseInt(card_text.substr(0,card_text.indexOf(' ')).replace(/x/g, ''))
cards_array.push({
name: card_name,
num: card_num,
})
})
decklist_decks.push({
name: deck_name,
cards: cards_array
})
})
decklist = {
decklist: {
name: decklist_name,
description: decklist_description,
decks: decklist_decks
}
}
$.ajax({
method: "POST",
url: "/decklists",
data: decklist
})
.done(function( msg ) {
window.location.replace("/decklists/" + msg.id);
})
.fail(function( msg) {
window.location.replace("/decklists/new");
})
}
function updateMiniList(e) {
inputValue = $(this).val().toLowerCase()
listEntries = $(this).parents().siblings('#mini-card-list').find('tr')
listEntries.each(function() {
entry = $(this)
entryName = $(this).data("name").toLowerCase()
if (!entryName.includes(inputValue)) {
entry.hide()
} else {
entry.show()
}
})
if(inputValue.length > 2) {
data = { "name": inputValue }
ApiCall("POST", "/cards/search", data, appendCards)
}
}
function ApiCall(method, target, data, callback) {
$.ajax({
method: method,
url: target,
data: data,
success: callback
})
}
function appendCards(cards) {
cards.forEach(function(card) {
name = card.name
newCardDiv = $('<tr data-name="' + name + '">\
<td>\
<select class="form-control" id="num-cards">\
<option value=0>0</option>\
<option value=1>1</option>\
<option value=2>2</option>\
<option value=3>3</option>\
<option value=4>4</option>\
</select>\
</td>\n\
<td>' + name + '</td>\n\
<td>\
<div class="btn-group btn-group-sm" role="group">\
<button type="button" class="btn btn-secondary deck-adjust-button">Main</button>\
<button type="button" class="btn btn-secondary deck-adjust-button">Stone</button>\
<button type="button" class="btn btn-secondary deck-adjust-button">Side</button>\
<button type="button" class="btn btn-secondary deck-adjust-button">Ruler</button>\
</div>\
</td>\
</tr>')
$('#mini-card-list').find('table').append(newCardDiv)
});
}
new.html.erb (Page interacting with JS)
<div class="container">
<div class="row">
<div class="col">
<h2>Create a New Decklist</h2>
</div>
</div>
<div class="row">
<div class="col-md-5">
<hr>
<h4>Decks</h4>
<hr>
<%= render "decklists/deck_div", deck_name: "Ruler" %>
<%= render "decklists/deck_div", deck_name: "Main" %>
<%= render "decklists/deck_div", deck_name: "Stone" %>
<%= render "decklists/deck_div", deck_name: "Side" %>
<%= render "decklists/form", decklist: #decklist %>
</div>
<div class="col-md-7">
<%= render "cards/mini_list", cards: #cards %>
</div>
</div>
</div>
deck_div partial
<div class="row">
<div class="col deck">
<hr>
<h4><%= deck_name %></h4>
<hr>
<div id="<%= deck_name.downcase + "-deck" %>">
</div>
</div>
</div>
Mini-List Partial
<div class="col">
<hr>
<h4>Cards</h4>
<hr>
<div>
<input type="text" placeholder="Search" class="form-control" id="list-search">
</div>
<div id="mini-card-list" style="overflow:scroll; height:400px;">
<table class="table">
</table>
</div>
</div>

Backbone doesn't forget previous model

I'm trying to create a page where I can see list of my items, and edit them when clicked (on a separate page).
But when I browse trough different items (models), and then try to edit one item, every other item that I have loaded edits too.
My view:
App.Views.Items.Types.Type = Backbone.View.extend({
template: '#template_itemtypeview',
el: '#content',
initialize: function() {
$('.manage_items_header').show();
this.render();
},
render: function() {
var self = this;
var itemtypes = new App.Collections.ItemTypes();
itemtypes.fetch({
success: function() {
var template = _.template($(self.template).html());
$(self.el).html(template({
model: self.model.toJSON(),
itemtypes: itemtypes.models
}));
}
});
return this;
},
events: {
"change": "change",
"click .save": "save",
"click .delete": "delete",
},
change: function(event) {
// Remove any existing alert message
App.Utils.hideAlert();
// Apply the change to the model
var target = event.target;
var change = {};
if (target.type == 'checkbox') {
change[target.name] = target.checked;
} else {
change[target.name] = target.value;
}
this.model.set(change);
},
save: function() {
var self = this;
this.model.save(null, {
success: function(model) {
self.render();
App.app.navigate('items/types/' + model.id, false);
App.Utils.showAlert('Success!', 'Item type saved successfully', 'alert-success');
},
error: function() {
App.Utils.showAlert('Error', 'An error occurred while trying to delete this item type', 'alert-error');
}
});
},
delete: function() {
var self = this;
this.model.destroy({
success: function() {
App.app.navigate('items/types/new', true);
alert('Item type deleted successfully');
//window.history.back();
}
});
return false;
} });
Relavent part of route:
itemTypeAdd: function(){
App.Views.HeaderView.selectMenuItem('manage_items');
new App.Views.Items.Types.Type({
model: new App.Models.ItemType()
});
},
itemTypeShow: function(id){
App.Views.HeaderView.selectMenuItem('manage_items');
var itemtype = new App.Models.ItemType({id: id});
itemtype.fetch({success: function(){
new App.Views.Items.Types.Type({
model: itemtype
});
}});
},
HTML:
<form class="form-horizontal span5">
<fieldset>
<legend>Item Type Details</legend>
<br/>
<div class="control-group">
<label for="collectionID" class="control-label">ID:</label>
<div class="controls">
<input id="collectionID" name="id" type="text" value="<%= model.id === null ? '' : model.id %>" class="span3"
disabled/>
</div>
</div>
<div class="control-group">
<label for="name" class="control-label">Name:</label>
<div class="controls">
<input type="text" id="name" name="name" value="<%= model.name %>"/>
<span class="help-inline"></span>
</div>
</div>
<div class="control-group">
<label for="name" class="control-label">Has places?:</label>
<div class="controls">
<input type="checkbox" name="has_place"<% if(model.has_place) { %> checked="checked"<% } %>>
<span class="help-inline"></span>
</div>
</div>
</fieldset>
<div class="form-actions">
Save
Delete
</div>
</form>
<div class="span2">
<legend>Item Types + New</legend>
<ul id="itemtypes_list">
<%
_.each(itemtypes,function(item,key,list){
%>
<li><%= item.attributes.name %></li>
<%
});
%>
</ul>
</div>

Categories