How to fill in checkbox in Backbone-form - javascript

im trying to fill a array checkboxes with other which came from a json array. my code is simple,
var cmyBox = Backbone.Collection.extend({
model: mmyBox,
url: 'http://localhost/wordpress/oferta/prueba1/?json=get_taxonomy&taxonomy=habilidad',
parse: function (resp) {
var skillsname = new Array();
var i = 0;
resp.terms.forEach(function(item) {
skillsname[i] = item.slug
i++
});
console.log(skillsname);
return skillsname;
}
});
var Form = Backbone.Model.extend({
schema: {
id: {},
nombre: {},
apellidos: {},
email: { type: 'Text', dataType: 'email', validators: ['required', validateEmail] },
telefono: { type: 'Text', dataType: 'tel', validators: ['required'] },
nacionalidad: { type: 'Select', options: ['EspaƱola', 'Extranjera'] },
link1: { type: 'Text', title: 'Enlace a Reel', dataType: 'url' },
link2: { type: 'Text', title: 'Enlace a Web/Blog', dataType: 'url' },
others: { type: 'Text', dataType: 'url' },
skills1: { type: 'Checkboxes', options: cmyBoxes },
}
});
var List = new Form ({
skills1: true
});
The problem is that the array is create and has what i need but its not where it would have to be. I dont know to assign the result of collection to that field. Maybe i m doing some wrong. Whtat i want to do is this:
skills1: { type: 'Checkboxes', options: ["artist", "medico", "programador"] },
Thanks

Well i found the solution, for someone who need it. Use the toString function, its very usefull...
var mmyBox = Backbone.Model.extend({
toString: function() { return this.get('slug'); }
});
var cmyBox = Backbone.Collection.extend({
model: mmyBox,
url: 'http://localhost/wordpress/oferta/prueba1/?json=get_taxonomy&taxonomy=habilidad',
parse: function (resp) {
return _.map( resp.terms, function( item ){
return {
id: item.id,
slug: item.slug
};
});
}
});

Related

Bug with kendo grid,for closing pop up editor,you need to press cancel many times

its over a week im dealing with a strange behavior of kendo grid ,let me split my problem, for better understanding ,i have a autocomplete text box ,after I press ENTER,it binds my grid,when I press "add new record" on my kendo grid,if I press cancel,the pop up will be closed,BUTTT after second search and the add new record,if press cancel,this time needs 2times pressing,3d time needs 3times pressing.......made me crazy,badly need your help
Here is the code
$(document).keypress(function (e) {
var myResult;
var modelProducerResult;
var temp = null;
var mydata;
var mydata_deviceType;
var modelProducerDrpList;
if (e.which == 13) {
var i = 0;
debugger;
var flag = 0;
// $('#turbingrid').data().kendoGrid.refresh();
var drp = document.getElementById('autocomplete').value;
$.ajax({
dataType: "json",
type: "POST",
url: "#Url.Action("turbineDeviceDetail","AdminTool")",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ "turbine": drp, }),
success: function (result) {
//debugger;
myResult = result;
var flg = "s";
$.ajax({
dataType: "json",
type: "POST",
url: "#Url.Action("producersDevice","AdminTool")",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ "flg": flg, }),
success: function (data) {
// debugger;
mydata = data;
}
})
var flg_dvType = "s";
$.ajax({
dataType: "json",
type: "POST",
url: "#Url.Action("deviceTypeList","AdminTool")",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ "flg": flg_dvType, }),
success: function (data) {
// debugger;
mydata_deviceType = data;
}
});
dataSource = new kendo.data.DataSource({
transport: {
read: function (options) {
options.success(result); // where data is the local data array
},
create: function (options) {
if ($("input[name='DeviceIP']").val() == "" || $("input[name='TurbineId']").val() == "") {
alert("DeviceIP and TurbineID could not be blank ");
$("input[name='DeviceIP']").css("background-color", "red");
$("input[name='TurbineId']").css("background-color", "red");
}
else
$.ajax({
type: "POST",
url: "#Url.Action("AddDeviceToTurbine","AdminTool")",
data: options.data.models[0],
dataType: "json",
success: function (data) {
options.success(data);
alert("New Device Has Been Inserted");
//var e = $.Event("keypress", { which: 13 });
//$('#autocomplete').trigger(e);
},
//error: function (data) {
// options.error(data);
// alert("Insert New Data Has Been Failed");
// alert(data);
//},
error: function (xhr, status, error) {
alert(xhr.responseText);
}
});
},
update: function (options) {
if ($("input[name='DeviceIP']").val() == "" || $("input[name='TurbineId']").val() == "") {
alert("DeviceIP and TurbineID could not be blank ");
$("input[name='DeviceIP']").css("background-color", "red");
$("input[name='TurbineId']").css("background-color", "red");
}
else
$.ajax({
type: "POST",
url: "#Url.Action( "update_grid","AdminTool")",
data: options.data.models[0],
dataType: "json",
success: function (data) {
options.success(data);
alert("Update Has Been Done!");
var value = document.getElementById('autocomplete').value;
var e = $.Event("keypress", { which: 13 });
$('#autocomplete').trigger(e);
},
error: function (data) {
options.error(data);
alert("Update Failed!");
},
});
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return { models: kendo.stringify(options.models) };
}
}
},
batch: true,
pageSize: 40,
schema: {
//data: employee,
model: {
id: "DeviceIP",
fields: {
DeviceIP: { editable: true, nullable: false },
//Producer: { type:"string" },
//3 Model: { type: "string" },
DeviceType: { type: "string" },
Description: { type: "string" },
Username: { type: "string" },
Password: { type: "string" },
PublicIP: { type: "string" },
ModelProducer: { type: "string" },
Model: { type: "string" },
Producer: { type: "string" },
TurbineId: { type: "string" }
//UnitPrice: { type: "number", validation: { required: true, min: 1} },
//Discontinued: { type: "boolean" },
//UnitsInStock: { type: "number", validation: { min: 0, required: true } }
}
}
}
});
$("#turbingrid").kendoGrid({
// debugger;
dataSource: dataSource,
scrollable: false,
//toolbar: ["create"],
toolbar: [
{
name: "create",
text: "ADD NEW DEVICE"
}
],
columns: [
{ field: 'DeviceIP', title: 'DeviceIP', width: '100px', id: 'DeviceIP' },
{ field: 'Producer', title: 'Producer', width: '80px', id: 'Producer' },//editor: ProductNameDropDownEditor,
{ field: 'Model', title: 'Model', width: '220px', id: 'Model' },
// { field: 'DeviceType', title: 'DeviceType', width: '100px', id: 'DeviceType', editor: deviceTypesList },
{ field: 'Description', title: 'Description', width: '220px' },
{ field: 'Username', title: 'Username', width: '120px' },
{ field: 'Password', title: 'Password', width: '100px' },
{ field: 'PublicIP', title: 'PublicIP', width: '120px', id: 'PublicIP' },
{ field: 'TurbineId', title: 'TurbineId', width: '120px', id: 'TurbineId', hidden: true },
{ field: 'device_id', title: 'device_id', width: '120px', id: 'deviceid', hidden: true },
// { field: 'ModelProducer', title: 'Producer/Model', id: 'ModelProducer', hidden: true, editor: modelPro },
{
command: ["edit"], title: " "
}
],
editable: "popup",
});
}
})
}
});
//This Part Is For The AUTOCOMPLETE textbox
$(document).ready(function () {
var value = document.getElementById('autocomplete').value;
$.ajax({
dataType: "json",
type: "POST",
url: "#Url.Action("List_Turbine","AdminTool")",
contentType: "application/json; charset=utf-8",
//data: JSON.stringify({ "name": value ,}),
data: {},
success: function (result) {
$("#autocomplete").kendoAutoComplete({
dataSource: result,
dataTextField: "Text",
// filter: "contains"
});
}
})
});

Disable a Kendo-UI TreeView node

I have a TreeView and I want to disable some nodes when they contain in their data a state_current != null like the "disable node" button in the demo.
my code is :
<script>
$(document).ready(function() {
var treeview = $('#Tree_view').kendoTreeView({
template: "#= item.name #",
dataSource: Parcours,
dataTextField: 'name',
loadOnDemand: true,
expand: onExpandedItem
});
});
function onExpandedItem(e) {
var id_user = #Model.id;
var item = $('#Tree_view').data('kendoTreeView').dataItem(e.node)
var type = item.fields.type;
if (item.level() > 0) {
item.id_parcours = item.parentNode().id_parcours;
if (item.level() == 2) {
item.id_promo = item.parentNode().id;
}
}
else item.id_parcours = item.Id;
switch (type) {
case 'parcours':
item.children.transport.options.read = {
url: '#Url.Action("Get_Session", "Users")' + '?user_id=' + id_user,
dataType: "json",
};
break;
case 'session':
item.children.transport.options.read = {
url: '#Url.Action("Get_Matiere")' + '?user_id=' + id_user,
dataType: "json"
};
break;
default:
break;
}
}
var Matiere = {
transport: {
read: {
url: '#Url.Action("Get_Matiere")',
type: 'GET',
dataType: 'json'
}
},
schema: {
model: {
fields: {
name: 'Name',
type: 'matiere'
},
hasChildren: false,
}
}
}
var Session = {
transport: {
read: {
url: '#Url.Action("Get_Session")',
type: 'GET',
dataType: 'json'
}
},
schema: {
model: {
fields: {
id: 'IdPromo',
name: 'NamePromo',
type: 'session',
date: 'Date',
state: 'State_current',
},
hasChildren: true,
children: Matiere
}
}
}
var Parcours = {
transport: {
read: {
url: '#Url.Action("Get_Parcours", "Users")',
data: {user_id: #Model.id},
type: 'GET',
dataType: 'json'
}
},
schema: {
model: {
fields: {
id: 'Id',
name: 'Name',
type: 'parcours'
},
hasChildren: true,
children: Session
}
}
};
</script>
Do this where you want to disable the nodes
var selectedNode = treeview.select();
treeview.enable(selectedNode, false);
Here treeview should be your treeview object, you can select it as below once the treeview is created. And instead of selectedNode you can give the node which you need to disable.
var treeview = $('#Tree_view').data("kendoTreeView");
If you want to do this while the treeview renders first you can check this in kendoTreeView databound event, or in select event if you want it while selecting.

Kendo dataSource.add - "Id is not defined"

I'm trying to add some items to a Kendo DataSource to then display in the grid. However, every time I try to save I get Reference Error: Id is not defined.
At first I thought it was because I didn't include Id in my schema but I checked and it looks alright.
var viewModel = new kendo.observable({
orgDataSource: new kendo.data.DataSource({
transport: {
read: {
url: "/Organization/GetAll",
dataType: "json"
},
update: {
url: "/Host/Organization/Edit",
dataType: "json",
type: "POST",
data: {
__RequestVerificationToken: getAntiForgeryToken()
}
},
create: {
url: "/Host/Organization/Create",
dataType: "json",
type: "POST",
data: {
__RequestVerificationToken: getAntiForgeryToken()
}
},
destroy: {
url: "/Host/Organization/Delete",
dataType: "json",
type: "POST",
data: {
__RequestVerificationToken: getAntiForgeryToken()
}
}
},
schema: {
model: {
id: "Id",
fields: {
Id: { type: "number", editable: false, nullable: true },
Name: { type: "string" },
LicenseExpiration: { type: "date" },
LicenseNumber: { type: "number" },
Active: { type: "boolean" },
CreateDate: { type: "date" },
LastModDate: { type: "date" },
AvailableLicenses: { type: "string" },
State: { type: "string" }
}
},
errors: "errorMsg"
},
pageSize: 20,
error: function (e) {
toastr.options = {
"positionClass": "toast-bottom-full-width"
};
toastr.error("There was an error: " + e.errors, "Uh, Oh!");
this.cancelChanges();
},
serverPaging: false,
serverFiltering: false,
serverSorting: false
}),
reloadOrganizations: function () {
this.get("orgDataSource").read();
},
onOrgSave: function (e)
{
var uid = $('input[name="OrgRowUID"]').val();
var tr = $('tr[data-uid="' + uid + '"]'); // get the current table row (tr)
var name = $('input[name="Name"]').val();
var licenseNumber = $('input[name="LicenseNumber"]').val();
var licenseExpiration = $('input[name="LicenseExpiration"]').val();
var email = $('input[name="Email"]').val();
var state = $('input[name="State"]').val();
var logo = $('input[name="ImageUrl]').val();
var active = $('input[name="Active"]').is(":checked");
// get the data bound to the current table row
var orgGrid = $("#OrganizationGrid").data("kendoGrid");
var data = orgGrid.dataItem(tr);
if (data == null)
{
viewModel.orgDataSource.add({ Name: name, LicenseNumber: licenseNumber, LicenseExpiration: licenseExpiration, Email: email, State: state, ImageUrl: logo, Active: active })
orgGrid.saveChanges();
viewModel.orgDataSource.sync();
viewModel.reloadOrganizations();
} else {
data.set("Name", name);
data.set("LicenseNumber", licenseNumber);
data.set("LicenseExpiration", licenseExpiration);
data.set("Email", email);
data.set("State", state);
data.set("ImageUrl", logo);
data.set("Active", active);
}
$("#orgCreateModal").modal('hide');
$("#orgEditModal").modal('hide');
}
});
The error is occurring on this line:
viewModel.orgDataSource.add({ Name: name, LicenseNumber: licenseNumber, LicenseExpiration: licenseExpiration, Email: email, State: state, ImageUrl: logo, Active: active });
The error in FireBug is:
Reference Error: Id is not defined - kendo.all.min.js line 25 > function
It's throwing that error because you're not setting "Id" to anything in your datasource. I had a similar problem a while back and Telerik said you have to give 'id' a valid unique value because they use that internally to keep things straight in the datasource. In your case, you are setting your schema id to "Id", but it doesn't look like your datasource has an "Id" field. I ended up just dumping a guid in there and it fixed my problem.

How to add new tags in select2?

I am trying to get the tags from my api. Everything works fine but I cant able to add new tags. Here is what i tried:
$(function(){
var user_email = localStorage.getItem('email');
var api = localStorage.getItem("user_api_key");
var auth = "apikey" +' ' +(user_email+":"+api);
$('#s2id_id_add-places').select2({
multiple: true,
tags: [],
tokenSeparators: [",", " "],
width: "200px",
ajax: {
placeholder: "Click to enter who",
type: "GET",
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", auth);
xhr.setRequestHeader("Content-Type","application/json");
xhr.setRequestHeader("Accept","application/json");
},
url: "https://example.com/api/v3/places/",
dataType: "json",
contentType: "application/json",
processData: true,
quietMillis: 50,
data: function(term) {
return {
term: term
};
},
results: function(data) {
var results = [];
if(data.objects.length > 0) {
for (i=0; i<data.objects.length; i++) {
results.push({id: data.objects[i].id, text: data.objects[i].label, isNew: true});
}
}
return {
results: results
};
},
});
});
By using the above code, I can only get the tags but I cant able to add the new tags. how can i add the new tags?
Please help
$("#e11_2").select2({
createSearchChoice: function(term, data) {
if ($(data).filter( function() {
return this.text.localeCompare(term)===0;
}).length===0) {
return {id:term, text:term};
}
},
multiple: true,
data: [{id: 0, text: 'story'},{id: 1, text: 'bug'},{id: 2, text: 'task'}]
});
You have to create a function like createSearchChoice, that returns a object with 'id' and 'text'. In other case, if you return undefined the option not will be created.

Making sure an ExtJS checkboxfield updates its model

I have inherited an ExtJs4 project, and I've got a fairly basic question.
I have a view that has a newly added checkbox field as one of the items, like so:
{
boxLabel: 'Test Message?',
xtype: 'checkboxfield',
id: 'cbTextMessage',
checked: false,
name: 'testMessage',
inputValue: true,
uncheckedValue: false
}
When the record is active, this value changes to the appropriate checked or unchecked state. When creating a new record, the value is set to the value of the checkbox. However, when editing an existing record, the model never gets updated to any value other than the original value.
The model:
Ext.define('PushAdmin.model.Message', {
extend: 'Ext.data.Model',
idProperty: 'id',
requires: ['Proxy.ParameterProxy'],
fields: [
{ name: 'id', type: 'int' },
{ name: 'games', type: 'auto',
convert: function(data, model) {
data = ( data && !Ext.isArray(data) ) ? [data] : data;
return data;
}
},
{ name: 'msgEnglish', type: 'string' },
{ name: 'msgFrench', type: 'string' },
{ name: 'msgSpanish', type: 'string' },
{ name: 'testMessage', type: 'bool' },
{ name: 'sendAt', type: 'date' },
{ name: 'note', type: 'string'},
{ name: 'status', type: 'string' },
],
proxy: {
type: 'rest',
url: '/apnsadmin/rest/Message',
pageParam: undefined,
startParam: undefined,
limitParam: undefined,
reader: {
type: 'json',
root: 'data',
successProperty: 'success'
}
}
});
And finally this is the function that gets called when the save button is clicked.
click: function () {
var grid = this.getQueuedMessagesGrid();
var sm = grid.getSelectionModel();
var selectedRecord = sm.getCount() > 0 ? sm.getSelection()[0] : undefined;
this.getMessageForm().getForm().updateRecord();
var newRecord = this.getMessageForm().getForm().getRecord();
if (selectedRecord!=undefined) {
console.log(selectedRecord);
console.log(newRecord);
selectedRecord.save();
} else {
// New record!
console.log("Saving new record");
grid.getStore().add(newRecord);
newRecord.save();
}
this.getMessageForm().setDisabled(true);
this.getMessageForm().getForm().reset();
}
},
I am aware that things are probably not the proper ExtJS way to do things, but since this is mostly working I am trying not to have to rewrite large chunks of it. I'd just like to know what I'm doing wrong in adding this checkbox/boolean field to the form.

Categories

Resources