Mongoose nesting - json

I'm trying to convert following pseudocode:
{
app_id: 1,
help_id: 1234,
locale: 'en',
{
help_title: 'This is the title of the help entry',
help_description: 'This is the description of the help entry',
help_content: {[
{ type: 'text', title: '', description: '', style: { ... }},
{ type: 'image', title: '', description: '', url: '', style: { ... }},
{ type: 'image', title: '', description: '', url: '', style: { ... }},
{ type: 'video', title: '', description: '', url: '', style: { ... }},
{ type: 'link', title: '', description: '', url: '', style: { ... }},
{ type: 'svg', title: '', description: '', url: '', style: { ... }},
{ type: 'pdf', title: '', description: '', url: '', style: { ... }},
{ type: 'document', title: '', description: '', url: '', style: { ... }},
]}
},
locale: 'da',
{ ... }
To actual code, here is what I have so far:
var mongoose = require('mongoose')
var Schema = mongoose.Schema
var HelpitemSchema = new Schema({
app_id: { type: Number },
help_id: { type: Number },
locale: { type: String },
details: { [
{help_title: { type: String },
help_description: {type: String}}
] }
})
But I'm getting a:
[eslint]
Parsing error: Unexpected token
9 | {help_title: { type: String },
10 | help_description: {type: String}}
> 11 | ] }
| ^
12 | })
[js] ':' expected.
Should I try using sub docs or am I missing something syntax-wise?
Any help would be greatly appreciated.

You can try to create a contentSchema and then use it in HelpitemSchema :
var contentSchema = new Schema( {
type: String,
title: String,
description: String,
style: Mixed
});
var HelpitemSchema = new Schema({
app_id: { type: Number },
help_id: { type: Number },
locale: { type: String },
details: {
help_title: { type: String },
help_description: { type: String },
help_content: [contentSchema]
}
});
Take a look here for more details

Related

Sequalize association fails (BelongsTo) NodeJs Sequalize

Trying to work with sequalize association ( belongsTo and hasMany() ) but when i tries to query findAll with include the Model which was associated it fails by saying Models are not associated.
User Model
const {DATE, STRING, INTEGER} = require("sequelize");
const {USER} = require("../config/db.config");
module.exports = (sequelize, Sequelize) => {
const User = sequelize.define("Users", {
id: {
primaryKey: true, type: INTEGER, required: true, autoIncrement: true
}, phoneNumber: {
type: STRING, required: true, unique: true
}, firstname: {
type: STRING, required: true
}, middlename: {
type: STRING, required: false
}, region: {
type: STRING, required: true
}, district: {
type: STRING, required: true
}, street: {
type: STRING, required: true
}, lastname: {
type: STRING, required: true,
}, 'type': {
type: STRING, required: true,
}, email: {
type: STRING, required: true, unique: true
}, status: {
type: Sequelize.ENUM("ACTIVE", "NOT-ACTIVE", "SUSPENDED"), defaultValue: "NOT-ACTIVE",
}, createdAt: {
type: DATE,
}, updatedAt: {
type: DATE,
}
});
User.associate = function (models) {
User.hasMany(models.Students, {foreignKey: 'userId', as: 'user'});
}
return User;
};
Student Model
const {DATE, STRING, INTEGER} = require("sequelize");
module.exports = (sequelize, Sequelize) => {
const Student = sequelize.define("Students",
{
id: {
primaryKey: true, type: STRING, required: true
}, userId: {
type: INTEGER, required: true,
}, status: {
type: Sequelize.ENUM("ACTIVE", "NOT-ACTIVE", "SUSPENDED"), defaultValue: "NOT-ACTIVE",
},
level: {
type: STRING, required: true,
}, createdAt: {
type: DATE,
}, updatedAt: {
type: DATE,
}
});
Student.associate = function (models) {
Student.belongsTo(models.Users, {foreignKey: 'userId', as: 'user'})
Student.belongsToMany(models.Classes, {through: 'StudentClass',})
}
return Student;
};
I have tried to query them by using the bellow function but i got nothing
function getAllStudents() {
Student.findAll({include: [{model: User, as: 'user', required: true}]}).then(value => {
console.log(value)
return value;
}).catch(reason => {
console.error(reason)
})
}
But i get the following
Result i get

Sending data to API and retrieving them in to a grid

In my project I am using extjs in front-end. yii2 in backend. I created a form to retrieve selected data from database.
As you can see I have two date fields and a dropdown list. And I have a group of checkboxes. This is a screenshot of my database table.
I should select the data I want using checkboxes and get them from database between 'from' to 'to' dates. When I click RUN button those selected data should be loaded to the grid in the below. When I click download button, those selected data should be downloaded to a csv file. But when I click RUN button it sends same API call twice. And one API gets data correctly and other one sends and error saying 'Undefined index: from'. This is the code in my view.
recordData: {
date: null,
from: null,
to: null,
rb1: null,
rb1: null,
rb2: null,
rb3: null,
rb4: null,
time: null,
rb5: null,
rb6: null,
rb7: null,
weight: 0,
status: 1
}
},
initComponent: function () {
var me = this;
me.title = 'Reports',
me.store = Ext.create('store.Reports');
Ext.apply(me, {
items: [{
xtype: 'form',
border: false,
padding: 10,
bodyStyle: { "background-color": "#e4e4e4" },
width: '100%',
store: me.store,
defaults: {
selectOnFocus: true,
labelWidth: 125
},
items: [{
xtype: 'datefield',
fieldLabel: 'From',
padding: '10 0 0 40',
name: 'from',
format: 'Y-m-d',
labelWidth: 150,
value: me.recordData.from,
displayField: 'from',
typeAhead: true,
queryMode: 'local',
emptyText: 'Select...'
}, {
xtype: 'datefield',
fieldLabel: 'To',
padding: '20 0 0 40',
name: 'to',
format: 'Y-m-d',
labelWidth: 150,
value: me.recordData.to,
displayField: 'to',
typeAhead: true,
queryMode: 'local',
emptyText: 'Select...'
}, {
xtype: 'combobox',
fieldLabel: 'Report Type',
padding: '20 0 0 40',
name: 'type',
labelWidth: 150,
store: [
['Order Report', 'Order Report']
],
value: me.recordData.type,
displayField: 'type',
typeAhead: true,
queryMode: 'local',
emptyText: 'Select...'
}, {
width: '100%',
bodyStyle: { "background-color": "#e4e4e4" },
padding: '20 0 0 40',
bodyPadding: 10,
renderTo: Ext.getBody(),
items: [{
xtype: 'checkboxgroup',
fieldLabel: 'Customize Report',
width: 700,
labelWidth: 150,
columns: 3,
vertical: false,
items: [
{ boxLabel: 'Order ID', name: 'rb1', inputValue: '1', itemId: 'check1' },
{ boxLabel: 'Connection Number', name: 'rb2', inputValue: '2', itemId: 'check2' },
{ boxLabel: 'Status', name: 'rb3', inputValue: '3', itemId: 'check3' },
{ boxLabel: 'Action', name: 'rb4', inputValue: '4', itemId: 'check4' },
{ boxLabel: 'LOB', name: 'rb5', inputValue: '5', itemId: 'check5' },
{ boxLabel: 'Channel', name: 'rb6', inputValue: '6', itemId: 'check6' },
{ boxLabel: 'Company Name', name: 'rb7', inputValue: '7', itemId: 'check7' }
]
}]
}, {
buttons: [{
xtype: 'button',
text: 'RUN',
itemId: 'btnRun',
handler: function (button, event) {
//console.log("Working!", form);
var form = button.up('form');
//targetGridpanel = button.up();
//console.log("Working!", targetGridpanel);
//console.log("Working!", form);
if (form.isDirty()) {
var _vals = form.getValues();
if (!form.isValid()) {
console.log("Not Working!");
Ext.Msg.show({
icon: Ext.MessageBox.ERROR,
buttons: Ext.Msg.OK,
title: me.action + ' Report',
msg: 'Fill mandatory fields'
});
} else {
//console.log(_vals);
me.store.saveRecord(_vals, function () {
});
//me.store.load();
if (me.down('#check1').isDirty()) {
me.down('#rb1').show(true);
}
if (me.down('#check2').isDirty()) {
me.down('#rb2').show(true);
}
if (me.down('#check3').isDirty()) {
me.down('#rb3').show(true);
}
if (me.down('#check4').isDirty()) {
me.down('#rb4').show(true);
}
if (me.down('#check5').isDirty()) {
me.down('#rb5').show(true);
me.down('#time').show(true);
}
if (me.down('#check6').isDirty()) {
me.down('#rb6').show(true);
}
if (me.down('#check7').isDirty()) {
me.down('#rb7').show(true);
}
}
} else {
console.log("Close!");
}
}
}]
}, {
xtype: 'gridpanel',
store: me.store,
flex: 1,
margin: '20 0 0 0',
//minHeight: 300,
height: 240,
viewConfig: {
stripeRows: true
},
bbar: {
xtype: 'pagingtoolbar',
store: me.store,
displayInfo: true,
plugins: Ext.create('Ext.ux.ProgressBarPager')
},
columns: [{
dataIndex: 'date',
//itemId:'date',
text: 'DATE',
flex: 1,
menuDisabled: false,
}, {
dataIndex: 'rb1',
itemId: 'rb1',
text: 'ORDER ID',
flex: 1,
menuDisabled: false,
hidden: true,
}, {
dataIndex: 'rb2',
itemId: 'rb2',
text: 'CONNECTION NUMBER',
menuDisabled: false,
hidden: true,
flex: 2
}, {
dataIndex: 'rb3',
itemId: 'rb3',
text: 'STATUS',
menuDisabled: false,
hidden: true,
flex: 1
}, {
dataIndex: 'rb5',
itemId: 'rb5',
text: 'LOB',
menuDisabled: false,
hidden: true,
flex: 1
}, {
dataIndex: 'rb4',
itemId: 'rb4',
text: 'ACTION',
menuDisabled: false,
hidden: true,
flex: 1
}, {
dataIndex: 'time',
itemId: 'time',
text: 'ACTION TIME',
menuDisabled: false,
hidden: true,
flex: 1
}, {
dataIndex: 'rb6',
itemId: 'rb6',
text: 'CHANNEL',
menuDisabled: false,
hidden: true,
flex: 1
}, {
dataIndex: 'rb7',
itemId: 'rb7',
text: 'COMPANY NAME',
menuDisabled: false,
hidden: true,
flex: 1.5
}]
}
, {
buttons: [{
xtype: 'button',
text: 'DOWNLOAD',
itemId: 'download',
//actionMethods: {'read': 'POST'},
handler: function (button, event) {
var self = button.up();
var form = self.up('form');
var vals = form.getValues();
//console.log('Download', vals);
if (vals.from && vals.to && vals.type && (vals.rb1 || vals.rb2 || vals.rb3 || vals.rb4 || vals.rb5 || vals.rb6 || vals.rb7)) {
if (button) {
Ext.Msg.show({
icon: Ext.MessageBox.QUESTION,
buttons: Ext.Msg.YESNO,
title: 'Download Report',
msg: 'Do you want to download the <strong>selected</strong> report file?',
fn: function (buttonId, text, opt) {
if ('yes' == buttonId) {
//console.log(buttonId);
var dummyFormId = 'py-form-' + (new Date()).getTime();
//console.log(dummyFormId);
var frm = document.createElement('form');
frm.id = dummyFormId;
frm.name = dummyFormId;
//console.log(frm);
frm.className = 'x-hidden';
document.body.appendChild(frm);
Ext.Ajax.request({
url: utils.createUrl('api', 'report-download'),
form: Ext.fly(dummyFormId),
isUpload: true,
params: {
from: vals.from,
to: vals.to,
type: vals.type,
rb1: vals.rb1,
rb2: vals.rb2,
rb3: vals.rb3,
rb4: vals.rb4,
rb5: vals.rb5,
rb6: vals.rb6,
rb7: vals.rb7
},
callback: function (opts, success, res) {
console.log('Hello');
//Ext.getBody().unmask();
//console.log(params);
try {
if (success) {
var response = Ext.decode(res.responseText);
if (!response.success) {
throw response.data;
}
} else {
throw response.data;
}
} catch (ex) {
Ext.Msg.show({
icon: Ext.MessageBox.ERROR,
buttons: Ext.Msg.OK,
title: 'Download Report',
msg: 'No Data Found'
});
}
},
// fn: function () {
// console.log(arguments);
// }
});
}
}
});
}
} else {
Ext.Msg.show({
icon: Ext.MessageBox.ERROR,
buttons: Ext.Msg.OK,
title: 'Download Report',
msg: 'Please fill the form first'
});
}
}
}
]
}
]
}],
});
me.callParent(arguments);
I send these data to a store file. This is store file code.
extend: 'Ext.data.Store',
model: 'model.Report',
storeId: 'reportStore',
autoLoad: false,
pageSize: Configs.grid.pageSize,
saveRecord: function(data,fnCallBack) {
var me = this;
//var data = this.data;
//autoLoad: true,
//console.log(data);
Ext.getBody().mask('Please wait...');
Ext.Ajax.request({
url: utils.createUrl('api', 'report-read'),
params: data,
callback: function(opts, success, res) {
Ext.getBody().unmask();
try {
if(success) {
var response = App.decodeHttpResp(res.responseText);
if(response.success) {
Ext.Msg.show({
icon: Ext.MessageBox.INFO,
buttons: Ext.Msg.OK,
title: 'Reports',
msg: 'Report saved successfully'
});
} else {
throw response.error;
}
me.load();
} else {
throw 'Unknown Reason';
}
} catch (ex) {
Ext.Msg.show({
icon: Ext.MessageBox.ERROR,
buttons: Ext.Msg.OK,
title: 'Report',
msg: 'Failed to save data<br />' +
'Reason: ' + ex
});
}
}
});
}
This is my front-end model.
extend: 'Ext.data.Model',
fields: [
{ name: 'from', type: 'auto' },
{ name: 'to', type: 'auto' },
{ name: 'rb1', type: 'auto' },
{ name: 'rb2', type: 'auto' },
{ name: 'rb3', type: 'auto' },
{ name: 'rb4', type: 'auto' },
{ name: 'rb5', type: 'auto' },
{ name: 'time', type: 'auto' },
{ name: 'rb6', type: 'auto' },
{ name: 'rb7', type: 'auto' }
],
proxy: {
type: 'ajax',
noCache: false,
actionMethods: {'read': 'POST'},
api: {
read: utils.createUrl('api', 'report-read'),
//create: utils.createUrl('api', 'user-update'),
// update: utils.createUrl('api', 'user-update'),
// destroy: utils.createUrl('api', 'user-delete')
},
reader: {
type: 'json',
root: 'data'
},
listeners: {
exception: function(proxy, response, operation) {
App.showHttpError('Reports', response);
//console.log(this.fields);
}
}
}
Using these files I send data to controller. That's where my API is defined.
This is my controller function.
public function actionReportRead(){
$post = Yii::$app->request->post();
$time = 0;
$_vals = (new Order())->readReports(
#$post['start'],
#$post['limit'],
$post['from'],
$post['to'],
#$post['rb1'],
#$post['rb2'],
#$post['rb3'],
#$post['rb5'],
#$post['rb4'],
#$time,
#$post['rb6'],
#$post['rb7']
);
$this->setOutputData($_vals);
$this->setOutputStatus(true);
}
This is the model for that.
public function readReports($start, $limit,$from,$to, $rb1, $rb2, $rb3, $rb5, $rb4, $time, $rb6, $rb7 )
{
if (!$start) { $start = 0; };
if (!$limit) { $limit = Config::PAGE_SIZE; };
//$q = (new ActiveQuery(self::className()));
$q = self::find();
//$q->where(['between', 'submitted_time', $from, $to ]);
$q->alias('T')->andWhere(['BETWEEN', 'T.submitted_time', $from, $to ]);
$q->limit($limit);
$q->offset($start);
$q->orderBy(['T.order_id' => SORT_ASC]);
$data = [];
$action = null;
foreach ($q->all() as $_o) {
if($_o->status == 2){
$action = 'Data Entry Verified';
$time = $_o->timeDataEntry;
}else if($_o->status == 3){
$action = 'QC Accepted';
$time = $_o->timeQcPass;
}else if($_o->status == 4){
$action = 'Accepted';
$time = $_o->timeVerify;
}else if($_o->status == 1){
$action = 'Verification Pending';
$time = $_o->timeQcReject;
}else if($_o->status == 0){
$action = 'Rejected';
$time = $_o->timeQcReject;
}
$userlist='SELECT name FROM Company WHERE id = '.$_o->company_id;
$rsuserlist = Yii::$app->db->createCommand($userlist)->query();
$row = $rsuserlist->read();
$data[] = (object) array(
'date' =>$_o->submitted_time,
'rb1' =>$_o->order_id,
'rb2' =>$_o->conn,
'rb3' =>$_o->status,
'rb5' =>$_o->conn_type,
'rb4' =>$action,
'time' =>$time,
'rb6' =>$_o->channel,
'rb7' =>$row['name']
);
}
$json=Json::encode($data);
$this->logger->actLog($json);
return $data;
}
As I have found backend is fine. But I am not pretty sure. I new to extjs. So, I tried many ways but nothing worked. Data is not being loaded to grid and API sends me the error, I mentioned before. Please help me to solve this problem. What should I do more.
I found the answer and I am answering my own question.
Here, one API gets all the data correctly. Other one doesn't get 'from' and 'to' values. So I used following code.
me.store.getProxy().extraParams = {
from: vals.from,
to: vals.to
};
Using this I could send all the parameters to other API and eliminate that issue. Now data is fetched to the grid without a problem.

Sails/Waterline Populate doesn't work as expected

I'm bangin' my head against the wall in the last hours, and I can't figure out a solution to my problem. In my sails models, I have 2 one-to-many associations. 'A' model can have many 'B', and 'B' model can have many 'C'. In my controller, when I do a.find().populate('b') (...) it returns me the entire collection of A model, but populate each entry of A model with only one B, which doesn't match the current dataset I have in my database(mysql). And doesn't populate the C entries in the B model. In other words, I'm trying to achieve something like nested population.
It's something wrong with the Controller code, right? How can I make this work?
Thanks in advance!
EDIT:
Company.js
module.exports = {
identity: 'company',
attributes: {
name: {
type: 'string',
required: true
},
address: {
type: 'string',
required: true
},
zip_code: {
type: 'string',
required: true
},
city: {
type: 'string',
required: true
},
nif: {
type: 'integer',
required: true,
minLength: 9
},
country: {
type: 'string',
required: true
},
phone_number: {
type: 'string',
required: true
},
email: {
type: 'email',
required: true
},
facilities: {
collection: 'facility',
references: 'facility',
on: 'id',
via: 'company'
}
}
};
Facility.js
module.exports = {
identity: 'facility',
attributes: {
company: {
columnName: 'id_company',
model: 'company'
},
warehouses: {
collection: 'warehouse',
references: 'warehouse',
on: 'id',
via: 'facility'
},
name: {
type: 'string',
required: true
},
address: {
type: 'string',
required: true
},
zip_code: {
type: 'string',
required: true
},
city: {
type: 'string',
required: true
},
country: {
type: 'string',
required: true
},
phone_number: {
type: 'string',
},
email: {
type: 'email',
},
longitude: {
type: 'float',
},
latitude: {
type: 'float'
}
}
};
Warehouse.js
module.exports = {
identity: 'warehouse',
attributes: {
facility: {
columnName: 'id_facility',
model: 'facility',
},
name: {
type: 'string',
required: true
},
longitude: {
type: 'float',
},
latitude: {
type: 'float'
}
}
};
MainController's relevant code:
companies: function(req, res) {
company.find().populate('facilities').exec(function(err, comp){
var error = '';
if(err){
error = 'Unable to retrieve the requested information. Try again later and, if the problem persists, contact the platform administrator.';
} else if(!comp[0]) {
error = 'There\'s no company data inserted.';
}
// (...)
});
},
You should remove the references and on from your models.
Regarding nested population, just like I said in the comment, Waterline does not currently support it. You could check Waterline2 which, as they say, offers the possibility of nested populating, but is not recommended for production.
Otherwise you could check this out: Sails.js populate nested associations

Ext.data.Store.loadRawData reading only last record

I am trying to read a JSON response into Ext.grid.Panel using Ajax . However, Grid is showing only last record out of 5 results, can anyone please help:
JSON Response:
{"tweets":[{"text":"T 1156 -On #KBC the 1 crore winner Taj Mohammed Rangrez ... requires great maturity and guts to leave #KBC at 1crore and 2 lifelines unused","date":"1379273177","user":"\/SrBachchan","id":"145125358"},{"text":"T 1156 -Taj Mhammed Rangrez wins 1 crore rupees at #KBC .. what a game he played .. and he, such a beautiful human !! write in to #KBC","date":"1379272401","user":"\/SrBachchan","id":"145125358"},{"text":"T 1156 -SO ... what did you think of the 1st Crorepati winner on #KBC ... send in your comments to me through the #KBC tag .. love ya !!","date":"1379272302","user":"\/SrBachchan","id":"145125358"},{"text":"T 1156 -The last 2 tweets should have been numbered T 1156 ... apologies !!","date":"1379272226","user":"\/SrBachchan","id":"145125358"},{"text":"T 1155 -Ashok Chakradhar writes : \u092a\u094d\u0930\u0936\u094d\u0928 2. \u0905\u0928\u093e\u0921\u093c\u0940 \u091c\u0940, \u0906\u091c\u0915\u0932 \u0926\u0942\u0938\u0930\u094b\u0902 \u0915\u093e \u092d\u0932\u093e \u0915\u0930\u0928\u0947 \u0935\u093e\u0932\u094b\u0902 \u0915\u094b \u092c\u0947\u0935\u0915\u0942\u092b \u0938\u092e\u091d\u093e \u091c\u093e\u0924\u093e \u0939\u0948\u0964 (cont) http:\/\/tl.gd\/n_1rmfn3e ","date":"1379270895","user":"\/SrBachchan","id":"145125358"}]}
Ext Code:
var tweetModel = Ext.define('Tweet', {
extend: 'Ext.data.Model',
fields: [
{ name: 'text', type: 'string' },
{ name: 'date', type: 'string' },
{ name: 'user', type: 'string' },
{ name: 'id', type: 'string' }
]
});
var v= Ext.create('Ext.data.Store', {
model: tweetModel,
proxy: {
type: 'ajax',
url: '',
reader: {
type: 'json',
root: 'tweets'
}
}
});
var trailerPanel= Ext.create('Ext.grid.Panel', {
title: 'Tweets List',
store: v,
columns: [
{text: 'Text', dataIndex:'text',filterable: true},
{text: 'Date', dataIndex:'date',filterable: true},
{text: 'User', dataIndex:'user',filterable: true},
{text: 'ID', dataIndex:'id',filterable: true}
],
width: 1000,
forceFit: true,
});
var frmTrailerPanel = Ext.create('Ext.form.Panel', {
title: 'Hashtag Form',
width: 300,
bodyPadding: 10,
renderTo: Ext.getBody(),
items: [{
xtype: 'textfield',
itemId:'hashtag',
name: 'hashtag',
fieldLabel: 'Enter Hashtag',
allowBlank: false // requires a non-empty value
}
],
//renderTo:ext.getBody(),
buttons: [{
text: 'Search',
handler: function() {
var form = this.up('form').getForm();
if(form.isValid()){
form.submit({
url: '../../assignment/index.php',
waitMsg: 'Fetching tweets...',
success: function(form, action) {
},
failure: function(form, action) {
var myData = Ext.JSON.decode(action.response.responseText);
v.loadRawData(myData,true);
trailerPanel.render(Ext.getBody());
}
});
}
}
}
]
});
Output:
That is because all 5 have the same id value.

Fill in checkbox array with new collection

I'm trying to fill a checkbox array with a JSON array from the request URL. I have read the documentation and I see that I could do this with models and collections, but I'm not sure how to start. If anyone could show me what the path is, I would appreciate it. This is my code:
var mBox = Backbone.Model.extend({
});
var cBox = Backbone.Collection.extend({
model: mBox,
url: 'http://localhost/oferta/prueba1/?json=get_taxonomy&taxonomy=habilidad&dev=1'
});
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' },
otros: { type: 'Text', dataType: 'url' },
skills: { type: 'Checkboxes', options: new cBox() },
}
});
You're off to a good start. What I think might be tripping you up is how the data is actually fetched and placed into the collection. You have a defined a url property on cBox, your collection, but that itself does not actually get any data from the server. You have to call Backbone's Collection.fetch() method to get the data and put it into the collection.
I would do something like this:
cBoxCheckboxes = new cBox(); // create a new cbox, but there is no data in here yet
cBoxCheckboxes.fetch(); // make a get request to the server (at the url you've specified) to get the data
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' },
otros: { type: 'Text', dataType: 'url' },
skills: { type: 'Checkboxes', options: cBoxCheckboxes /* the collection with the data in it */ },
}
});
that solutions doesnt work like, i would like.. I rewrite the code and i do this:
var mmyBox = Backbone.Model.extend({});
var cmyBox = Backbone.Collection.extend({
model: mmyBox,
url: 'http://localhost/wordpress/oferta/prueba1/?json=get_taxonomy&taxonomy=habilidad&dev=1',
parse: function (resp, xhr) {
console.log(resp.terms);
return resp.terms;
}
});
function validateEmail(str) {
var regex = new RegExp("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?");
return regex.test(str) ? null : 'Invalid email';
}
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' },
otros: { type: 'Text', dataType: 'url' },
skills: { type: 'Checkboxes', options: new cmyBox() },
}
});
The parse function gives back the array terms from the json.
Array
{
"status": "ok",
"count": 3,
"terms": [
{
"id": 11,
"slug": "artist",
"title": "artist",
"description": "",
"post_count": 1
},
{
"id": 13,
"slug": "medico",
"title": "medico",
"description": "",
"post_count": 1
},
{
"id": 12,
"slug": "programador",
"title": "programador",
"description": "",
"post_count": 1
}
]
It seems than the new cmyBox doesnt create the new collection. Well that its what i see by console.
Thanks Josh for the answer. Cheers.