why add newRecord[] is empty - extjs

I have a problem when adding a newRecord, the console always outputs [].
Please help me.
_storePR2.add(_key.data);
_storePR2.commitChanges();
var newRecord = _storePR2.getNewRecords();
console.log('newRecord',newRecord);
Output: newRecord []
enter image description here
this my store code and model :
Ext.define('Sasmita.store.vending.purchase.Purchasegoodrec', {
extend: 'Ext.data.Store',
requires: [
'Ext.data.proxy.Ajax',
'Ext.data.reader.Json',
'Ext.data.Field'
],
constructor: function(cfg) {
var me = this;
cfg = cfg || {};
me.callParent([Ext.apply({
autoLoad: false,
storeId: 'vending.purchase.Purchasegoodrec',
proxy: {
type: 'ajax',
url: 'jsonresult/Sasmita_Vending_Purchase/getPurchaseGoodrec',
reader: {
type: 'json',
root: 'data',
idProperty: 'sitecode2'
}
},
fields: [
{
name: 'purchase_id_tr'
},
{
name: 'parent_id'
},
{
name: 'file_ext'
},
{
name: 'file_name'
},
{
name: 'file_size'
},
{
name: 'description'
},
{
name: 'id'
},
{
name: 'id_file'
},
{
name: 'id_po'
},
{
name: 'qty_hasil'
},
{
name: 'no_pr'
},
{
dateFormat: 'Ymd',
name: 'date_pr',
type: 'date'
},
{
name: 'warehouse'
},
{
name: 'warehouse_name'
},
{
name: 'row_created_by'
},
{
name: 'row_created_datetime'
},
{
name: 'row_changed_by'
},
{
name: 'row_changed_datetime'
},
{
name: 'title'
},
{
name: 'notes'
},
{
name: 'qty_order'
},
{
name: 'no_po'
},
{
name: 'date_po'
},
{
name: 'supplier'
},
{
name: 'package'
},
{
name: 'qty_approve'
},
{
name: 'purchase_product_name'
},
{
name: 'unit'
},
{
name: 'unit_price'
},
{
name: 'total_price'
},
{
name: 'total_price_head'
},
{
name: 'vat'
},
{
name: 'net_price'
},
{
name: 'sum_total'
}
]
}, cfg)]);
}
});
and this my controller action button choose :
var me = this;
var _panel = me.getMainPanel();
var _tabpanel = _panel.down('#tabmaintain');
var _activetab = _tabpanel.getActiveTab();
var _window = button.up('window');
var _grid = _window.down('grid');
//var _girdd = this.getPanelSearch();
//var _grids = _girdd.down('grid');
var _gridSelected = _grid.getSelectionModel().getSelection();
//var row = _grid.store.indexOf(_gridSelected);
//console.log(row);
console.log(_gridSelected);
console.log(_grid);
//console.log(_girdd.down('grid'));
//selected=[];
//Check selected product
if(_gridSelected.length===0){
Ext.Msg.alert('Warning','Please select product');
return;
}
//Submit Product
var _gridPR = _activetab.down('#detailProduct');
var _storePR2 = _gridPR.getStore();
//console.log(_storePR2.data);
Ext.Array.each(_gridSelected,function(_key,_value,item){
//console.log(selected.push(item));
_validate = true;
_storePR2.each(function(_storeData,_storeIndex){
console.log(_key.data);
if(_storeData.data.no_po === _key.data.no_po){
_validate = false;
Ext.Msg.alert('Warning','The Product had been picked');
return;
}
});
if(_validate){
// Add record to the store by data
_storePR2.add(_key.data);
// Get array of new records from the store
var newRecords = _storePR2.getNewRecords();
console.log('newRecord',newRecords);
// Commit changes after getting new records
_storePR2.commitChanges();
_window.close();
}
});

That is because you committed the changes, so there are no longer any 'new records'.
Try to get the new records before committing the changes:
// Add record to the store by data
_storePR2.add(_key.data);
// Get array of new records from the store
var newRecords = _storePR2.getNewRecords();
console.log('newRecord',newRecords);
// Commit changes after getting new records
_storePR2.commitChanges();
Here is a fiddle.

First you need to add records to store and commit changes,then get new records.
grid_store.add({'Name':"ab",'dob':"099"})
grid_store.commitChanges();
var newRecord = grid_store.getNewRecords()
console.log('newRecord',newRecord);
});
Here is a fiddle: http://jsfiddle.net/2p78md5t/3/

Related

PullRefresh plugin of a List doesn't handle ChainedStore possibility

Using Ext JS 7.1 Modern, I have prepared an example to show the problem.
When I have remote filters on my main store, binding the dataview.List to a ChainedStore correctly handles my local filtering. However, when I also add a PullRefresh plugin to the list, I get an error during pull refresh. I see from the source code that the plugin doesn't consider the possibility that a list's store can be a ChainedStore.
I have tried to explain the problem with a Sencha Fiddle and also attached the code below.
I have temporarily solved the problem by overriding the fetchLatest and onLatestFetched methods of Ext.dataview.pullrefresh.PullRefresh plugin, to use the source store if the list's store is a ChainedStore. But I believe the source code must be updated to handle this case.
app.js
Ext.define('App.model.Test', {
extend: 'Ext.data.Model',
fields: ['id', 'firstName', 'lastName']
});
Ext.define('App.store.Test', {
extend: 'Ext.data.Store',
alias: 'store.teststore',
model: 'App.model.Test'
});
Ext.define('App.viewmodel.Test', {
extend: 'Ext.app.ViewModel',
alias: 'viewmodel.test',
data: {
query: ''
},
stores: {
test: {
type: 'teststore',
autoLoad: true,
proxy: {
type: 'ajax',
url: 'names.json',
reader: {
type: 'json',
rootProperty: 'data'
}
},
remoteFilter: true,
filters: {
property: 'id',
value: 1
}
},
chained: {
type: 'chained',
autoLoad: true,
source: '{test}'
}
}
});
Ext.define('App.controller.TestController', {
extend: 'Ext.app.ViewController',
alias: 'controller.testcontroller',
doSearch: function (field) {
var list = this.lookup('list'),
store = list.getStore(),
value = field.getValue();
if (Ext.isEmpty(value)) {
store.removeFilter('firstName')
} else {
store.filter([{
property: 'firstName',
value: value,
operator: 'like'
}])
}
}
});
Ext.define('App.dataview.TestList', {
extend: 'Ext.dataview.List',
xtype: 'testlist',
viewModel: {
type: 'test'
},
plugins: [{
type: 'pullrefresh',
mergeData: false
}],
emptyText: 'Name not found',
bind: {
store: '{chained}'
},
itemTpl: '<div class="contact">{id} <b>{firstName} {lastName}</b></div>'
});
Ext.define('App.MainView', {
extend: 'Ext.Panel',
controller: 'testcontroller',
fullscreen: true,
viewModel: {
type: 'test'
},
items: [{
xtype: 'searchfield',
ui: 'solo',
placeholder: 'Search names',
listeners: {
buffer: 500,
change: 'doSearch'
},
bind: {
value: '{query}'
}
}, {
reference: 'list',
xtype: 'testlist'
}]
})
Ext.application({
name: 'App',
mainView: 'App.MainView'
});
names.json
var data = [{
id: 1,
firstName: 'Peter',
lastName: 'Venkman'
}, {
id: 2,
firstName: 'Raymond',
lastName: 'Stantz'
}, {
id: 3,
firstName: 'Egon',
lastName: 'Spengler'
}, {
id: 4,
firstName: 'Winston',
lastName: 'Zeddemore'
}]
var results = data.filter(function(record) {
if (params.filter) {
return record.id > params.filter[0].value
}
})
return {
"success": true,
"data": results
}
App.override.dataview.pullrefresh.PullRefresh:
Ext.define('App.override.dataview.pullrefresh.PullRefresh', {
override: 'Ext.dataview.pullrefresh.PullRefresh',
privates: {
fetchLatest: function() {
const store = this.getStore().isChainedStore ? this.getStore().getSource() : this.getStore()
store.fetch({
page: 1,
start: 0,
callback: this.onLatestFetched,
scope: this
});
},
onLatestFetched: function(newRecords, operation, success) {
var me = this,
list = me.getList(),
store = list.getStore().isChainedStore ? list.getStore().getSource() : list.getStore(),
length, toInsert,
oldRecords, newRecord, oldRecord, i;
if (success) {
if (me.getMergeData()) {
oldRecords = store.getData();
toInsert = [];
length = newRecords.length;
for (i = 0; i < length; i++) {
newRecord = newRecords[i];
oldRecord = oldRecords.getByKey(newRecord.getId());
if (oldRecord) {
oldRecord.set(newRecord.getData());
}
else {
toInsert.push(newRecord);
}
}
store.insert(0, toInsert);
}
else {
store.loadRecords(newRecords);
}
me.setLastUpdated(new Date());
}
me.setState('loaded');
list.fireEvent('latestfetched', me, toInsert || newRecords);
if (me.getAutoSnapBack()) {
me.snapBack(true);
}
}
}
})
Thanks in advance
Since this post, instead of being a question, was a bug report with a possible solution, it has been posted to Ext JS 7.x Community Forums\Ext JS 7.x Bugs.
The above solution, that overwrites the plugin where source store is needed, works if anyone comes across the same issue.

At the same time, two identical elements can not be selected in dropDownList

Hello i am have two kendo ui drodDownList:
kendo-drop-down-list(
ng-model = 'vm.firstList'
k-data-source='vm.filterData'
k-data-text-field='"title"'
k-data-value-field='"name"'
k-value-primitive='true'
k-filter='"contains"'
k-on-change='vm.onChange($event)'
)
and
kendo-drop-down-list(
ng-model = 'vm.secondList'
k-data-source='vm.filterData'
k-data-text-field='"title"'
k-data-value-field='"name"'
k-value-primitive='true'
k-filter='"contains"'
k-on-change='vm.onChange($event)'
)
it is data source:
this.filterData = [
{ name: 'Brown', title: 'Soier' },
{ name: 'Maks', title: 'Inkl' },
{ name: 'Lint', title: 'Baks' },
{ name: 'Hover', title: 'Niyou' }
]
they have same data source, and i am want when choosing item in first dd then remove this item from other dd (and likewise for the second). At the same time, two identical elements can not be selected.
my solution:
in first dd add:
k-on-change='vm.onFirstSelect(kendoEvent)'
k-data-source='vm.firstFilterElements'
for second dd:
k-on-change='vm.onSecondSelect(kendoEvent)'
k-data-source='vm.secondFilterElements'
in controller add:
this.filterElements = [
{ name: 'Brown', title: 'Soier' },
{ name: 'Maks', title: 'Inkl' },
{ name: 'Lint', title: 'Baks' },
{ name: 'Hover', title: 'Niyou' }
]
this.firstFilterElements = this.filterElements;
this.secondFilterElements = this.filterElements;
onFirstSelect(e) {
this.secondFilterElements = this.filterByItem(e);
}
onSecondSelect(e) {
this.firstFilterElements = this.filterByItem(e);
}
filterByItem (e) {
return this.filterElements.filter(function (el) {
return el.name !== e.sender.dataItem(e.item)
[e.sender.options.dataValueField];
});
}
if someone can optimize it i will be glad)

Only continue loop after method has finished

I want the following code to run synchronous.
Each inquirer.prompt() needs to run after the other.
This is my code now:
_.forEach(diff.wrongVersion, (dependency) => {
choices = [ 'project version: ' + dependency.projectVersion, 'layer version: ' + dependency.layerVersion];
inquirer.prompt({
type: 'list',
name: 'dependencies',
message: 'Choose which version to use for ' + dependency.name,
choices
});
});
Could anybody help me with this?
I thought this could be done with Promise but I have no idea how.
You can use Array#reduce or lodash#reduce to achieve this type of sequential prompt.
diff.wrongVersion.reduce((promise, dependency) => promise.then(result =>
inquirer.prompt({
type: 'list',
name: dependency.name,
message: `Choose which version to use for: ${dependency.name}`,
choices: [
`project version: ${dependency.projectVersion}`,
`layer version: ${dependency.layerVersion}`
]
})
.then(answer => Object.assign(result, answer))
), Promise.resolve({})).then(result => {
console.log(result);
});
// =========== Mocking Inquirer Module =====================
var inquirer = {
prompt: function(question) {
var choices = question.choices
.map((v, i) => `[${i+1}] - ${v}`)
.join('\n');
var message = `${question.message}\n${choices}`;
var result = {};
var answer;
return new Promise((resolve, reject) => {
do {
answer = parseInt(window.prompt(message));
} while(
isNaN(answer) ||
answer < 1 ||
answer > choices.length ||
answer === null
);
if(answer === null) {
reject();
} else {
result[question.name] = question.choices[answer-1];
resolve(result);
}
});
}
};
const diff = {
wrongVersion: [
{
projectVersion: 'pv-1.0',
layerVersion: 'lv-1.0',
name: 'Dep-A'
},
{
projectVersion: 'pv-1.0',
layerVersion: 'lv-1.0',
name: 'Dep-B'
},
{
projectVersion: 'pv-1.0',
layerVersion: 'lv-1.0',
name: 'Dep-C'
},
{
projectVersion: 'pv-1.0',
layerVersion: 'lv-1.0',
name: 'Dep-D'
},
{
projectVersion: 'pv-1.0',
layerVersion: 'lv-1.0',
name: 'Dep-E'
},
]
};
diff.wrongVersion.reduce((promise, dependency) => promise.then(result =>
inquirer.prompt({
type: 'list',
name: dependency.name,
message: `Choose which version to use for: ${dependency.name}`,
choices: [
`project version: ${dependency.projectVersion}`,
`layer version: ${dependency.layerVersion}`
]
})
.then(answer => Object.assign(result, answer))
), Promise.resolve({})).then(result => {
console.log(result);
});
If I understand you correctly, you need the following principle:
var inquirer = {};
inquirer.prompt = function(object) {
return new Promise(function(resolve, reject) {
setTimeout(function() { // <-- here I emulate async execution
console.log('object ==> ', object);
resolve();
}, 1000);
});
}
var diff = {
wrongVersion: [{
projectVersion: 0,
layerVersion: 0,
name: 'zero'
}, {
projectVersion: 1,
layerVersion: 1,
name: 'one'
}, {
projectVersion: 2,
layerVersion: 2,
name: 'two'
}, {
projectVersion: 3,
layerVersion: 3,
name: 'three'
}]
}
var iterator = 0;
function callPrompt() {
var dependency = diff.wrongVersion[iterator];
var choices = ['project version: ' + dependency.projectVersion, 'layer version: ' + dependency.layerVersion];
inquirer.prompt({
type: 'list',
name: 'dependencies',
message: 'Choose which version to use for ' + dependency.name,
choices: choices
}).then(function() {
iterator++;
if (diff.wrongVersion[iterator]) {
callPrompt();
}
});
};
callPrompt();
Example on jsfiddle (pay attention on concole) - https://jsfiddle.net/regwtew1/2/

ExtJs Grid Auto Refresh using REST Proxy

I have tried to refresh the Grid every 5 or 10 seconds which is using REST Proxy, but the grid is not getting refreshed more than once. Please find the code which we have tried.
Ext.define('App.Store.DeviceStore', {
extend: 'Ext.data.Store',
requires: [
'Ext.data.proxy.Ajax',
'Ext.data.reader.Json'
],
constructor: function(cfg) {
var me = this;
cfg = cfg || {};
me.callParent([Ext.apply({
storeId: 'app.store.DeviceStore',
model: 'App.model.DeviceModel',
activeRefreshTask:false,
pageSize: 5,
autoLoad: {
pageSize: 5
}
}, cfg)]);
},listeners:{
'load':function(store,records,successful,operation){
if(successful === true && store.activeRefreshTask === false){
var task = {
identifyId: 'deviceListStore',
run: function() {
if (App.app._currentPage == 'devicesform') {
store.reload();
} else {
Ext.TaskManager.stop(this);
}
},
interval: '10000'
}
Ext.TaskManager.start(task);
store.activeRefreshTask = true;
}
}
}
});
The model for the above store is
Ext.define('App.model.DeviceModel', {
extend: 'Ext.data.Model',
requires: [
'Ext.data.field.String'
],
proxy:{
type:'rest',
reader: {
type: 'json',
rootProperty: 'data',
totalProperty:'total'
},
useDefaultXhrHeader: false,
headers:{'Content-Type':'application/json'},
api: {
read: 'url given gere'
}
},
fields: [
{
type: 'string',
name: 'id'
},
{
type: 'string',
name: 'name'
},
{
type: 'string',
name: 'desc'
},
{
type: 'string',
name: 'ipAddr'
}
]
});
I have found the issue , You have passed the interval as string in place lo number.
just change to interval: '10000' to inteval: 10000 and your taskrunner will runs fine.
var runner = new Ext.util.TaskRunner(),
updateStore , task;
updateStore = function() {
if (App.app._currentPage == 'devicesform') {
store.load();
} else {
Ext.TaskManager.stop(this);
}
};
task = runner.start({
run: updateStore ,
interval: 1000
});
probably your store.reload is sending again the same params on the request, so with a request that not change nothing changes.

Extjs localstore method set

I am not able to update record in localStorage by id. I get the exception :
Uncaught TypeError: Cannot read property 'type' of undefined WebStorage.js:391Ext.define.getIds WebStorage.js:391Ext.define.update WebStorage.js:190Ext.define.runOperation Batch.js?_dc=1423751003307:251Ext.define.start Batch.js?_dc=1423751003307:178Ext.define.batch Proxy.js?_dc=1423751002203:456Ext.define.sync AbstractStore.js?_dc=1423751002173:810Ext.define.afterEdit AbstractStore.js?_dc=1423751002173:906Ext.define.callStore Model.js?_dc=1423751003310:1814Ext.define.afterEdit Model.js?_dc=1423751003310:1773Ext.define.set Model.js?_dc=1423751003310:1175(anonymous function) Main.js?_dc=1423751002786:26(anonymous function) VM3763:6wrap
My model is simple:
Ext.define('AM.model.Points', {
extend: 'Ext.data.Model',
idProperty: {
name: 'UUID',
type: String,
isUnique: true
},
fields: [
{
name: 'NO',
type: "string"
},
{
name: 'Y',
type: "int"
},
{
name: 'ROW',
type: 'int'
},
{
name: 'SEAT',
type: 'string'
},
{
name: 'PROCEEDED',
type: 'int'
},
{
name: 'X',
type: "int"
},
{
name: "CurrentPlace",
type: "int",
defaultValue: 0
}
],
});
My controller class init function:
init: function(){
// метод getStore контроллера возвращает экземпляр хранилища,
// если он уже создан - или создаёт его
console.log('Main controller init function()');
var changingImage = Ext.create('Ext.Img', {
src: '/is-bin/intershop.static/WFS/EnterpriseOrg-MainChannel-Site/ProductStore/ru_RU/kzch.jpg',
renderTo: Ext.get('canv1')
});
Ext.get('canv1').on('click', function(eventObj, elRef) {
var index = Ext.StoreMgr.lookup("LocalStore").findExact('UUID',AM.util.Utilities.CurrentPlace);
var rec = Ext.StoreMgr.lookup("LocalStore").getAt(index);
console.log('Ext.StoreMgr.lookup("LocalStore") ' + Ext.StoreMgr.lookup("LocalStore"));
console.log('index' + index);
console.log('rec' + rec);
var uuid = rec.get('UUID');
console.log('uuid is: '+uuid);
**rec.set('X', window.event.offsetX);**
});
The logic is that I click on canvas and pass X coordinate of the click to method on click. I retrieve model from store by previously saved id to update it. But I cant update record. What should be done? Version 4.2.1 Thanx in advance.

Resources