Ext JS: Override JsonReader or post-process - javascript

A particular request to my server returns x fields of JSON. I want to combine several of these fields and insert the concatenated data into the x+1 field of my JsonStore.
I know how to process the load event, read each record, concatenate the appropriate fields, and insert into my x+1st field. However, is there a better (more efficient) way to accomplish this - perhaps by overriding JsonReader?

You are looking for Ext.data.Field.convert
Reference - ExtJS 3.x / ExtJS 4.x
Example using 4.x version -
....
fields: [
'name', 'email',
{name: 'age', type: 'int'},
{name: 'gender', type: 'string', defaultValue: 'Unknown'},
{
name: 'whatever',
convert: function(value, record) {
return record.get('f1') + record.get('a2'),
}
}
]
....

Related

Using ExpressionProperties to access different model templateOptions

Firstly I would like to say Angular Formly is a fantastic library for novices such as myself. I am not a web developer, however find this library to be intuitive and powerful.
However I do need assistance with use of Expression Properties.
I have a model library which contains library items, for example:
{
"itemId":"STX001",
"title":"Grey Wolf",
"category":"White", etc.
}
{
"itemId":"STX002",
"title":"Noble Black",
"category":"Black", etc.
}
etc.
I also have a formly form which uses ui-select in top field to lookup all values from Library, select one of these (I will call this Item), and then populate remaining fields in the form with Items properties, then submit form to Catalogue model.
The problem I am facing is I cannot reference the properties of Item from within other fields. I have tried using expressionProperties but can only extract the valueProp value (which is uniqueID), however I am after Item.title, Item.category, etc.
Code below:
{
//This is form fields for creating a new Catalogue entry
key: 'libraryId',
type: 'ui-select',
templateOptions: {
label: gettextCatalog.getString('Search Library'),
options: [],
valueProp: 'itemId',
itemTitle: 'title',
itemCategory: 'category',
labelProp: 'title',
focus: true,
placeholder: 'Start typing keywords..'
},
controller: function ($scope) {
getLibrary().then(function(data){
$scope.options.templateOptions.options = data;
return data;
});
}
}
{
key: 'title',
type: 'input',
templateOptions: {
label: gettextCatalog.getString('Name'),
required: true
},
expressionProperties : {
//This is what i'm trying to achieve but doesn't work
'templateOptions.placeholder' : 'model.libraryId.itemTitle'
}
},
Use the call back function provided
expressionPropertyObj = {
'templateOptions.required': (model, formState: any, field: FormlyFieldConfig) => {
console.log('model',model);
console.log('state',formState);
console.log('field',field);
},

Unable to display Gridx from JSON data

I have written a simple program to fetch data from an external JSON file and display it in Dojo Gridx. However, it is not working.
Dojo Code:
require(["dojo/text!json_to_gridx/js/data.json", "dojo/json", "gridx/Grid"], function(myJSONData, JSON, Gridx) {
// fetch and parse JSON
var myJSON = JSON.parse(myJSONData);
console.log(myJSON); // working fine
// create datastore
var store = myJSON; // should this be changed?
// create Gridx
if(!window.grid){
console.log('working'); // working fine
gridx = new Gridx({
id: 'grid',
store: store,
structure: [
{id: 'name', field: 'name', name: 'Name'},
{id: 'company', field: 'company', name: 'Company'}
]
});
console.log('working2'); // does not work
gridx.placeAt('gridContainer');
gridx.startup();
}
});
JSON:
[{"name": "Rahul Desai","company": "PSL"},{"name": "Alston","company": "PSL"}]
I am getting an error:
TypeError: cacheClass is not a constructor Model.js
How do I fix this? Please help!
EDIT: I was being suggested to use Memory Store and "gridx/core/model/cache/Async"
Now, the code for creating the Gridx looks like:
this._disksGrid = new Gridx({
id: 'grid',
cacheClass: asyncCache,
store: store,
structure: [
{id: 'name', field: 'name', name: 'Name'},
{id: 'company', field: 'company', name: 'Company'}
]
});
No error now, but the Gridx is not displayed. Any idea why?
EDIT 2: Turns out I was starting wrong grid in previous edit. Now the Gridx shows up but the second value is repeated and the first value does now show up.
Name Company
Alston PSL
Alston PSL
I made the changes mentioned in EDIT and EDIT 2 and also added unique IDs to every row of JSON and validated it correctly. That solved the problem.

Save nested form data back to server in ExtJS

I have a Model that contains an association to another Model. I am able to display the nested data into a form by using the mapping attribute on the field. Example:
Ext.define('Example.model.Request', {
extend: 'Ext.data.Model',
fields: [
{
name: 'id',
type: Ext.data.Types.NUMBER,
useNull: false
}
{
name: 'plan_surveyor',
mapping: 'plan.surveyor',
type: Ext.data.Types.STRING
}
],
associations: [
{type: 'hasOne', associationKey: 'plan', getterName:'getPlan', model: 'Specs.model.Plan'}
],
proxy: {
type: 'direct',
api: {
read: requestController.load,
update: requestController.update,
},
reader: {
type: 'json',
root: 'records'
},
writer: {
type: 'json',
writeAllFields: true,
nameProperty: 'mapping'
}
}
});
Using this method, I can display the plan.surveyor value in the form by reference plan_surveyor. I call Form.loadRecord(model) to pull the data from the model into the form.
However, now that I'm trying to send the data back to the server, I get the error:
Error performing action. Please report the following: "Unrecognized field "plan.surveyor"
I am attempting to save to the server by first calling Form.updateRecord(model), then model.save(). Is there a way to have the Writer understand that 'plan.surveyor' is not a property name but instead to properly handle nesting?
Am I doing this the right way to start with, or should I just be handling the setting of the form data and loading back into the model in a more manual fashion? It seems that nested data is not all that well supported in general - any recommendations?
Ext.define('Example.model.Request', {
extend: 'Ext.data.Model',
fields: [
{
name: 'id',
type: Ext.data.Types.NUMBER,
useNull: false
}
{
name: 'plan_surveyor',
mapping: 'plan.surveyor',//change to 'plan_surveyor'
type: Ext.data.Types.STRING
}
],
change that show in comment ,because data index is given in above format because ur give ur format thata time that is not dataindex it's a column or extjs preparatory ,so please change that may it's work well
it's not work u will send hole code

ExtJS: share store between grid and chart

I'm writing a simple application storing and displaying timestamped messages. Messages are JSON objects containing, say 2 main fields like:
{
"emitted": "2011-12-08 12:00:00",
"message": "This is message #666"
}
I have a model to describe these messages:
Ext.define('Message', {
extend: 'Ext.data.Model',
fields: [
{ name: 'emitted', type: 'date' },
{ name: 'message', type: 'string' }
]
});
I have no problem displaying these messages in a grid. However, i would now like to display these messages in a chart. For instance, I would be able to grab numbers (like the #666 in the above example) and display a line chart.
Ideally, i don't want to create a new store for the chart, i would like to reuse the same message store, but apply a filter on the fields to grab the proper value. I don't know, something that might look like:
var chart = {
xtype: 'chart',
...
series: [{
type: 'line',
axis: ['left', 'bottom'],
xField: 'emitted',
yField: {fieldName:'message', fieldGrabber: function(v) {
new RegExp("This is message #(\d+)$", "g").exec(v)[1]
}}
}]
};
Does this kind of thing is possible in ExtJS ?
I just tried to explain what I'm trying to do, i have no idea where to find such a feature: in the chart class, in the store class, or using a kind pf proxy to the store.
Side note:
I cannot ask the data to be properly formatted to the server. The messages I receive are not backed up anywhere, they are just live events streamed to the client via socketIO.
Any advices greatly appreciated!
You should extract the value inside you model to a separate field:
Ext.define('Message', {
extend: 'Ext.data.Model',
fields: [
{ name: 'emitted', type: 'date' },
{ name: 'message', type: 'string' },
{ name: 'nr', convert: function(v, r){
return r.get('message').replace(/^.*#/, '');
} }
]
});
Or you might be better off just having the 'nr' field and using a renderer in Grid that displays it as "This is message #{nr}".
Then you can use the 'nr' field directly in you chart.
I switched to Highcharts and threw ExtJS out to the trash :P

EXTJS Combobox not selecting by valueField after expand

I have written some code that works pretty well, but I have a strange bug
Here is an example...
PLEASE WATCH MY COMBOBOX BUG VIDEO
Like I said, this works well every time datachanged fires - the right index is selected and the displayField is displayed but, everytime after I type some text in the combobox, later, when the "datachanged" fires, it wont display the displayField. Instead, it displays the value from the setValue method I launch.
The strange thing is that if I don't ever type text and change the selection with the mouse there is no bug. Finally, this appears only when I type text in the combobox.
Has anyone heard of this bug, have a solution, or some wise advice?
The Code !
Two data stores :
ficheDataStore = new Ext.data.Store({
id: 'ficheDataStore',
autoLoad: true,
proxy: new Ext.data.HttpProxy({
url: 'ficheDetail.aspx', // File to connect to
method: 'GET'
}),
baseParams: { clientId: clientId, Type: 'Fiche' }, // this parameter asks for listing
reader: new Ext.data.JsonReader({ // we tell the datastore where to get his data from
root: 'results'
}, [
{ name: 'GUID', type: 'string', mapping: 'GUID' },
{ name: 'TagClient', type: 'string', mapping: 'TagClient' },
{ name: 'Nom', type: 'string', mapping: 'Nom' },
{ name: 'Compteur', type: 'string', mapping: 'CompteurCommunes' },
{ name: 'CompteurCommunesFacturation', type: 'string', mapping: 'CompteurCommunesFacturation' },
{ name: 'AdresseFacturation', type: 'string', mapping: 'AdresseFacturation' },
{ name: 'Codes', type: 'string', mapping: 'Codes' },
{ name: 'Observations', type: 'string', mapping: 'Observations' },
{ name: 'Adresse', type: 'string', mapping: 'Adresse' }
])
});
communesDataStore = new Ext.data.Store({
autoLoad: true,
proxy: new Ext.data.HttpProxy({ url: 'ficheDetail.aspx?Type=Communes' }),
reader: new Ext.data.JsonReader({ root: 'results' }, [{ name: 'Compteur' }, { name: 'Localisation'}])
});
Who return something like this for the
first:
{results:[{"Nom":"cercle interieur"},{"Observations":""},{"Codes":" "},{"Adresse":"dd"},{"CompteurCommunes"
:"1"},{"TagClient":"3-56"},{"GUID":"443609c6-d064-4676-a492-7baa7b4288d1"},{"AdresseFacturation":""}
,{"CompteurCommunesFacturation":"1"}]}
For the latter :
{"results":[{ "Compteur" : "1","Localisation" : "6200 ST ISIDORE"},{ "Compteur" : "2","Localisation"
: "21340 CHANGE"},{ "Compteur" : "3","Localisation" : "1200 ELOISE"},{ "Compteur" : "4","Localisation"
: "1200 ST GERMAIN SUR RHONE"},{ "Compteur" : "5","Localisation" : "75000 PARIS"},{ "Compteur" : "6"
,"Localisation" : "75001 PARIS 1ER ARRONDISSEMENT"}]}
a Combobox :
var comb = new Ext.form.ComboBox(
{
store: communesDataStore,
fieldLabel: 'Code postal',
// hiddenName: 'Compteur',
name: 'CompteurCommune',
id: 'CompteurCommunes',
width: 300,
typeAhead: true,
mode: 'local',
minChars: 0,
selecOnFocus: true,
forceSelection: true,
valueField: 'Compteur',
displayField: 'Localisation',
autocomplete: true,
emptyText: 'Selectionnez un code postal',
triggerAction: 'all',
value: ''
});
in a datachanged event i set the new value of the Combobox "CompteurCommunes" :
ficheDataStore.addListener('datachanged', handleDatachangedEvent);
function handleDatachangedEvent()
{
try {
comb.setValue(ficheDataStore.getAt(4).data.Compteur);
}
catch (err) { }
}
It's probably because when you type random data into combo, it may not locate correct fieldValue every time. Then it stucks at the last non-existing value.
Try to set ComboBox to any existing value (in combo's datastore) before doing new setValue() in your datachanged event handler. Or you can try to use clearValue() method to reset the previous (undefined) valueField.
There also initList() method existing to reset combo to initial state.
EDIT: After some testing, I found that:
combo.store.clearFilter(); must be used before setValue in the external event handler.
function formatComboBox(value, metaData, record, rowIndex, colIndex, store) {
myStore = Ext.getCmp('myComboBox');
myStore.clearFilter();
var idx = myStore.find('value',value);
return (idx != '-1') ? myStore.getAt(idx).data.label : value;
}
First, the Ext JS combobox should automatically apply the value and display when an item is selected, barring you've assigned a store and told Ext the field requires a value.
The value you appear to be asking for (CompteurCommunes) does not appear in your reader definitions, so it would be a part of the records in the data store.
What is the underlying reason for why you are trying to set this value for the ComboBox?
You can have a look at hiddenName and hiddenId parameter of Ext.form.ComboBox. If you set the value of hidden form field linked with combobox then combobox would render the label of that value instead of the value itself.
This is useful when you need to set the value at server end and direct the user to the page.
Another useful method is selectByValue. This method would select the element that has the value equal to the passed argument.
In your dataChangedListener instead of setting the value of combobox, you should set the value hidden form field associated with ComboBox. Also after setting the value of hidden field you might have to fire selectByValue method.
You can have a look at ExtJS API Documentation for further reference.
In case anybody - like me - get here through google because it's the most similar to their ComboBox ft. setValue() problem:
After an hour of stepping in out and over Ext's internals, I found that I needed to set lazyInit: false for the combo boxes. It defaults to true and being true may cause unlogical behaviour if you don't know about this. And why would you? Anything else seems to be not lazy by default.

Categories