How to set a Ext.form.ComboBox default value from JSON? - json

I know that this is a simple question, but I got stuck looking for a solution.
First, I got the FormPanel, that obtains data passed by JSON that looks like:
var formPanel = new Ext.FormPanel({
....
[
{name: 'country', mapping: 'country'}
]
...
Then, I populate the store with data from an external file that has a list of countries
var countryStore = new Ext.data.SimpleStore({
fields: ['vcountry', 'vcountrydesc'],
data : Ext.ms.data.countries,
id:1,
});
What I want to do is to set a default value in a Ext.form.ComboBox, which is defined as name: 'country', precisely, I want to do something like this:
var countryFld = new Ext.form.ComboBox({
store: countryStore,
.....
mode: 'local',
forceSelection: true,
triggerAction: 'all',
emptyText: 'Select Country',
value: 'country', **<---I WANT TO DO THIS, BUT TO DISPLAY A VALUE, NOT A STRING!**
....
}
});
I assume that solution is very simple, but I got stuck on it.

SIMPLE, very stupid of me to ask...
Solution is just like for any other form
dataIndex: 'country',
instead of
value:'country',

Related

Dartlang: How to get key and values from json?

I'm having a little problem and couldn't figure it out. I created a table with checkbox and it's working and can save to json without a problem. Now i wanna make my checkboxes have their default values set from json data when the page loads (to make it easier to edit). Anyway here is my code:
//row index
var index = 0;
//gets full info of student
var responseStudent = rpc.call('db.findOne', ['StudentAnket', {
'_id': '${this.objId}'
}]);
result = responseStudent['result'];
//gets info needed for my table
//{anket: true, request: true, statement: false, etc...}
var resultMat = result['listmaterial'];
//materials is a list which contains id, name of rows
materials.forEach((m) {
//creating table body
index = index + 1;
tbody.append(new Element.tr()
..append(new TableCellElement()..text = index.toString())
..append(new TableCellElement()..append(new LabelElement()
..text = m['name']
..setAttribute('for', m['id'])))
..append(new TableCellElement()..append(new InputElement()
..id = m['id']
..type = "checkbox"
..checked = "VALUE TAKEN FROM JSON")));
});
So how can i get keys and values from resultMat and set checked property for each checkbox?
Edit:
List materials = [{
'id': 'anket',
'name': 'Student anket'
}, {
'id': 'request',
'name': 'Request'
}, {
'id': 'statement',
'name': 'Statement'
}, {
'id': 'marklist',
'name': 'Mark List'
}];
Your information how your materials structure looks like is not clear. A List has only one value not two ('id, 'name of rows'). First you have to ensure that your JSON is not a String but a Dart data structure (Lists, Maps, values).
You can take a look at the answers to this questions to learn how this works
Dart Parse JSON into Table
Then you should be able to access the value like
..checked = resultMat[m['id']] ;

ExtJs - Creating a Grid from records in a database

I'm using ExtJS 4.2 and I have some records in a MySql database. My question is: How can I create a grid that displays the records in the database?
I tried using ResultSet in a servlet to retrieve the records from the database, but I'm not sure how to proceed from there.
How can i populate the fields in the grid with the records in my database?
I'm new to ExtJS and I'm finding it difficult to come up with a solution for this. Does this have something to do with the store field? If so, how do i go about achieving the above said requirement?
You need to create store, bind to the grid and then load data from server. And sure you need backend for this ExtJS4 do not provide any tools for working with databases
For example( taken from sencha docs ):
Ext.onReady(function(){
Ext.define('Book',{
extend: 'Ext.data.Model',
proxy: {
type: 'ajax',
reader: 'xml'
},
fields: [
// set up the fields mapping into the xml doc
// The first needs mapping, the others are very basic
{name: 'Author', mapping: '#author.name'},
'Title', 'Manufacturer', 'ProductGroup'
]
});
// create the Data Store
var store = Ext.create('Ext.data.Store', {
model: 'Book',
autoLoad: true,
proxy: {
// load using HTTP
type: 'ajax',
url: 'sheldon.xml',
// the return will be XML, so lets set up a reader
reader: {
type: 'xml',
// records will have an "Item" tag
record: 'Item',
idProperty: 'ASIN',
totalRecords: '#total'
}
}
});
// create the grid
Ext.create('Ext.grid.Panel', {
store: store,
columns: [
{text: "Author", flex: 1, dataIndex: 'Author'},
{text: "Title", width: 180, dataIndex: 'Title'},
{text: "Manufacturer", width: 115, dataIndex: 'Manufacturer'},
{text: "Product Group", width: 100, dataIndex: 'ProductGroup'}
],
renderTo:'example-grid',
width: 540,
height: 200
});
});
The main idea is - models are for defining structure of the record and validation(read about it here), stores - for storing and fetching(by parsing response from server or local defined data) records that match model structure(Basic store) and finally grid handles some events(like "load" or "refresh") and updating rows based on grids column defenition(docs)

Sencha Touch 2 read values from key AND value from nested JSON

I am trying to load some JSON, in which I store a lot of variables about some 100 anaesthetic drugs for pediatric patients.
The actual values get calculated before from patient's weight, age etc.:
Example:
var propofolInductionTitle = propofolName + ' ' + propofol0PercentConcentration + '- Induktion';
var propofol0InductionDosageMG = (Math.round(kg * 2 * 10) / 10) + ' - ' + (Math.round(kg * 5 * 10) / 10);
I then create my drug as a block of json consisting of the variables I need which are later to be replaced by the calculated values. I specifically try to avoid Strings in the JSON to allow for easier localization to english and french when all variables are defined in the math block.
var hypnotikaJSON = {
"thiopentalTitle": [
{"thiopentalBrandName": ""},
{"vialContentTitle": "thiopentalVialContent"},
{"solutionTitle": "thiopentalSolution"},
{"concentrationTitle": "thiopentalConcentration"},
{"dosageString": "thiopentalDosageString"},
{"atWeight": "thiopentalDosageMG"},
{"thiopentalAtConcentration": "thiopentalDosageML"}
],
"propofolInductionTitle": [
{"propofolInductionBrandName": ""},
{"propofolVialContentTitle": "propofolInductionVialContent"},
{"propofolSolutionTitle": "propofolSolution"},
{"propofolConcentrationTitle": "propofolInductionConcentration"},
{"propofolInductionDosageStringTitle": "propofolInductionDosageString"},
{"atWeight": "propofolInductionDosageMG"},
{"propofolAtInductionConcentration": "propofolInductionDosageML"}
],
"propofolSedationTitle": [
{"propofolSedationBrandName":""},
{"propofolVialContentTitle":"propofolSedationVialContent"},
{"propofolSolutionTitle":"propofolSolution"},
{"propofolConcentrationTitle":"propofolSedationConcentration"},
{"propofolSedationDosageStringTitle":"propofolSedationDosageString"},
{"atWeight":"propofolSedationDosageMG"},
{"propofolAtSedationConcentration":"propofolSedationDosageML"}
],
"laryngealMaskTitle": [
{"laryngealMaskSizeTitle":"laryngealMaskSize"},
{"laryngealMaskCuffSizeTitle":"laryngealMaskCuffSize"},
{"laryngealMaskBiggestETTTitle":"laryngealMaskBiggestETT"},
{"laryngealMaskBronchoscopeSizeTitle":"laryngealMaskBronchoscopeSize"}
]
};
My specific need is that the JSON reader has to give me the key AND value of each object as I need both to populate a template. The reason ist that the fields for the drugs are different in parts. Some have additional routes of administration so I have another key:value pair a different drug doesnt have. Some are given both as bolus and per drip, some arent. So no convenient json structure ist possible.
I found an answer by rdougan here that partly allowed me to do just that:
Model:
Ext.define('my.model.Drug', {
extend: 'Ext.data.Model',
config: {
fields: ['name', 'value']
}
});
Custom Json Reader:
Ext.define('Ext.data.reader.Custom', {
extend: 'Ext.data.reader.Json',
alias: 'reader.custom',
getRoot: function (data) {
if (this.rootAccessor) {
data = this.rootAccessor.call(this, data);
}
var values = [],
name;
for (name in data) {
values.push({
name: name,
value: data[name]
});
}
return values;
}
});
Store:
var store = Ext.create('Ext.data.Store', {
fields: ['name', 'value'],
data: hypnotikaJSON,
autoLoad: true,
proxy: {
type: 'memory',
reader: {
type: 'custom'
}
}
});
Panel:
this.viewport = new Ext.Panel({
fullscreen: true,
layout: 'fit',
items: [{
xtype: 'list',
itemTpl: '<p class="description">{name}</p><p class ="values">{value}</p>',
store: store
}]
});
Unfortunately I'm a physician and no programmer, and after a lot of reading I cant find out to apply this to a nested JSON. The custom reader seems to only go for the first level.
I could do it without a reader, without a store with just a lot of plan html around each entry, that has proven to be very very slow though so I would like to avoid it while updating from Sencha Touch 1.1. and better do it right this time.
Could you please point me to a way to parse this ugly data structure?
Thank you
I don't know much about extending JSON readers, so just guessing, but maybe you are supposed override the 'read' method? Then you can go over the JSON as you wish
Also, if you have control over the JSON you should consider changing it.
Usually, the keys in JSON should be the same throughout all items in the array.
keys are not data, they are metadata.
So, if you do have different properties between different drugs, then something like this might be a solution:
[{
name: 'Propofol 1%',
properties: [
{title: 'induction', value: '22-56g'},
{title: 'Sedation', value: '22'},
etc.
]},
{name: 'nextDrug'}
etc..

Extjs combobox - getting json deeper values

For internal reasons, I have to send back from the server to the combo the following json string:
{"root":[{"employeeId":1,"user":{"userName":"admin"}}]}
As you can see, the user is actually an object, any way that the combobox will be able to read it?
the combo is configured as the following:
,displayField:'user.userName'
,title:'Manager'
,xtype: 'numberfield'
,hiddenName: 'employeeId'
,valueField : 'employeeId'
this is the store:
var store = new Ext.data.JsonStore({
autoLoad: true,
url: "/some_data",
root: 'root',
methos:'POST',
fields:[{name:"employeeId"},{name:"user.userName"}] });
the ext wont render it, any solution for that?
Use the 'mapping' property on fields in your store to remap the "deep" values to simple names the ComboBox can then reference:
new Ext.form.ComboBox({
fieldLabel: 'Manager',
hiddenName: 'employeeId',
store: new Ext.data.JsonStore({
root: 'root',
url: '/some_data',
method: 'POST',
fields: [
{name: 'employeeId'},
{name: 'userName', mapping: 'user.userName'}
]
}),
displayField: 'userName',
valueField: 'employeeId'
});

Filtering a comboxes remote store locally in ExtJs

I have an ExtJs combobox. Its store loaded using JSON (using MyStore class below). I want to load all the values to the store, and then filter them with the text entered in the combo's textfield (preferably using the typeAhead feature).
The problem is that I want to do the filtering on the client side (combo's mode property is 'remote', by default). I don't want my combo to reload its store every time I type something.
How can I do that?
Thanks.
Here's my store class :
MyStore = Ext.extend(Ext.data.JsonStore, {
constructor: function(jsonUrl, storeId, id, description, isAutoLoad, cfg) {
cfg = cfg || {};
GenericStore.superclass.constructor.call(this, Ext.apply({
storeId: storeId,
root: 'result',
url: jsonUrl,
autoLoad: isAutoLoad,
fields: [
{
name: id
},
{
name: description
}
]
}, cfg));
}
});
And the combo :
xtype: 'combo',
fieldLabel: 'The Combo',
width: 150,
store: myStoreData,
valueField: 'id',
displayField: 'name',
minChars : 0,
editable : false,
itemId : 'my-combo'
To achieve this you must:
Construct MyStore class with "isAutoLoad" config option as "true"
In your combobox config set the "mode" config option to "local" (see Built the combo config code bellow for another config)
Here is my short example:
Construct myStoreData variable
var myStoreData = new MyStore({
autoLoad: true, //so the store will load automatically
...any_other_config_option...
});
Built the combo config
{
xtype: 'combo',
fieldLabel: 'The Combo',
width: 150,
store: myStoreData,
// myStoreData is already loaded before as it have 'autoLoad' config set to true
// and act as localstore to populate the combo box item
// when the combo "mode" config set to 'local'
valueField: 'id',
displayField: 'name',
minChars : 0,
editable : true, //before was editable : false,
itemId : 'my-combo',
mode: 'local', // by default this was mode: 'remote'
typeAhead: true // by default this was typeAhead: false
}
You will want to use the store.filter() method. You can use this to use user-entered information to filter your store that the combo box uses. This is taken from the ExtJS API documentation for data.store.
store.filter([
{
property : 'name',
value : 'Ed',
anyMatch : true, //optional, defaults to true
caseSensitive: true //optional, defaults to true
},
//filter functions can also be passed
{
fn : function(record) {
return record.get('age') == 24
},
scope: this
}
]);
In my case I had to add the config option lastQuery:'' to the combo.
explanation : http://progex.wordpress.com/2010/03/26/extjs-combo-dropdown-does-not-filter-on-first-trigger/
Add listener to your store on 'load' event, do filtering, by removing or flagging records, if removing it is clear load to combo component, if flagging you need to recognize those flaggs in combo and display or not...
It hard to go with more details if I do not see your code for store and combo, so I can give you only general idea