Set grid id dynamicly from DB extjs6 - extjs

I have a grid.
This grid gets data from postgres table.
This table uses 4 users.
The problem is if user B create and a row in a table with id:5, user A would not know it. So when user A create a row he should know what is the last id or create an a row and get back rows id.
When i press "Add" button in a grid , extjs send "create" command to server, server retruns "success: true" and number of "id" new created row in a postgres table.
Id like to show and use this 'id' in my grid.
For example if i add a row, and get "id: 19' from server, i have to create 19 row in and grid. When i`d like to edit this row, etxjs have to send to server update with 'id:19'.
How to make it?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="/extjs/ext-6.2.0/build/classic/theme-classic/resources/theme-classic-all.css" />
<script type="text/javascript" src="/extjs/ext-6.2.0/build/ext.js"></script>
<script type="text/javascript" src="/extjs/ext-6.2.0/build/ext-all.js"></script>
<script type="text/javascript">
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: 'date', type: 'date', dateFormat: 'Y-m-d'}
// {
// name: 'time',
// type: 'date',
// dateFormat: 'H:i'
// },
]
});
// var occupationStore = Ext.create('Ext.data.Store', {
// fields: ['time'],
// data: [{
// time: 'CEO'
// },
// {
// time: 'Vicepresident'
// },
// {
// time: 'Marketing manager'
// },
// ]
// });
Ext.onReady(function() {
// Создаем store
var store = Ext.create('Ext.data.Store', {
autoLoad: true,
autoSync: true,
model: 'Users',
proxy: {
type: 'ajax',
url: 's.rakov.php',
api: {
create: 's.rakov.php?action=create',
read: 's.rakov.php?action=read',
update: 's.rakov.php?action=update',
destroy: 's.rakov.php?action=delete'
},
reader: {
type: 'json',
rootProperty: 'data'
},
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 grid = Ext.create('Ext.grid.Panel', {
renderTo: document.body,
//plugins: [rowEditing],
// Редактирование
plugins: {
ptype: 'cellediting',
clicksToEdit: 1
},
listeners: {
edit: function() {
}
},
width: '99,3%',
height: 330,
frame: true,
title: 'Users',
store: store,
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',
//name: 'timeStart1',
//fieldLabel: 'Time In',
anchor: '100%',
allowBlank: false
}
}
},
{
header: 'Время начала',
width: 120,
// sortable: true,
dataIndex: 'time_start',
//format: 'H:i',
// Нужно для верного отображеия времени после редактирования в таблице
renderer: Ext.util.Format.dateRenderer('H:i'),
editor: {
completeOnEnter: false,
field: {
xtype: 'timefield',
format: 'H:i',
//name: 'timeStart1',
//fieldLabel: 'Time In',
minValue: '8:00',
maxValue: '20:00',
increment: 30,
anchor: '100%',
//allowBlank: false
}
}
},
{
header: 'Результат',
width: '30%',
// sortable: true,
dataIndex: 'task_result',
editor: {
completeOnEnter: false,
field: {
xtype: 'textfield',
//name: 'timeStart1',
//fieldLabel: 'Time In',
//anchor: '100%',
allowBlank: false
}
}
},
{
header: 'Время конца',
width: 120,
// sortable: true,
dataIndex: 'time_end',
//format: 'H:i',
// Нужно для верного отображеия времени после редактирования в таблице
renderer: Ext.util.Format.dateRenderer('H:i'),
editor: {
completeOnEnter: false,
field: {
xtype: 'timefield',
format: 'H:i',
//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'
},
// {
// header: 'Тип задачи',
// width: 120,
// // sortable: true,
// dataIndex: 'task_type',
// editor: {
// completeOnEnter: false,
// field: {
// xtype: 'combobox',
// //name: 'timeStart1',
// //fieldLabel: 'Time In',
// anchor: '100%',
// allowBlank: false
// }
// }
// }
],
dockedItems: [{
xtype: 'toolbar',
items: [{
text: 'Add',
iconCls: 'icon-add',
handler: function() {
// Создаем новую задачу
// Для корректной работы с БД нужно задать ID новой строки, равной +1 от последней ID из таблицы.
var rec = new Users();
//console.log (x);("rec data= " + rec.id + " -- " + rec.data.id);
var idArr = grid.store.data.items;
var idValue = [];
for (var i = 0; i < idArr.length; i++) {
idValue.push(idArr[i].id);
}
idValue.sort(function(a, b) {
return a - b;
});
var maxId = idValue[idValue.length - 1];
console.log(maxId);
//rec.id = maxId + 1;
//rec.data.id = maxId + 1;
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.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);
//store.add(rac);
//grid.getView().refresh();
// rowEditing.startEdit(rec, 0);
}
}, '-', {
itemId: 'delete',
text: 'Delete',
iconCls: 'icon-delete',
disabled: false,
handler: function() {
var selection = grid.getView().getSelectionModel().getSelection()[0];
if (confirm('Вы действительно хотите удалить задачу №' + selection.id + " ?")) {
// Удлаяем
if (selection) {
store.remove(selection);
}
}
}
}]
}]
});
});
</script>
</head>
<body>
<div id="gridDiv"></div>
</body>
</html>

You have to provide the new id to the client in the update response.
I have made a fiddle for you: https://fiddle.sencha.com/#view/editor&fiddle/226o
In short, when the client sends to the server the create request with the body e.g.
{"updateData":[{"task":"Test", "id":"ext-task-46"},{"task":"Test 2", id: "ext-task-47"}]}
(updateData being your writer's rootProperty), the server has to answer with
{"success":true,"data":[{"task:"Test","id":5},{"task:"Test 2","id":6}]
or, shorter, with
{"success":true,"data":[{"id":5},{"id":6}]
(data being your reader's rootProperty). The matching between the submitted and the returned records for the id update is by position; and all other fields can be updated as well.
The server can thus return to the client any changes that have been enforced by the server on the submitted records; except for the fact that certain records could not be created.

Related

Sencha Offline Proxy

facing issue in Sencha offline proxy , when json received 100 records
offline proxy only add 50 records add in store here is my simple code
response.responseText [my ajax response], it returns reocords set
var data = Ext.decode(response.responseText);
for (var c=0; c < data.length; c++){
console.log(c);
var itemrecord = Ext.create('Inertia.model.InstallingCompany');
itemrecord.set(data[c]);
Ext.getStore('InstallingCompanies-offline').add(itemrecord);
}
console.log(c);
console.log(Ext.getStore('InstallingCompanies-offline').data.length);
For this you can use direct store.loadData() method of store.
In this FIDDLE, I have create a demo using gridpanel and Ext.data.Store. I hope this FIDDLE will help you or guide you to achieve your requirement.
Code Snippet
Ext.define('ForumThread', {
extend: 'Ext.data.Model',
fields: [
'title', 'forumtitle', 'forumid', 'username', {
name: 'replycount',
type: 'int'
}, {
name: 'lastpost',
mapping: 'lastpost',
type: 'date',
dateFormat: 'timestamp'
},
'lastposter', 'excerpt', 'threadid'
],
idProperty: 'threadid'
});
Ext.create('Ext.data.Store', {
storeId: 'topicsStore',
model: 'ForumThread'
});
function renderTopic(value, p, record) {
return Ext.String.format(
'{0}',
value,
record.data.forumtitle,
record.getId(),
record.data.forumid
);
}
Ext.create('Ext.grid.Panel', {
height: window.innerHeight,
title: 'Example of Store loadData() with GRID and Ajax Request',
renderTo: Ext.getBody(),
store: Ext.data.StoreManager.lookup('topicsStore'),
loadMask: true,
columns: [{
xtype: 'rownumberer',
width: 35,
sortable: false
}, {
tdCls: 'x-grid-cell-topic',
text: "Topic",
dataIndex: 'title',
flex: 1,
renderer: renderTopic,
sortable: true,
groupable: false,
cellWrap: true
}, {
text: "Author",
dataIndex: 'username',
flex: 0.5,
sortable: true,
groupable: false
}, {
text: "Replies",
dataIndex: 'replycount',
align: 'center',
width: 90,
sortable: false
}, {
id: 'last',
text: "Last Post",
dataIndex: 'lastpost',
flex: 0.5,
renderer: Ext.util.Format.dateRenderer('n/j/Y g:i A'),
sortable: true,
groupable: false
}],
listeners: {
afterrender: function (cmp) {
var store = Ext.data.StoreManager.lookup('topicsStore'),
store1;
cmp.getEl().mask('Please wait..!');
Ext.Ajax.request({
url: 'topics.json',
success: function (data) {
var response = Ext.decode(data.responseText);
store.loadData(response.topics);
cmp.getEl().unmask();
//Add data using store.add() method in Store
store1 = Ext.create('Ext.data.Store', {
model: 'ForumThread'
});
response.topics.forEach(function (item) {
store1.add(item);
})
console.log(`total count of store1 data is ${store1.getCount()}`);
}
});
}
}
});

Extjs 6 How to sum dates inside summaryType?

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.
}

How to render date in right timezone extjs 6?

Im new in extjs.
I have a grid.
When i add new row script automaticaly puts there time time_start = Ext.Date.format(new Date(), '2008-01-01\\TH:i:s'); and its work fine, extjs automaticaly sends to server time.
But when i look at a grid there is a time +3 hours.
For example if my local time is 23.00.00, extjs send to server "2008-01-01T23:00:00", but shows in a grid "02:00".
But it must show "23:00".
Its add +3 hours to a cell view, whats wrong ?
Ext.require(['Ext.data.*', 'Ext.grid.*']);
// Создаем model
Ext.define('Users', {
extend: 'Ext.data.Model',
//idProperty: 'id',
fields: [{
name: 'id',
type: 'int'
}
]
});
Ext.onReady(function() {
// Создаем store
var store = Ext.create('Ext.data.Store', {
autoLoad: true,
autoSync: true,
model: 'Users',
proxy: {
type: 'ajax',
url: 'server.php',
api: {
create: 'server.php?action=create',
read: 'server.php?action=read',
update: 'server.php?action=update',
destroy: 'server.php?action=delete'
},
reader: {
type: 'json',
rootProperty: 'data'
},
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 grid = Ext.create('Ext.grid.Panel', {
renderTo: document.body,
//plugins: [rowEditing],
// Редактирование
plugins: {
ptype: 'cellediting',
clicksToEdit: 1
},
listeners: {
edit: function() {
}
},
width: 1000,
height: 330,
frame: true,
title: 'Users',
store: store,
iconCls: 'icon-user',
columns: [{
text: 'id',
width: 50,
sortable: true,
dataIndex: 'id',
renderer: function(v, meta, rec) {
return rec.phantom ? '' : v;
}
},
{
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: 120,
// sortable: true,
dataIndex: 'time_start',
//format: 'H:i',
// Нужно для верного отображеия времени после редактирования в таблице
renderer: Ext.util.Format.dateRenderer('H:i'),
editor: {
completeOnEnter: false,
field: {
xtype: 'timefield',
format: 'H:i',
//name: 'timeStart1',
//fieldLabel: 'Time In',
minValue: '8:00',
maxValue: '20:00',
increment: 30,
anchor: '100%',
allowBlank: false
}
}
}
],
dockedItems: [{
xtype: 'toolbar',
items: [{
text: 'Add',
iconCls: 'icon-add',
handler: function() {
// Создаем новую задачу
// Для корректной работы с БД нужно задать ID новой строки, равной +1 от последней ID из таблицы.
var rec = new Users();
//console.log (x);("rec data= " + rec.id + " -- " + rec.data.id);
var idArr = grid.store.data.items;
var idValue = [];
for (var i = 0; i < idArr.length; i++) {
idValue.push(idArr[i].id);
}
idValue.sort(function(a, b) {
return a - b;
});
var maxId = idValue[idValue.length - 1];
console.log(maxId);
rec.id = maxId + 1;
rec.data.id = maxId + 1;
rec.date = Ext.Date.format(new Date(), 'Y-m-d');
rec.data.date = Ext.Date.format(new Date(), 'Y-m-d');
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);
//store.add(rac);
//grid.getView().refresh();
// rowEditing.startEdit(rec, 0);
}
}, '-', {
itemId: 'delete',
text: 'Delete',
iconCls: 'icon-delete',
disabled: false,
handler: function() {
var selection = grid.getView().getSelectionModel().getSelection()[0];
if (confirm('Вы действительно хотите удалить задачу №' + selection.id + " ?")) {
// Удлаяем
if (selection) {
store.remove(selection);
}
}
}
}]
}]
});
});
You have to write renderer on column
renderer : function(value){
var serverDate = new Date(value{2015-12-04T10:39:22});
var newFrmDate = Ext.Date.format(serverDate,'m-d-Y h:i A');
return newFrmDate;
}
you can specify your own date time format.

How to send date in format Y-m-d Ext JS 6

I have a grid. When I add new row script automatically puts there date in format "Y-m-d" and its work fine, Ext JS automatically sends to server date in format "2017-06-24" ("Y-m-d"). But when I update this date, Ext JS send to server date in format 2017-06-24T00:00:00.
Whats wrong?
Help me send to server "2017-06-24" date ("Y-m-d"), after updating.
Ext.require(['Ext.data.*', 'Ext.grid.*']);
// Создаем model
Ext.define('Users', {
extend: 'Ext.data.Model',
//idProperty: 'id',
fields: [{
name: 'id',
type: 'int'
}
]
});
Ext.onReady(function() {
// Создаем store
var store = Ext.create('Ext.data.Store', {
autoLoad: true,
autoSync: true,
model: 'Users',
proxy: {
type: 'ajax',
url: 'server.php',
api: {
create: 'server.php?action=create',
read: 'server.php?action=read',
update: 'server.php?action=update',
destroy: 'server.php?action=delete'
},
reader: {
type: 'json',
rootProperty: 'data'
},
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 grid = Ext.create('Ext.grid.Panel', {
renderTo: document.body,
//plugins: [rowEditing],
// Редактирование
plugins: {
ptype: 'cellediting',
clicksToEdit: 1
},
listeners: {
edit: function() {
}
},
width: 1000,
height: 330,
frame: true,
title: 'Users',
store: store,
iconCls: 'icon-user',
columns: [{
text: 'id',
width: 50,
sortable: true,
dataIndex: 'id',
renderer: function(v, meta, rec) {
return rec.phantom ? '' : v;
}
},
{
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: 120,
// sortable: true,
dataIndex: 'time_start',
//format: 'H:i',
// Нужно для верного отображеия времени после редактирования в таблице
renderer: Ext.util.Format.dateRenderer('H:i'),
editor: {
completeOnEnter: false,
field: {
xtype: 'timefield',
format: 'H:i',
//name: 'timeStart1',
//fieldLabel: 'Time In',
minValue: '8:00',
maxValue: '20:00',
increment: 30,
anchor: '100%',
allowBlank: false
}
}
}
],
dockedItems: [{
xtype: 'toolbar',
items: [{
text: 'Add',
iconCls: 'icon-add',
handler: function() {
// Создаем новую задачу
// Для корректной работы с БД нужно задать ID новой строки, равной +1 от последней ID из таблицы.
var rec = new Users();
//console.log (x);("rec data= " + rec.id + " -- " + rec.data.id);
var idArr = grid.store.data.items;
var idValue = [];
for (var i = 0; i < idArr.length; i++) {
idValue.push(idArr[i].id);
}
idValue.sort(function(a, b) {
return a - b;
});
var maxId = idValue[idValue.length - 1];
console.log(maxId);
rec.id = maxId + 1;
rec.data.id = maxId + 1;
rec.date = Ext.Date.format(new Date(), 'Y-m-d');
rec.data.date = Ext.Date.format(new Date(), 'Y-m-d');
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);
//store.add(rac);
//grid.getView().refresh();
// rowEditing.startEdit(rec, 0);
}
}, '-', {
itemId: 'delete',
text: 'Delete',
iconCls: 'icon-delete',
disabled: false,
handler: function() {
var selection = grid.getView().getSelectionModel().getSelection()[0];
if (confirm('Вы действительно хотите удалить задачу №' + selection.id + " ?")) {
// Удлаяем
if (selection) {
store.remove(selection);
}
}
}
}]
}]
});
});
The datefield xtype has a submitFormat config where you can specify the date format string to be submitted to the server.
https://docs.sencha.com/extjs/6.2.0/classic/Ext.form.field.Date.html#cfg-submitFormat
Update: As Selmaril mentioned in the comment, this goes into the section where you define a datefield.
{
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',
submitFormat: 'd/m/Y'
allowBlank: false
}
}
}
You are working with a Model here. On that model, you have a fields config where you can define which fields contain which data ype, and in case of date, in which format it should be submitted to the server.
fields:[{
name: 'id',
type: 'int'
},{
name: 'date',
type:'date',
dateFormat:'Y-m-d'
}]
Furthermore, I see some other red flags in your code:
Don't use record.date = or record.data.date = to set the date on the record.
Don't format the date using Date.format() unless absolutely necessary. Internally, you should always work with javascript dates, not strings. Use a xtype:'gridcolumn' in your grid with the appropriate format (e.g. format:'d/m/Y') for display.
So, for instance, when programmatically updating an existing record or creating a new grid row or a new record outside store, use record.set('date', new Date()); or store.add({date:new Date()}) or Ext.create('Users',{date: new Date()}).
I use dateWriteFormat: "Y-m-d" in my models and it works perfectly to send US-classic dates to my postgres backend.

MultiSelect in extjs Combobox

I'm trying to multiselect in combobox of the Extjs, After I select the Items , the tpl index is rendered , want to render the value that's the displayfield selected when away out from the cell, how can I be able to Achieve this.
here's the code
function run() {
var myStore=Ext.create('Ext.data.Store', {
storeId: 'simpsonsStore',
fields: ['busname', 'time', 'typebus',],
pageSize:2,
proxy: {
type: 'memory',
enablePaging: true
},
data: [{
busname: 'ABCD',
time: '15:30:00',
typebus: 'AC Volvo',
}, {
busname: 'aaa',
time: '13:30:00',
typebus: 'Seater',
},{
busname: 'AAAA',
time: '18:30:00',
typebus: 'Sleeper',
},{
busname: 'ABCD',
time: '19:30:00',
typebus: 'AC Volvo',
},]
});
Ext.create('Ext.grid.Panel', {
xtype :'gridpanel',
itemId:'busTimegrid',
pageSize:1,
title: 'BUS DEATILS',
mapperId:'getBusTime',
store: Ext.data.StoreManager.lookup('simpsonsStore'),
columns: [{
header: 'Bus Name',
dataIndex: 'busname',
editor: 'textfield'
}, {
text: 'Bus Time',
dataIndex: 'time',
xtype: 'gridcolumn',
renderer: function (value) {
if (value instanceof Date)
         return Ext.util.Format.date(value, 'H:i:s');
     else
     return value;
},
flex: 1,
editor: {
xtype: 'timefield',
format: 'H:i:s',
allowBlank: true,
maskRe: /[0-9,:]/,
listeners: {
beforeselect: function(timefield, record) {
var grid = timefield.up('grid');
if(grid.store.find('time', record.data.disp) != -1) {
Ext.Msg.alert("Bus time already exist.");
return false;
}
}
}
}
}, {
header: 'Bus TYpe',
dataIndex: 'typebus',
editable:true,
renderer: function (value) {
if (Ext.isNumber(value)) {
var store = this.getEditor().getStore();
return store.findRecord('id', value).get('name');
}
return value;
},
editor: {
xtype: 'combo',
displayField: 'name',
valueField: 'id',
editable:true,
forceSelection:true,
multiSelect: true,
displayTpl: '<tpl for=".">' +
'{name}' +
'<tpl if="xindex < xcount">, </tpl>' +
'</tpl>',
store: Ext.create('Ext.data.Store', {
fields: ['id', 'name'],
data: [{
id: 1,
name: 'AC Volvo'
}, {
id: 2,
name: 'Seater'
}, {
id: 3,
name: 'Sleeper'
}]
})
}
}],
selModel: 'cellmodel',
plugins: {
ptype: 'cellediting',
clicksToEdit: 1,
},
listners: [{
fn: 'onUsernamefieldBlur',
event: 'blur',
delegate: 'busname'
}],
onUsernamefieldBlur: function (textfield, e, eOpts) {
if (textfield.getValue() === '') {
Ext.Msg.alert("Busname can't be empty");
textfield.setFocus(true);
}
},
height: 200,
width: 400,
dockedItems: [{
xtype: 'pagingtoolbar',
store: myStore, // same store GridPanel is using
dock: 'bottom',
displayInfo: true
}],
renderTo: Ext.getBody()
});
var gridRow = myStore.getModifiedRecords();
Ext.each(gridRows, function (gridRow) {
var dirtyInd = myStore.indexOf(gridRow);
var newTime = new Date(store.getAt(dirtyInd).data.time);
},
myStore.each(function (record, idx) {
var newT = new Date(record.get('time'));
if (Ext.Date.diff(newTime, newT,Ext.Date.SECOND)=== 0)
{
samebustime = true;
}
}));
if(samebustime){
Ext.Msg.alert('Warning','Same time occured')
}
}
Fiddle
I have done some modification to your original source code. You might like it or not. But in this code you get what you have asked for. I am not sure if that is exactly what you want.
Ext.application({
name: 'Fiddle',
launch: function () {
run();
window.show();
}
});
function run() {
var myStore = Ext.create('Ext.data.Store', {
storeId: 'simpsonsStore',
fields: ['busname', 'time', 'typebus',],
pageSize: 2,
proxy: {
type: 'memory',
enablePaging: true
},
data: [{
busname: 'ABCD',
time: '15:30:00',
typebus: 'AC Volvo',
}, {
busname: 'aaa',
time: '13:30:00',
typebus: 'Seater',
}, {
busname: 'AAAA',
time: '18:30:00',
typebus: 'Sleeper',
}, {
busname: 'ABCD',
time: '19:30:00',
typebus: 'AC Volvo',
},]
});
var typebusStore = Ext.create('Ext.data.Store', {
storeId: 'typeBusStore',
fields: ['id', 'name'],
data: [{
id: 1,
name: 'AC Volvo'
}, {
id: 2,
name: 'Seater'
}, {
id: 3,
name: 'Sleeper'
}]
})
Ext.create('Ext.grid.Panel', {
xtype: 'gridpanel',
itemId: 'busTimegrid',
pageSize: 1,
title: 'BUS DEATILS',
mapperId: 'getBusTime',
store: Ext.data.StoreManager.lookup('simpsonsStore'),
columns: [{
header: 'Bus Name',
dataIndex: 'busname',
editor: 'textfield'
}, {
text: 'Bus Time',
dataIndex: 'time',
xtype: 'gridcolumn',
renderer: function (value) {
if (value instanceof Date)
return Ext.util.Format.date(value, 'H:i:s');
else
return value;
},
flex: 1,
editor: {
xtype: 'timefield',
format: 'H:i:s',
allowBlank: true,
maskRe: /[0-9,:]/,
listeners: {
beforeselect: function (timefield, record) {
var grid = timefield.up('grid');
if (grid.store.find('time', record.data.disp) != -1) {
Ext.Msg.alert("Bus time already exist.");
return false;
}
}
}
}
}, {
header: 'Bus TYpe',
dataIndex: 'typebus',
editable: true,
renderer: function (value, md, record) {
var retValue = Array();
if (Ext.isArray(value)) {
Ext.each(value, function(id) {
retValue.push(Ext.data.StoreManager.lookup('typeBusStore').findRecord('id', id).get('name'));
});
}
if (retValue.length > 0) {
return retValue.join(", ");
}
return value;
},
editor: {
xtype: 'combo',
displayField: 'name',
valueField: 'id',
editable: true,
forceSelection: true,
multiSelect: true,
displayTpl: '<tpl for=".">' +
'{name}' +
'<tpl if="xindex < xcount">, </tpl>' +
'</tpl>',
store: typebusStore
}
}],
selModel: 'cellmodel',
plugins: {
ptype: 'cellediting',
clicksToEdit: 1,
},
listners: [{
fn: 'onUsernamefieldBlur',
event: 'blur',
delegate: 'busname'
}],
onUsernamefieldBlur: function (textfield, e, eOpts) {
if (textfield.getValue() === '') {
Ext.Msg.alert("Busname can't be empty");
textfield.setFocus(true);
}
},
height: 200,
width: 400,
dockedItems: [{
xtype: 'pagingtoolbar',
store: myStore, // same store GridPanel is using
dock: 'bottom',
displayInfo: true
}],
renderTo: Ext.getBody()
});
var gridRows = myStore.getModifiedRecords();
console.log(gridRows)
var samebustime = false;
Ext.each(gridRows, function (gridRow) {
var dirtyInd = myStore.indexOf(gridRow);
var newTime = new Date(store.getAt(dirtyInd).data.time);
myStore.each(function (record, idx) {
var newT = new Date(record.get('time'));
if (Ext.Date.diff(newTime, newT, Ext.Date.SECOND) === 0) {
samebustime = true;
}
})
});
if (samebustime) {
Ext.Msg.alert('Warning', 'Same time occured')
}
}
Fiddle

Resources