Extjs model array of string mapping - javascript

It seems to be very basic question, but happens to kill lot of my time.
How can I map following in to Ext.data.Model?
<Principal>STEMMED CORP.</Principal>
<BusinessDefinitions>
<value>NY CLIENTS CORE</value>
<value>US LISTED DERIVS- STOCK,ADR,ETF</value>
<value>US CLIENT SITE TRADING</value>
<value>SYNDICATES - ADRS AND CBS</value>
<value>GWM CAPITAL MARKETS</value>
</BusinessDefinitions>
<countryOfResidence>USA</countryOfResidence>
Problem is, I unable to figure out how to get array of string for BusinessDefinitions against each value.
The following field is what I have added to Model.fields:
// Business Definition(s)
{
name: 'BusinessDefinitions',
type: 'auto',
mapping: 'value',
convert: function(n, record) {
console.log('BusinessDefinition: ' + n);
return n;
}
}
I have tried other combinations as well, but nothing seem to work.

The following was fabricated to fit your data from the example below.
Here is a Sencha Fiddle of the answer I have provided. It is 4.2.1.883 compliant. I have yet to try this with version 5.1.0.
Data
<BusinessArray>
<BusinessItem>
<Principal>STEMMED CORP.</Principal>
<BusinessDefinitions>
<value>NY CLIENTS CORE</value>
<value>US LISTED DERIVS- STOCK,ADR,ETF</value>
<value>US CLIENT SITE TRADING</value>
<value>SYNDICATES - ADRS AND CBS</value>
<value>GWM CAPITAL MARKETS</value>
</BusinessDefinitions>
<countryOfResidence>USA</countryOfResidence>
</BusinessItem>
</BusinessArray>
Application
Ext.define('App.model.Business', {
requires: [ 'Ext.data.reader.Xml' ],
extend: 'Ext.data.Model',
fields: [{
name: 'principal',
mapping: 'Principal',
type: 'string'
}, {
name: 'country',
mapping: 'countryOfResidence',
type: 'string'
}, {
name: 'businessDefs',
type : 'auto',
convert: function(value, record) {
var nodes = record.raw.querySelectorAll('BusinessDefinitions value');
var items = [];
for (var i = 0; i < nodes.length; i++) {
items.push(nodes[i].textContent);
}
return items;
}
}]
});
Ext.application({
name : 'Fiddle',
launch : function() {
var store = Ext.create('Ext.data.Store', {
model: 'App.model.Business',
proxy: {
type: 'ajax',
url: 'business.xml',
reader: {
type: 'xml',
record: 'BusinessItem'
}
},
autoLoad : true
});
Ext.create('Ext.panel.Panel', {
title : 'XML Model Example',
layout : 'hbox',
items : [{
xtype: 'combo',
fieldLabel: 'Business',
emptyText: 'select',
editable: false,
queryMode: 'local',
store: store,
displayField: 'principal',
valueField: 'businessDefs',
listeners : {
select: function (combo, record, index) {
Ext.Msg.alert('Business Definitions', combo.getValue().join('<br />'));
}
}
}],
renderTo: Ext.getBody()
});
}
});
Example
The example below is from the accepted solution from Sencha Forums: How do I parse a XML node to an array of strings? Also handing XML attributes?.
XML Data
<jobs>
<job>
<id>1</id>
<name audioSrc="audio/jobs/names/electrician.mp3">Electrician</name>
<attributes>
<attributeID>sitting</attributeID>
<attributeID>individual</attributeID>
<attributeID>lightEquip</attributeID>
<attributeID>doer</attributeID>
<attributeID>physical</attributeID>
<attributeID>repair</attributeID>
</attributes>
</job>
</jobs>
Store
Ext.create('Ext.data.Store', {
model: 'App.model.JobData',
proxy: {
type: 'ajax',
url: dataURL,
reader: {
type: 'xml',
record: 'job'
}
}
});
Model
Ext.define('App.model.JobData', {
requires: [ 'Ext.data.reader.Xml' ],
extend: 'Ext.data.Model',
config: {
fields: [{
name: 'id',
mapping: 'id',
type: 'int'
}, {
name: 'title',
mapping: 'name',
type: 'string'
}, {
name: 'attributeList',
mapping : 'attributes',
convert: function(value, record) {
var nodes = record.raw.querySelectorAll('attributes attributeID');
var arrayItem = [];
var l = nodes.length;
for (var i = 0; i < l; i++) {
var node = nodes[i];
arrayItem.push(nodes[i].textContent);
console.log(nodes[i].textContent);
}
return arrayItem;
}
}]
}
});

Following is what worked for me:
No need to add requires: [ 'Ext.data.reader.Xml' ],
With that, following is the final field
},{
//Business Definition/s
name: 'BusinessDefinitions',
type: 'auto',
mapping: function(data){
return data.children[2].children[10];
},
convert: function(value, record) {
var items = [];
var nodes = record.data.BusinessDefinitions.querySelectorAll('BusinessDefinitions value');
for (var i = 0; i < nodes.length; i++) {
items.push(nodes[i].textContent);
}
return items;
}
},

Related

How to insert several Model instances (array) inside a combobox in Ext JS

I barely know something regarding ExtJS and I'm struggling a lot since some days ago.
I know code presented here might not be the most performatic one, but it's a legacy application that I had to perform support (I did not develop it from scratch).
These below are called to populate a ExtJS combobox - carregaComboVersao makes a get call to server in order to obtain a response.
carregaVAloresCombo parses the response in order to populate combobox.
me.comboVersao is my combobox component, defined in this same javascript file as:
me.comboVersao = me.down('combobox[name=idVersao]');
carregaComboVersao: function(idObra){
var me = this;
KLIFT.model.mOrcamentoVersao.load(0, {
url: '../orcamentoVersao/buscaVersoesOrcamentoPorObra',
params: {
idObra: idObra
},
success: function(record){
alert(JSON.stringify(record));
me.carregaValoresCombo(record);
me.setLoading(false);
}
});
},
carregaValoresCombo: function(record){
var novo = JSON.stringify(record);
var me = this;
if (novo !== null) {
var item = record["raw"]["data"];
var array = new Array();
for(i=0; i<item.length; i++){
obj = Ext.create('KLIFT.model.mOrcamentoVersao', {
id : item[i].id,
dthrCriacao : item[i].dthrCriacao,
descritivoVersao: item[i].descritivoVersao,
versao: item[i].versao
});
}
me.comboVersao.setValue(obj);
}
Here is the combobox defined in a form component:
{
xtype: 'combobox',
fieldLabel: 'Versão',
displayField: 'descritivoVersao',
valueField: 'descritivoVersao',
width: 300,
name: 'idVersao',
editable:false,
model: Ext.create(('KLIFT.model.mOrcamentoVersao'))
}
and here is the model:
Ext.define('KLIFT.model.mOrcamentoVersao', {
extend: 'Ext.data.Model',
fields: [
{name: 'versao', type: 'int'},
{name: 'dthrCriacao', type: 'datetime'},
{name: 'descritivoVersao', type: 'string'},
{name: 'id', type: 'int'}
]
}
);
Any help is welcome.
Just an addition - response from server comes into 'record' variable as:
{"raw":{"data":[{"id":1,"dthrCriacao":"2018-02-25T00:00:00-0300","descritivoVersao":"mais veia","versao":0},{"id":2,"dthrCriacao":"2018-02-25T00:00:00-0300","descritivoVersao":"mais intermediaria","versao":1},{"id":3,"dthrCriacao":"2018-02-25T00:00:00-0300","descritivoVersao":"mais NOVA","versao":2}]},"modified":{},"data":{"versao":0,"dthrCriacao":"","descritivoVersao":"","id":0},"hasListeners":{},"events":{},"stores":[],"phantom":false,"internalId":0,"id":"KLIFT.model.mOrcamentoVersao-ext-record-2","dirty":true}
For pushing multiple values in combobox list, use store and map the store to the combobox.Mention the model in the store definition.
var store = Ext.create('Ext.data.Store', {
model: 'KLIFT.model.mOrcamentoVersao',
});
Add the multiple model instances to the store, which in turn will be added to the combobox.
comboVersao.getStore().add(obj);
For Example:
Ext.application({
name: 'Fiddle',
launch: function() {
Ext.define('KLIFT.model.mOrcamentoVersao', {
extend: 'Ext.data.Model',
fields: [{
name: 'versao',
type: 'int'
},
{
name: 'dthrCriacao',
type: 'datetime'
},
{
name: 'descritivoVersao',
type: 'string'
},
{
name: 'id',
type: 'int'
}
]
});
var store = Ext.create('Ext.data.Store', {
model: 'KLIFT.model.mOrcamentoVersao',
});
var comboVersao = Ext.create('Ext.form.ComboBox', {
fieldLabel: 'Versão',
displayField: 'descritivoVersao',
valueField: 'descritivoVersao',
width: 300,
name: 'idVersao',
editable: false,
store: store,
queryMode: 'local',
renderTo: Ext.getBody()
});
var carregaValoresCombo = function(record) {
var novo = JSON.stringify(record);
var me = this;
if (novo !== null) {
var item = record["raw"]["data"];
var array = new Array();
for (i = 0; i < item.length; i++) {
obj = Ext.create('KLIFT.model.mOrcamentoVersao', {
id: item[i].id,
dthrCriacao: item[i].dthrCriacao,
descritivoVersao: item[i].descritivoVersao,
versao: item[i].versao
});
comboVersao.getStore().add(obj);
}
}
}
carregaValoresCombo({"raw":{"data":[{"id":1,"dthrCriacao":"2018-02-25T00:00:00-0300","descritivoVersao":"mais veia","versao":0},{"id":2,"dthrCriacao":"2018-02-25T00:00:00-0300","descritivoVersao":"mais intermediaria","versao":1},{"id":3,"dthrCriacao":"2018-02-25T00:00:00-0300","descritivoVersao":"mais NOVA","versao":2}]},"modified":{},"data":{"versao":0,"dthrCriacao":"","descritivoVersao":"","id":0},"hasListeners":{},"events":{},"stores":[],"phantom":false,"internalId":0,"id":"KLIFT.model.mOrcamentoVersao-ext-record-2","dirty":true});
}
});
<link rel="stylesheet" href="https://cdn.sencha.com/ext/gpl/4.1.1/resources/css/ext-all.css">
<script type="text/javascript" src="https://cdn.sencha.com/ext/gpl/4.1.1/ext-all-debug.js"></script>

ext js 6 pass dynamic id from grid panel to model

How to passing id from gridpanel to model ?
here my grid panel code:
{
text : 'Tindakan',
xtype: 'actioncolumn',
minWidth: 130,
sortable: false,
menuDisabled: true,
items: [{
icon: 'images/view.png', // Use a URL in the icon config
tooltip: 'Lihat',
handler : function(grid, rowIndex, colIndex) {
var rec = grid.getStore().getAt(rowIndex);
alert("Lihat - " + rec.get('id'));
}]
}
Here is my model code:
Ext.define('Kds.model.ProfilView', {
extend: 'Ext.data.Store',
alias: 'model.profilView',
fields: [
'name',
'ic_no',
'address',
],
pageSize : 20,
proxy: {
type: 'rest',
url : 'http://localhost/kds-rest/web/index.php/people/view/'+id,
useDefaultXhrHeader : false,
withCredentials: false,
reader: {
type: 'json',
rootProperty: 'data',
//totalProperty: 'totalItems'
}
},
autoLoad: 'true',
});
How do you use that model? If you create or use that each time, you can try this:
handler : function(grid, rowIndex, colIndex) {
var rec = grid.getStore().getAt(rowIndex);
//Create or get model to use
var model = Ext.create('Kds.model.ProfilView', {
// then give the record id to model
recordId: rec.get('id') // edited
});
}
// to use in model
Ext.define('Kds.model.ProfilView', {
extend: 'Ext.data.Store',
alias: 'model.profilView',
fields: [
'name',
'ic_no',
'address'
],
pageSize : 20,
autoLoad: 'true',
initComponent: function() {
var me = this;
me.proxy = {
type: 'rest',
url : 'http://localhost/kdsrest/web/index.php/people/view/'+me.recordId, // or this.up().recordId,
................
} // iniComponent
me.callParent();
Edit: How to load model dynamically: fiddle: https://fiddle.sencha.com/#fiddle/11g9
Ext.define('model.instance', {
extend: 'Ext.data.Model',
fields: ['name', 'city', 'country'],
proxy: {
type: 'ajax',
url: 'info',
reader: {
type: 'json',
rootProperty: 'records'
}
}
});
var fn = function getSelectedRow(gridView, rowIndex, colIndex, column, e,direction) {
var me = this;
var store = gridView.getStore();
var record = store.getAt(rowIndex);
var inst = Ext.create('model.instance', {
name: record.get('name')
});
inst.load({
scope: this,
success: function(rec) {
console.log(rec);
}
});
}
var store1 = Ext.create('Ext.data.Store', {
fields: ['name', 'surname'],
data: [{
name: 'Rick',
surname: 'Donohoe'
}, {
name: 'Jane',
surname: 'Cat'
}]
});
var grid = Ext.create('Ext.grid.Panel', {
columns: [{
dataIndex: 'name'
}, {
dataIndex: 'surname'
}, {
xtype: 'actioncolumn',
text: 'Select',
icon: '/image',
handler: Ext.bind(fn, this)
}],
store: store1,
renderTo: Ext.getBody()
});

Store loaded, grid rendered with rows but no data shown

Here's a grid:
Ext.define('Customer_Portal_UI.view.BulkUpdateResultWindow.ResultGrid', {
extend: 'Ext.grid.Panel',
alias: 'widget.ResultGrid',
itemId: 'ResultGrid',
columns: [
{ text: 'Participant', mapping: 'firstname' },
{ text: 'Success', mapping: 'success' },
{ text: 'Status', mapping: 'statusMessage' }
],
viewConfig: { itemId: 'ResultGridView' },
initComponent: function () {
this.store = Ext.create('Ext.data.ArrayStore', {
storeId: 'ResultGridStore',
idProperty: 'contactid',
fields: [
'firstname',
'success',
'statusMessage',
'contactid'
]
});
this.callParent();
}
});
Here's how I attempt do load it:
var grid = this.Utils.getCmp('gridpanel[itemId=ResultGrid]');
var store = grid.getStore();
var response = Ext.JSON.decode(result.responseText);
for (var i = 0; i < response.length; i++) {
store.add({ firstname: response[i].contact.firstname, success: response[i].success, statusMessage: response[i].statusMessage, contactid: response[i].contact.contactid });
}
If I go in the console after that for loop, the store is loaded. If I call getStore() on the grid, its store contains data as well.
But the grid is rendered with the right number of lines (matching # of records in response) but those lines are empty.
Any ideas ?
Thanks!
Column doesn't have a mapping property. Use dataIndex.

ExtJS 4 remoteSort asDate

For my remote-sort i use in ExtJS 3 the keyword asDate which was sent in direction-part of request:
sort:my_date
dir:asDate ASC
In ExtJS 4 i miss the sortType information in Request:
sort:[{"property":"my_date","direction":"DESC"}]
is there any way to get the sortType information on server side?
You can the override encodeSorters function. I'll make you an example :)
http://jsfiddle.net/Vandeplas/xLz5C/1/
var store = Ext.create('Ext.data.Store', {
model: 'User',
sorters: [{
property: 'age',
direction: 'DESC',
sortType: 'asDate'
}, {
property: 'firstName',
direction: 'ASC'
}],
proxy: {
type: 'ajax',
url: '/echo/json/',
reader: {
type: 'json',
root: 'users'
},
encodeSorters: function (sorters) {
var min = [],
length = sorters.length,
i = 0;
for (; i < length; i++) {
min[i] = {
property: sorters[i].property,
direction: sorters[i].direction,
sortType: sorters[i].sortType
};
}
return this.applyEncoding(min);
}
}
});

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