ExtJs - How to get value from the Store by id? - extjs

How to get value from the Store by id?
store in such fields
fields: [
{name: "id", type: 'int'},
{name: "name", type: 'String'},...
I need to get the id - name value.
I try so:
var rec = Ext.StoreMgr.lookup("MyStore").getById(id);
alert(rec.data.name);
what am I doing wrong?

The function getById finds the record with the specified id which has nothing to do to with the id you specified in the fields config - Basically you're looking at record.id while you should be looking at record.data.id.
For 3.3.1 you should use:
var index = Ext.StoreMgr.lookup("MyStore").findExact('id',id);
var rec = Ext.StoreMgr.lookup("MyStore").getAt(index);

Related

Declare array into searchFields Worklight JSONStore

I have a JSON object to my collection with JSONStore like this:
{
name : 'name1',
industry : ['Banking', 'Energy', 'Insurance', 'Media', 'Retail', 'Telco', 'Travel'],
buyer : ['CMO'],
link : 'foo.com'
}
But, how is possible declare the industry field into searchFields?, in order to search a pattern in the array.
Cheers
There's no array type for search fields. You can only index values in objects that are string, boolean, number and integer.
You could change:
{ industry : ['Banking', 'Energy'] }
to:
{ industry : [{name: 'Banking'}, {name: 'Energy'}] }
and then use the following search field: {'industry.name' : 'string'}. That will enable you to do something like WL.JSONStore.get('collection').find({'industry.name' : 'Banking'}, {exact: true}) and get back an object like this one:
[{_id: ..., json: {name: ..., industry: [..., {name: Banking}, ...], buyer: ..., link: ...}}]
This is documented under the search field section of general terminology in the documentation here.
That would mean writing code like this to change the data being added to the collection:
var output = [];
['Banking', 'Energy', 'Insurance', 'Media'].forEach(function (element) {
output.push({name: element});
});
console.log( JSON.stringify(output, null, ' ') );
Alternatively, you could also change it into a string:
{industry : ['Banking', 'Energy', 'Insurance', 'Media'].toString() }
and get back something like this:
{industry : "Banking,Energy,Insurance,Media"}
Then you can use the search field {industry : 'string'} and do something like WL.JSONStore.get('collection').find({industry: 'Energy'}, {exact: false}) to get objects that have Energy somewhere in the industry value string.
FYI - Feature requests here.

add 2 variables of XTemplate in extjs

I am trying to add 2 member variables of Xtemplate.
I tried something like this
reader: new Ext.data.XmlReader({
record: 'RealTimeFlow'
},[
{name: 'successEvent', mapping: '#sEvents'},
{name: 'successLatency', mapping : '#sLatency'},
{name: 'failedEvent', mapping: '#fEvents'},
{name: 'failedPercent', mapping: '#fPercent'},
{name: 'failedLatency', mapping : '#fLatency'}
])
});
var RTFtpl = new Ext.XTemplate(
'<p align="left">Total Events:{[values.successEvent+values.failedEvent]}<br \>',.........................
If success event = 40 and failed event = 6
then the answer should be 44 ...... but by using the above I am getting 406
Any idea what I am doing wrong
That's because it is adding two strings together
'40' + '6' = '406' in Javascript
Try parsing them as numbers. You could use parseInt perhaps, or make sure that the values are numbers in your model.
fixed the problem
in the store added the type value to the variables
reader: new Ext.data.XmlReader({
record: 'RealTimeFlow'
},[
{name: 'successEvent', mapping: '#sEvents', type : 'int'},
{name: 'successLatency', mapping : '#sLatency'},
{name: 'failedEvent', mapping: '#fEvents',type : 'int'},
{name: 'failedPercent', mapping: '#fPercent'},
{name: 'failedLatency', mapping : '#fLatency'}
]),
newDate : new Date()
});
and
var RTFtpl = new Ext.XTemplate(
'<p align="left">Total Events:{[values.successEvent+values.failedEvent]}<br \>',

ExtJS 4 Show data from multiple stores in grid

I have 2 models - for example - Users and Orders
Ext.define('AM.model.User', {
extend: 'Ext.data.Model',
fields: ['id', 'username', 'firstName', 'lastName', 'state', 'city'],
associations: [
{
type: 'hasMany',
model: 'Order',
name: 'orders'
},],
});
Ext.define('AM.model.Order', {
extend: 'Ext.data.Model',
fields: ['id', 'userId', 'date', 'description', 'value'],
belongsTo: 'User',
});
and their stores. I'm looking for a way to display data from both stores in grid. (so my columns would be firstName, lastName, orderDate, orderDescription, orderValue...
What is the proper way to display them?
Thanks.
You should do this with your server side code and get this all data into a single store.
If you want to do this with associations, you need to define a renderer for your grid column.
Like so:
{
text: "orderDescription",
renderer: function(value,meta,record){//1.
//var orderStore = record.orderStore;//2a.
//var orderList = ordersStore.data.items;//2b.
var orderList = record.orders().data.items; //3.This line is the same as 2 the lines above(2a,2b).
var order = orderList[0]; //4. TODO..loop through your list.
var description = order.data.description; //5.
return description ;
},
I will try to explain for anyone who wants to do it this way.
The third parameter is the current record in your 'User' Store being renderd for the grid. The first two just need to be there, to receive record. Leaving them out will not work.
1a/1b. I left these there to demonstrate how the association works. Basically, each record in your 'User' Store gets its own corresponding 'ordersStore'. It will be called 'ordersStore', because you put in your association [name: 'orders'].
The orders() method is automatically created, again based on the name 'orders'. This just returns the orderStore. The store contains a field data -> which contains a field items. items is the actual list of orders.
Now you have access to your list of orders. You can loop trough the orders now. Or if you have only one order, just the first one.
Your order again contains a field data which contains your actual data.
Lets try with below example-
Step 1: Adding records from Store 2 to Store 2.
var store2 = new Ext.data.Store({
...
});
var store1 = new Ext.data.Store({
...
listeners: {
load: function(store) {
store2.addRecords({records: store.getRange()},{add: true});
}
}
});
Step 2: Using records from Store 2 with Store 1.
For example, the first data col comes from Store 1 and the data from Store 2 forms cols 2 and 3. You can use a renderer that finds the data in the second store if the 'other' columns are just 'lookup' data, e.g.:
var store1 = new Ext.data.Store({
...,
fields: ['field1', 'field2']
});
var store2 = new Ext.data.Store({
...
id: 'field2',
fields: ['field2', 'fieldA', 'fieldB']
});
var renderA = function(value) {
var rec = store2.getById(value);
return rec ? rec.get('fieldA') : '';
}
var renderB = function(value) {
var rec = store2.getById(value);
return rec ? rec.get('fieldB') : '';
}
var columns = [
{header: 'Field 1', dataIndex: 'field1'},
{header: 'Field A', dataIndex: 'field2', renderer: renderA},
{header: 'Field B', dataIndex: 'field2', renderer: renderB}
];
Best of luck.
Ref. from here

How to add records in json-store

var store = new Ext.data.JsonStore({
id:'jfields',
totalProperty:'totalcount',
root:'rows',
url: 'data.php',
fields:[{ name:'jfields' },
{ name:'firstyear' , mapping :'firstyear' , type:'float' },
{ name:'secondyear', mapping :'secondyear', type:'float' },
{ name:'thirdyear' , mapping :'thirdyear' , type:'float' },
{ name:'fourthyear', mapping :'fourthyear', type:'float' },
{ name:'fifthyear' , mapping :'fifthyear' , type:'float' } ]
}
});
What I want is to add data at the end for this store , but I am totally confused , what I did is I add the following code to it but not working.
listeners: {
load : function(){
BG_store.add([{"jfields":"Monthly","firstyear":22.99,"secondyear":21.88,"thirdyear":21.88,"fourthyear":22.99,"fifthyear":21.88}]);
}
}
But I do not think my concept are cleared ,Please any body show some way how to do it .
You need to define a record type, create it and at it, e.g:
TaskLocation = Ext.data.Record.create([
{name: "id", type: "string"},
{name: "type", type: "string"},
{name: "type_data", type: "string"},
{name: "display_value", type: "string"}
]);
Then:
var record = new TaskLocation({
id: Ext.id(),
type: "city",
type_data: "",
display_value: "Brighton"
});
Then:
my_store.add(record);
my_store.commitChanges();
Remember by the time the data is in the store it's not in the same format as you sent it down but in Record objects instead.
See the recordType property in the JsonStore. It's a function that can be used as a record constructor for the store in question. Use it like this:
var newRecord = new myStore.recordType(recordData, recordId);
myStore.add(newRecord);
I have also figured out a simple solution to this:
listeners: {
load: function( xstore , record , option ) {
var u = new xstore.recordType({ jfields : 'monthly' });
xstore.insert(record.length, u);
}
}
Here what I have to add is this listeners as when the data loads it will create the record type and u can add fields as data as many as u want

Populate a combobox using DirectStore

I'm having issues while populating a combobox using DirectStore, the combobox is as follow:
this.Combo = new Ext.form.ComboBox({
fieldLabel: "Name",
editable: false,
triggerAction: 'all',
mode: 'remote',
store: new Ext.data.DirectStore({
reader: new Ext.data.JsonReader({
successProperty: 'success',
idProperty: 'name',
root: 'data',
fields: [ 'name' ]
}),
autoLoad: true,
api: { read: SS.MyApi.getNames }
}),
valueField: 'name',
displayField: 'name'
});
The returned json is:
[{"type":"rpc","tid":7,"action":"MyApi","method":"getNames","result":{"success":true,"data":{"name":["name1","name2","name3"]}}}]
And the c# code that generates the json
[DirectMethod]
public JObject getNames()
{
List<string> names = new List<string>();
names.Add("name1");
names.Add("name2");
names.Add("name3");
JObject data = new JObject();
data.Add(new JProperty("name", names));
return new JObject(
new JProperty("success", true),
new JProperty("data", data)
);
}
The combobox is showing only one entry with "name1,name2,name3". How can i have one entry per name?
Thanks in advance!
your returned json tells the combobox exactly what to do
"data":{"name":["name1","name2","name3"]}
i only has 1 field (name) in data and this has the value name1, name2, name3
your json has to look more like this:
data : [
{
name : "name1"
}, {
name : "name2"
}, {
name : "name3"
}
]
Trick: I don't know how to mapping this yet, but you can convert it to specific type (anonymous) like this (using Linq):
var list = names.Select(s => new { name = s });
you return
JObject > JProperty data
|----> JObject > JProperty name
|----> List<string>
For me one of the JObject > JProperty is OPTIONAL, lets said is name... then you reader root is ok (data) and the field should is also mapping correctly with the transformation that we did.
In your code, you return
JObject > JProperty data
|----> Enumerable<{name}>
"result":{"success":true,"data":[{"name":"name1"},{"name":"name2"},{"name":"name3"}]}
NOTE: Obviously if you know how to mapping string directly you don't have to convert it and will be better.

Resources