Related
Conditionally i need to disable the toolbar button based on the grid json data, if status not "New"
tbarItems.push(
"->",
{
text: t('import'),
id: 'masterdata_import',
iconCls: 'pimcore_icon_import',
disabled: false,
scale: 'small',
handler: this.importJob.bind(this),
dataIndex: 'status',
renderer: function (value, rowIndex, record) {
if (value !== 'New') {
tbar.disable();
}
},
}
);
https://i.stack.imgur.com/8hVmN.png
Any idea how to do this?
Thanks
i made an example at sencha fiddle. Take a look:
https://fiddle.sencha.com/#view/editor&fiddle/2qs3
You can bind disabled parameter to parameter from viewModel, while viewModel can be updated e.g when data in store changed (event datachanged is fired).
getLayout: function () {
if (this.layout == null) {
var itemsPerPage = pimcore.helpers.grid.getDefaultPageSize(70);
this.store = pimcore.helpers.grid.buildDefaultStore(
'/admin/referenceapp/import/get-import-files?processed=0',
['date','time','sourceFileLocation','sizeReadable','status','jobReference'],
itemsPerPage,
{autoLoad: true}
);
// only when used in element context
if(this.inElementContext) {
var proxy = this.store.getProxy();
proxy.extraParams["folderDate"] = this.element.folderDate;
} else {
}
this.pagingtoolbar = pimcore.helpers.grid.buildDefaultPagingToolbar(this.store);
var tbarItems = [];
tbarItems.push(
"->",
{
text: t('import'),
id: 'masterdata_import',
iconCls: 'pimcore_icon_import',
//disabled: false,
scale: 'small',
bind: {
disabled: "{one_different_than_new}"
},
handler: this.importJob.bind(this)
}
);
var tbar = Ext.create('Ext.Toolbar', {
cls: 'main-toolbar',
items: tbarItems
});
var columns = [
{text: t("date"), sortable: true, dataIndex: 'date', flex: 100, filter: 'date'},
{text: t("time"), sortable: true, dataIndex: 'time', flex: 100, filter: 'string'},
{text: t("source_file_location"), sortable: true, dataIndex: 'sourceFileLocation', filter: 'string', flex: 200},
{text: t("size"), sortable: true, dataIndex: 'sizeReadable', filter: 'string', flex: 200},
{text: t("status"), sortable: true, dataIndex: 'status', filter: 'string', flex: 200},
{text: t("jobReference"), sortable: true, dataIndex: 'jobReference', filter: 'string', flex: 200},
];
columns.push({
xtype: 'actioncolumn',
menuText: t('delete'),
width: 40,
dataIndex: 'status',
renderer: function (value, rowIndex, record) {
if (value !== 'New') {
rowIndex.tdCls = 'importnotdelete'
}
},
disabled:false,
items: [{
tooltip: t('icon_delete_import'),
icon: "/bundles/pimcoreadmin/img/flat-color-icons/delete.svg",
handler: this.removeVersion.bind(this)
}]
});
var plugins = [];
this.grid = new Ext.grid.GridPanel({
frame: false,
title: t('plugin_referenceapp_masterdataname_importview'),
store: this.store,
region: "center",
columns: columns,
columnLines: true,
bbar: Ext.create('Ext.PagingToolbar', {
pageSize: 0,
store: this.store,
displayInfo: true,
limit:0
}),
tbar: tbar,
stripeRows: true,
autoScroll: true,
plugins: plugins,
viewConfig: {
forceFit: true
},
viewModel: {
data: {
"one_different_than_new": false
}
},
//listeners: {
// afterrender : function(model) {
// console.log(model.store.data.items);
//
// for(i = 0; i<model.store.data.items.length; i++){
//
// if (model.store.data.items[i].status !== 'New') {
// tbar.disable();
// //console.log('test');
// }
//
// else{
// //console.log('no new');
// }
// }
//
// }
//}
});
this.grid.on("rowclick", this.showDetail.bind(this));
this.detailView = new Ext.Panel({
region: "east",
minWidth: 350,
width: 350,
split: true,
layout: "fit"
});
var layoutConf = {
items: [this.grid, this.detailView],
layout: "border",
//closable: !this.inElementContext
};
if(!this.inElementContext) {
//layoutConf["title"] = t('product_versions');
}
this.layout = new Ext.Panel(layoutConf);
this.layout.on("activate", function () {
this.store.load();
var check = function () {
var isDifferentThanNew = false;
this.store.each(function (r) {
if (r.get('status') != 'New') {
isDifferentThanNew = true;
}
});
this.grid.getViewModel().set('one_different_than_new', isDifferentThanNew);
}
// Listen on datachanged and update
this.store.on('update', function (s) {
check();
});
this.store.on('datachanged', function (s) {
check();
});
check();
}.bind(this));
}
return this.layout;
},
I have a table in postgresql.
There is a field type of "interval" and its name is 'time_duration'.
postgresql send to my extjs grid json like:
[{"id":"18","time_start":"2008-01-01 19:00:00+03","time_end":"2008-01-01 19:01:00+03","task":"test","task_type":"","date":"2017-07-03 00:00:00+03","task_result":"asdasd","username":"test_rakov","time_duration":"00:01:00"},{"id":"20","time_start":"2008-01-01 19:00:00+03","time_end":"2008-01-01 20:00:00+03","task":"asdasdasdasdsdf asdas","task_type":"","date":"2017-07-03 00:00:00+03","task_result":"asdasd","username":"test_rakov","time_duration":"01:00:00"},{"id":"21","time_start":"2008-01-01 12:00:00+03","time_end":"2008-01-01 14:00:00+03","task":"asdasdasdasdasd","task_type":"","date":"2017-07-03 00:00:00+03","task_result":"asdasd","username":"test_rakov","time_duration":"02:00:00"},{"id":"19","time_start":"2008-01-01 18:21:51+03","time_end":"2008-01-01 18:22:00+03","task":"asdasd","task_type":"","date":"2017-07-02 00:00:00+03","task_result":"","username":"test_rakov","time_duration":"00:00:09"}]
Id like to use Ext.grid.feature.GroupingSummary
When i use summaryType: 'sum' with dataIndex: 'time_duration' its return dates like a string and also add 0 at the start.
The summaryType gets in value parametr string "0Tue Jul 04 2017 00:01:00 GMT+0300 (RTZ 2 (зима))Tue Jul 04 2017 01:00:00 GMT+0300 (RTZ 2 (зима))Tue Jul 04 2017 02:00:00 GMT+0300 (RTZ 2 (зима))". So the dates from json are joined.
Id like to sum them. For example "time_duration":"01:00:00"+ "time_duration":"01:00:00" = "02:00:00".How to do it in right way? Mb change fields type in postgresl to something else? Help me please.
Here is my code:
Ext.require(['Ext.data.*', 'Ext.grid.*']);
// Создаем model
Ext.define('Users', {
extend: 'Ext.data.Model',
//idProperty: 'id',
//idProperty: 'id',
fields: [{
name: 'id',
type: 'int',
//mapping: 'id'
},
{
name:'time_duration',
type:'date',
dateFormat:'H:i:s'
}
]
});
Ext.onReady(function() {
// Создаем store
var store = Ext.create('Ext.data.Store', {
autoLoad: true,
autoSync: true,
model: 'Users',
// Задает параметр для фильтрации подтаблиц myGroupingFeature
groupField: 'date',
groupDir: 'DESC',
proxy: {
type: 'ajax',
url: 'test_rakov.php',
api: {
create: 'test_rakov.php?action=create',
read: 'test_rakov.php?action=read',
update: 'test_rakov.php?action=update',
destroy: 'test_rakov.php?action=delete'
},
reader: {
type: 'json',
// Данные получаемые от сервера, которые мы затем обрабатываем в таблице
rootProperty: 'dataFromServer'
},
writer: {
type: 'json',
encode: true,
rootProperty: 'dataUpdate',
allowSingle: false,
writeAllFields: true,
//root:'records'
},
actionMethods: {
create: 'GET',
read: 'GET',
update: 'GET',
destroy: 'GET'
}
},
listeners: {
write: function(store, operation) {
var record = operation.getRecords()[0],
name = Ext.String.capitalize(operation.action),
verb;
if (name == 'Destroy') {
verb = 'Destroyed';
} else {
verb = name + 'd';
}
//Ext.example.msg(name, Ext.String.format("{0} user: {1}", verb, record.getId()));
}
}
});
// Отображает подтаблицы в таблице
var myGroupingFeature = Ext.create('Ext.grid.feature.GroupingSummary', {
groupHeaderTpl: '{columnName}: {name} ({rows.length} задач)',
hideGroupedHeader: false,
// Сворачивать по умолчанию или нет
startCollapsed: false
});
// Данные для выбора типа задачи
var storeCombo = new Ext.data.SimpleStore({
fields: ["value"],
data: [
["Анализ регистраций в WebAdmin"],
["AP -Анализ работы сервера"],
["AP -Составление config файлов"],
["Анализ заявок в СРМ"],
["Встречи"],
["Консультация сотрудников ОТП"],
["Перекур"],
["Программирование"],
["Почтовая переписка"],
["Другое"],
]
});
// Выбор типа задачи
var combo = new Ext.form.ComboBox({
store: storeCombo,
editable: false,
valueField: "value",
displayField: "value",
});
var grid = Ext.create('Ext.grid.Panel', {
columnLines: true,
renderTo: document.body,
// Редактирование таблицы
plugins: {
ptype: 'cellediting',
clicksToEdit: 1
},
listeners: {
edit: function() {
}
},
width: '99,3%',
// Высота на весь экран
autoHeight: true,
frame: true,
title: 'Users',
store: store,
// Отображает подтаблицы в таблице
features: [myGroupingFeature],
iconCls: 'icon-user',
columns: [{
text: 'id',
width: '2%',
sortable: true,
dataIndex: 'id',
renderer: function(v, meta, rec) {
return rec.phantom ? '' : v;
}
},
{
header: 'Задача',
width: '30%',
// sortable: true,
dataIndex: 'task',
editor: {
completeOnEnter: false,
field: {
xtype: 'textfield',
enableKeyEvents: true,
listeners: {
keydown: function(field, e) {
if (e.getKey() == e.ENTER) {
field = grid.getSelectionModel().getCurrentPosition().rowIdx;
grid.getView().focusRow(field);
}
}
},
//name: 'timeStart1',
//fieldLabel: 'Time In',
anchor: '100%',
allowBlank: false
}
}
},
{
header: 'Время начала',
width: '5%',
// sortable: true,
dataIndex: 'time_start',
//format: 'H:i',
// Нужно для верного отображеия времени после редактирования в таблице
renderer: Ext.util.Format.dateRenderer('H:i'),
editor: {
completeOnEnter: true,
field: {
xtype: 'timefield',
format: 'Hi',
//name: 'timeStart1',
//fieldLabel: 'Time In',
//minValue: '8:00',
//maxValue: '20:00',
increment: 720,
//anchor: '100%',
//allowBlank: false
}
}
},
{
header: 'Результат',
width: '30%',
// sortable: true,
dataIndex: 'task_result',
editor: {
completeOnEnter: false,
field: {
xtype: 'textfield',
enableKeyEvents: true,
listeners: {
keydown: function(field, e) {
if (e.getKey() == e.ENTER) {
field = grid.getSelectionModel().getCurrentPosition().rowIdx;
grid.getView().focusRow(field);
}
}
},
//name: 'timeStart1',
//fieldLabel: 'Time In',
//anchor: '100%',
allowBlank: false
}
}
},
{
header: 'Время конца',
width: '5%',
// sortable: true,
dataIndex: 'time_end',
//format: 'H:i',
// Нужно для верного отображеия времени после редактирования в таблице
renderer: Ext.util.Format.dateRenderer('H:i'),
editor: {
completeOnEnter: false,
field: {
xtype: 'timefield',
format: 'Hi',
enableKeyEvents: true,
listeners: {
keydown: function(field, e) {
if (e.getKey() == e.ENTER) {
field = grid.getSelectionModel().getCurrentPosition().rowIdx;
grid.getView().focusRow(field);
}
}
},
//name: 'timeStart1',
//fieldLabel: 'Time In',
minValue: '8:00',
maxValue: '20:00',
increment: 30,
anchor: '100%',
allowBlank: false
}
}
},
{
header: 'Дата',
width: 70,
// sortable: true,
dataIndex: 'date',
renderer: Ext.util.Format.dateRenderer('d/m/Y'),
editor: {
completeOnEnter: false,
field: {
xtype: 'datefield',
dateFormat: 'd/m/Y',
allowBlank: false
}
}
},
{
header: 'Длительность',
width: 60,
// sortable: true,
dataIndex: 'time_duration',
//xtype: 'datecolumn',
renderer: Ext.util.Format.dateRenderer('H:i:s'),
summaryType: 'sum',
//summaryType: function(f1){ console.log(f1); return;}
//summaryRenderer: Ext.util.Format.dateRenderer('H:i')
summaryRenderer: function(value, summaryData, dataIndex){
//console.log("val1= " + value);
var val2 = value.substring(1);
//console.log("val2= " + x);
var x = Ext.Date.format(val2, 'H:i:s');
//console.log (x);
//console.log( Ext.Date.format(val2, 'H:i:s'));
//console.log("tmpDate= " + tmpDate);
//return Ext.String.format('{0} student{1}', value, value !== 1 ? 's': '');
}
},
{
header: 'Тип задачи',
width: '20%',
dataIndex: 'task_type',
editor: combo
}
],
dockedItems: [{
xtype: 'toolbar',
items: [{
text: 'Добавить задачу',
iconCls: 'icon-add',
handler: function() {
// Создаем новую задачу
// Для корректной работы с БД нужно задать ID новой строки, равной +1 от последней ID из таблицы.
var rec = new Users();
//rec.date = Ext.Date.format(new Date(), 'Y-m-d\\T00:00:00');
//rec.data.date = Ext.Date.format(new Date(), 'Y-m-d\\T00:00:00');
rec.set('date', new Date());
rec.set('time_start', new Date(),'H:i:s');
//rec.time_start = Ext.Date.format(new Date(), '2008-01-01\\TH:i:s');
//rec.data.time_start = Ext.Date.format(new Date(), '2008-01-01\\TH:i:s');
store.insert(0, rec);
}
}, '-', {
itemId: 'delete',
text: 'Удалить задачу',
iconCls: 'icon-delete',
disabled: false,
handler: function() {
var selection = grid.getView().getSelectionModel().getSelection()[0];
if (confirm('Вы действительно хотите удалить задачу №' + selection.id + " ?")) {
// Удлаяем
if (selection) {
store.remove(selection);
}
}
}
}]
}]
});
});
You can pass summaryType a function:
.... Alternatively, the summaryType can be a function definition. If
this is the case, the function is called with two parameters: an array
of records, and an array of field values to calculate the summary
value.
http://docs.sencha.com/extjs/6.2.1/classic/Ext.grid.feature.GroupingSummary.html
So instead of:
summaryType: 'sum'
You can use:
summaryType: function(records){
// do your logic and return a value.
}
I am very new to extjs, and I saw this excellent post:
dynamic url inside a extjs table dont work
I was wondering if there is a way to enable checkbox functionality on the subtable?
I tried making slight modifications to the sample, but I can't find a way to have the checkboxes clickable and capture the events associated with it.
Please see the modified code below. Is it possible to have a clickable checkbox inside a Subtable?
Thanks in advance!
// SALVAGUARDAS -- added Approved field
Ext.define('Salvaguardas', {
extend: 'Ext.data.Model',
fields: ['Approved', 'id_amenaza', 'tipo', 'modo', 'codigo', 'denominacion', 'eficiencia', ]
});
//SALVAGUARDAS
var salvaguardaStore = Ext.create('Ext.data.Store', {
model: 'Salvaguardas',
data: [
{Approved: true, id_amenaza: 1, tipo: 'Correctiva', modo: 'Correctiva', codigo: 'corr-01', denominacion: 'correctiva 1', eficiencia: 'MB' }
]
});
//GRIDPANEL
Ext.create('Ext.grid.Panel', {
renderTo: 'example-grid',
store: amenazaStore,
//width: 748,
//height: 598,
title: '<bean:write name="informesAGRForm" property="nombreActivo"/>',
plugins: [{
ptype: "subtable",
headerWidth: 24,
listeners: {
'rowdblclick': function(grid, rowIndex, columnIndex, e){
// Get the Record, this is the point at which rowIndex references a
// record's index in the grid's store.
var record = grid.getStore().getAt(rowIndex);
// Get field name
var fieldName = grid.getColumnModel().getDataIndex(columnIndex);
var data = record.get(fieldName);
alert(data);
}
},
columns: [{
//text: 'Approved',
//dataIndex: 'Approved',
//hidden: true,
//width: 100
xtype: 'checkcolumn',
header: 'Approved',
dataIndex: 'Approved',
width: 85,
listeners: {
checkChange: function ()
{
console.log('checkChange');
}
}
}, {
text: 'id_amenaza',
dataIndex: 'id_amenaza',
hidden: true,
width: 100
}, {
width: 100,
text: 'id_salvaguarda',
dataIndex: 'id_salvaguarda'
},
{
text: 'denominacion',
dataIndex: 'denominacion',
width: 100
},{
text: 'descripcion',
dataIndex: 'descripcion',
width: 100
},{
text: 'eficacia',
dataIndex: 'eficacia',
width: 100
},
],
getAssociatedRecords: function (record) {
var result = Ext.Array.filter(
salvaguardaStore.data.items,
function (r) {
return r.get('id_amenaza') == record.get('id');
});
return result;
}
}],
listeners: {
rowdblclick: function (view, record, tr, columnIndex, e) {
console.log('rowdblclick');
var cell = e.getTarget('.x-grid-subtable-cell');
if (!cell) {
return;
}
var row = Ext.get(cell).up('tr');
var tbody = row.up('tbody');
var rowIdx = tbody.query('tr', true).indexOf(row.dom);
//var records = view.up('grid').getPlugin('subtable').getAssociatedRecords(record);
var records = view.up('grid').plugins[0].getAssociatedRecords(record);
var subRecord = records[rowIdx];
console.log('rowdblclick: ' + rowIdx + ' - ' + subRecord);
},
rowclick: function (view, record, tr, columnIndex, e) {
console.log('rowclick');
var cell = e.getTarget('.x-grid-subtable-cell');
if (!cell) {
return;
}
var row = Ext.get(cell).up('tr');
var tbody = row.up('tbody');
var rowIdx = tbody.query('tr', true).indexOf(row.dom);
//var records = view.up('grid').getPlugin('subtable').getAssociatedRecords(record);
var records = view.up('grid').plugins[0].getAssociatedRecords(record);
var subRecord = records[rowIdx];
console.log('rowclick: ' + rowIdx + ' - ' + subRecord);
}
},
collapsible: false,
animCollapse: false,
columns: [
{
text: 'ID',
hidden: true,
hideable: false,
dataIndex: 'id'
},
{
text: 'Codigo',
width: 50,
sortable: true,
hideable: false,
dataIndex: 'codigo'
},
{
text: 'Denominación',
width: 150,
dataIndex: 'denominacion',
},
{
text: ' Autenticidad',
flex: 1,
dataIndex: 'a_riesgo'
},
{
text: 'Confidencialidad',
flex: 1,
dataIndex: 'c_riesgo'
},
{
text: 'Integridad',
flex: 1,
dataIndex: 'i_riesgo'
},
{
text: 'Disponibilidad',
flex: 1,
dataIndex: 'd_riesgo'
},
{
text: 'Trazabilidad',
flex: 1,
dataIndex: 't_riesgo'
},
{
text: 'Total',
flex: 1,
dataIndex: 'total_riesgo'
}]
});
Is it possible to make cell editable in ext js 3.4 gridpanel?
If yes please reply me how?
This is the code I tried,
var fm = Ext.form;
var grid = new Ext.grid.EditorGridPanel({
height: 500,
renderTo: Ext.getBody(),
width: 800,
loadMask: false,
viewConfig: {
emptyText: 'No data to display'
},
selModel: checkboxselection,
tbar: mainGridToolbar,
clicksToEdit: 1,
store: cartStore,
listeners: {
afteredit: function(o) {
var pos = o.record.get('POS');
var quantity = o.value;
}
},
columns: [
checkboxselection,
{
header: "quantity",
align: 'right',
dataIndex: 'QUANTITY',
sortable: true,
editor: new fm.TextField({
allowBlank: false
})
}
]
});
Edit
You are missing the plugin line... (I never heard of a EditorGridPanel, but I am on 4.x and may be mistaken at this point)
plugins: new Ext.ux.grid.RowEditor({saveText: 'Update'});
Origin
Use the Row Editor Plugin for these. You can specify for each cell if it should be editable or not.
You should really take look at the examples that comes along with the library! These lines can be found under ext-3.4.0\examples\grid\row-editor.js
Ext.onReady(function(){
Ext.QuickTips.init();
var Employee = Ext.data.Record.create([{
name: 'name',
type: 'string'
}, {
name: 'email',
type: 'string'
}, {
name: 'start',
type: 'date',
dateFormat: 'n/j/Y'
},{
name: 'salary',
type: 'float'
},{
name: 'active',
type: 'bool'
}]);
// hideous function to generate employee data
var genData = function(){
var data = [];
var s = new Date(2007, 0, 1);
var now = new Date(), i = -1;
while(s.getTime() < now.getTime()){
var ecount = Ext.ux.getRandomInt(0, 3);
for(var i = 0; i < ecount; i++){
var name = Ext.ux.generateName();
data.push({
start : s.clearTime(true).add(Date.DAY, Ext.ux.getRandomInt(0, 27)),
name : name,
email: name.toLowerCase().replace(' ', '.') + '#exttest.com',
active: true,
salary: Math.floor(Ext.ux.getRandomInt(35000, 85000)/1000)*1000
});
}
s = s.add(Date.MONTH, 1);
}
return data;
}
var store = new Ext.data.GroupingStore({
reader: new Ext.data.JsonReader({fields: Employee}),
data: genData(),
sortInfo: {field: 'start', direction: 'ASC'}
});
var editor = new Ext.ux.grid.RowEditor({
saveText: 'Update'
});
var grid = new Ext.grid.GridPanel({
store: store,
width: 600,
region:'center',
margins: '0 5 5 5',
autoExpandColumn: 'name',
plugins: [editor],
view: new Ext.grid.GroupingView({
markDirty: false
}),
tbar: [{
iconCls: 'icon-user-add',
text: 'Add Employee',
handler: function(){
var e = new Employee({
name: 'New Guy',
email: 'new#exttest.com',
start: (new Date()).clearTime(),
salary: 50000,
active: true
});
editor.stopEditing();
store.insert(0, e);
grid.getView().refresh();
grid.getSelectionModel().selectRow(0);
editor.startEditing(0);
}
},{
ref: '../removeBtn',
iconCls: 'icon-user-delete',
text: 'Remove Employee',
disabled: true,
handler: function(){
editor.stopEditing();
var s = grid.getSelectionModel().getSelections();
for(var i = 0, r; r = s[i]; i++){
store.remove(r);
}
}
}],
columns: [
new Ext.grid.RowNumberer(),
{
id: 'name',
header: 'First Name',
dataIndex: 'name',
width: 220,
sortable: true,
editor: {
xtype: 'textfield',
allowBlank: false
}
},{
header: 'Email',
dataIndex: 'email',
width: 150,
sortable: true,
editor: {
xtype: 'textfield',
allowBlank: false,
vtype: 'email'
}
},{
xtype: 'datecolumn',
header: 'Start Date',
dataIndex: 'start',
format: 'm/d/Y',
width: 100,
sortable: true,
groupRenderer: Ext.util.Format.dateRenderer('M y'),
editor: {
xtype: 'datefield',
allowBlank: false,
minValue: '01/01/2006',
minText: 'Can\'t have a start date before the company existed!',
maxValue: (new Date()).format('m/d/Y')
}
},{
xtype: 'numbercolumn',
header: 'Salary',
dataIndex: 'salary',
format: '$0,0.00',
width: 100,
sortable: true,
editor: {
xtype: 'numberfield',
allowBlank: false,
minValue: 1,
maxValue: 150000
}
},{
xtype: 'booleancolumn',
header: 'Active',
dataIndex: 'active',
align: 'center',
width: 50,
trueText: 'Yes',
falseText: 'No',
editor: {
xtype: 'checkbox'
}
}]
});
var cstore = new Ext.data.JsonStore({
fields:['month', 'employees', 'salary'],
data:[],
refreshData: function(){
var o = {}, data = [];
var s = new Date(2007, 0, 1);
var now = new Date(), i = -1;
while(s.getTime() < now.getTime()){
var m = {
month: s.format('M y'),
employees: 0,
salary: 0,
index: ++i
}
data.push(m);
o[m.month] = m;
s = s.add(Date.MONTH, 1);
}
store.each(function(r){
var m = o[r.data.start.format('M y')];
for(var i = m.index, mo; mo = data[i]; i++){
mo.employees += 10000;
mo.salary += r.data.salary;
}
});
this.loadData(data);
}
});
cstore.refreshData();
store.on('add', cstore.refreshData, cstore);
store.on('remove', cstore.refreshData, cstore);
store.on('update', cstore.refreshData, cstore);
var chart = new Ext.Panel({
width:600,
height:200,
layout:'fit',
margins: '5 5 0',
region: 'north',
split: true,
minHeight: 100,
maxHeight: 500,
items: {
xtype: 'columnchart',
store: cstore,
url:'../../resources/charts.swf',
xField: 'month',
yAxis: new Ext.chart.NumericAxis({
displayName: 'Employees',
labelRenderer : Ext.util.Format.numberRenderer('0,0')
}),
tipRenderer : function(chart, record, index, series){
if(series.yField == 'salary'){
return Ext.util.Format.number(record.data.salary, '$0,0') + ' total salary in ' + record.data.month;
}else{
return Ext.util.Format.number(Math.floor(record.data.employees/10000), '0,0') + ' total employees in ' + record.data.month;
}
},
// style chart so it looks pretty
chartStyle: {
padding: 10,
animationEnabled: true,
font: {
name: 'Tahoma',
color: 0x444444,
size: 11
},
dataTip: {
padding: 5,
border: {
color: 0x99bbe8,
size:1
},
background: {
color: 0xDAE7F6,
alpha: .9
},
font: {
name: 'Tahoma',
color: 0x15428B,
size: 10,
bold: true
}
},
xAxis: {
color: 0x69aBc8,
majorTicks: {color: 0x69aBc8, length: 4},
minorTicks: {color: 0x69aBc8, length: 2},
majorGridLines: {size: 1, color: 0xeeeeee}
},
yAxis: {
color: 0x69aBc8,
majorTicks: {color: 0x69aBc8, length: 4},
minorTicks: {color: 0x69aBc8, length: 2},
majorGridLines: {size: 1, color: 0xdfe8f6}
}
},
series: [{
type: 'column',
displayName: 'Salary',
yField: 'salary',
style: {
image:'../chart/bar.gif',
mode: 'stretch',
color:0x99BBE8
}
}]
}
});
var layout = new Ext.Panel({
title: 'Employee Salary by Month',
layout: 'border',
layoutConfig: {
columns: 1
},
width:600,
height: 600,
items: [chart, grid]
});
layout.render(Ext.getBody());
grid.getSelectionModel().on('selectionchange', function(sm){
grid.removeBtn.setDisabled(sm.getCount() < 1);
});
});
I am using extjs grid, and I have a jQuery timer, which will call RenderGrid function every 20 seconds. I want to show mask for grid each timer tick. Please advise.
function RenderGrid(dataObj) {
var jasonContent = JSON.parse(dataObj)
if (document.getElementById('panel').innerHTML != '') {
document.getElementById('panel').innerHTML = '';
}
var myData = {
records: jasonContent
};
var fields = [
{ name: 'Position_ID', mapping: 'Position_ID' },
{ name: 'PriorityCount', mapping: 'PriorityCount' },
{ name: 'MyCheckBox', mapping: 'MyCheckBox' },
{ name: 'Veh_Plateno', mapping: 'Veh_Plateno' },
{ name: 'Drv_Firstname', mapping: 'Drv_Firstname' },
{ name: 'GPSTimeAsString', mapping: 'GPSTimeAsString' },
{ name: 'Speed', mapping: 'Speed' },
{ name: 'SubFleet_Name', mapping: 'SubFleet_Name' }
];
var gridStore = new Ext.data.JsonStore({
fields: fields,
data: myData,
root: 'records'
});
var cols = [
{ id: 'Position_ID', header: "Position_ID", width: 160, sortable: true, dataIndex: 'Position_ID', hidden: true, hideable: false },
{ header: "", width: 30, sortable: false, dataIndex: 'MyCheckBox', renderer: renderCheckBox, hideable: false, menuDisabled: true },
{ header: "", width: 30, sortable: false, dataIndex: 'PriorityCount', renderer: renderIcon, hideable: false, menuDisabled: true },
{ header: "Veh_Plateno", width: 100, sortable: true, dataIndex: 'Veh_Plateno' },
{ header: "Drv_Firstname", width: 100, sortable: true, dataIndex: 'Drv_Firstname' },
{ header: "GPSTime", width: 100, sortable: true, dataIndex: 'GPSTimeAsString' },
{ header: "Speed", width: 100, sortable: true, dataIndex: 'Speed' },
{ header: "SubFleet_Name", width: 100, sortable: true, dataIndex: 'SubFleet_Name' }
];
gridStore.setDefaultSort('Veh_Plateno', 'asc');
var grid = new Ext.grid.GridPanel({
ddGroup: 'gridDDGroup',
store: gridStore,
renderTo: 'panel',
columns: cols,
enableDragDrop: true,
stripeRows: true,
pageSize:25,
header: false,
loadMask: true,
autoExpandColumn: 'Position_ID',
width: 900,
height: 325,
region: 'west',
title: 'Data Grid',
selModel: new Ext.grid.RowSelectionModel({ singleSelect: false }),
listeners: {
'rowdblclick': function (grid, rowIndex, e) {
var rec = grid.getStore().getAt(rowIndex);
var columnName = grid.getColumnModel().getDataIndex(2);
Ext.MessageBox.alert('', rec.get(columnName));
// do something
}
}
});
//grid.getEl().mask();
//grid.store.reload();
//grid.getEl().unmask();
//gridStore.load({ params: { start:0, limit: 25} });
/// grid.loadMask.show();
grid = null;
cols = null;
fields = null;
gridStore = null;
myData = null;
}
thaks man this approch working fine with me but now my browser is hanging it seems, grid object will enter in infinite loop this all my script code, please prvide me example with timer if you can :
var grid = null;
function RenderPositionsGrid(dataObj) {
var jasonContent = JSON.parse(dataObj)
var myData = {
records: jasonContent
};
if (grid == null) {
var fields = [
{ name: 'Position_ID', mapping: 'Position_ID' },
{ name: 'PriorityCount', mapping: 'PriorityCount' },
{ name: 'MyCheckBox', mapping: 'MyCheckBox' },
{ name: 'Veh_Plateno', mapping: 'Veh_Plateno' },
{ name: 'Drv_Firstname', mapping: 'Drv_Firstname' },
{ name: 'GPSTimeAsString', mapping: 'GPSTimeAsString' },
{ name: 'Speed', mapping: 'Speed' },
{ name: 'SubFleet_Name', mapping: 'SubFleet_Name' }
];
var gridStore = new Ext.data.JsonStore({
fields: fields,
data: myData,
root: 'records'
});
var cols = [
{ id: 'Position_ID', header: "Position_ID", width: 160, sortable: true, dataIndex: 'Position_ID', hidden: true, hideable: false },
{ header: "", width: 30, sortable: false, dataIndex: 'MyCheckBox', renderer: renderCheckBox, hideable: false, menuDisabled: true },
{ header: "", width: 30, sortable: false, dataIndex: 'PriorityCount', renderer: renderIcon, hideable: false, menuDisabled: true },
{ header: "Veh_Plateno", width: 100, sortable: true, dataIndex: 'Veh_Plateno' },
{ header: "Drv_Firstname", width: 100, sortable: true, dataIndex: 'Drv_Firstname' },
{ header: "GPSTime", width: 100, sortable: true, dataIndex: 'GPSTimeAsString' },
{ header: "Speed", width: 100, sortable: true, dataIndex: 'Speed' },
{ header: "SubFleet_Name", width: 100, sortable: true, dataIndex: 'SubFleet_Name' }
];
gridStore.setDefaultSort('Veh_Plateno', 'asc');
grid = new Ext.grid.GridPanel({
ddGroup: 'gridDDGroup',
store: gridStore,
renderTo: 'panel',
columns: cols,
enableDragDrop: true,
stripeRows: true,
pageSize: 25,
header: false,
loadMask: true,
autoExpandColumn: 'Position_ID',
width: 900,
height: 325,
region: 'west',
title: 'Data Grid',
selModel: new Ext.grid.RowSelectionModel({ singleSelect: false }),
listeners: {
'rowdblclick': function (grid, rowIndex, e) {
var rec = grid.getStore().getAt(rowIndex);
var columnName = grid.getColumnModel().getDataIndex(2);
Ext.MessageBox.alert('', rec.get(columnName));
// do something
}
}
});
}
else {
grid.store.loadData(myData);
}
}
function renderIcon(val) {
if (val) {
val = '../images/grid/icon_warning.png';
return "<img class=Blink src='" + val + "'>";
}
}
function renderCheckBox(val, cell, record) {
var x = '<input onclick="alert(' + cell.id + ')" type="checkbox" name="mycheckbox" />';
//var x = '<input type="checkbox" name="mycheckbox" />';
return x;
}
function renderDate(date) {
alert(date);
return date.format("d.m.Y");
}
function BindGridView() {
Data.GetVehiclePositions(onSuccess, onFail, null);
}
function onSuccess(result) {
RenderPositionsGrid(result);
var timeout = 4000; var timer;
timer = $.timer(timeout, function () { BindGridView(result); });
}
function onFail(result) {
alert("fail");
}
function blink() {
$('.Blink').delay(100).fadeTo(200, 0.5).delay(200).fadeTo(100, 1, blink);
}
Ext.onReady(function () {
BindGridView();
blink();
});
You could use
var myMask = new Ext.LoadMask(grid.getEl(), {msg:"Please wait..."});
myMask.show();
But I find your approach kind of weird, seems like the only thing changing every 20 seconds is your dada, your store, column model, grid never changed.
Can you just do a simple loadData(Object data, [Boolean append] ) in your timer handler? the API is here