Related
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 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.
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.
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
I have a grid with actionColumn and when I click on edit icon it should call the other form(already available) with data populated in to fields from database so that the user can edit and save it. I am new to Extjs please help
I tried with the following code but its not working:
myForm.getForm().load({
url: '/.RetrieveRecords',
params: { id: id},
method: 'POST',
waitMsg: 'Loading data...'
Here is my form1:
Ext.application({
name : 'extjs.com',
launch : function()
{
var myForm = Ext.create('Ext.form.Panel',
{
title: 'Registration Form',
id: 'form',
Layout: 'border',
border: 'true',
padding: 10,
bodyPadding: 30,
renderTo: Ext.getBody(),
defaultType: 'textfield',
items :
[
{fieldLabel: 'First Name', name: 'firstname', id: 'firstname',allowBlank: false, minLength: 2, maxLength:25, regex:/^[a-zA-Z]/},
{fieldLabel: 'Last Name', name: 'lastname', id: 'lastname', allowBlank: false, minLength: 2, maxLength:25},
{fieldLabel: 'Email', name: 'email', id: 'email',allowBlank: false, vType: 'email', msgTarget:'under'},
{fieldLabel: 'Mobile Number', name: 'mobilenumber', id: 'mobilenumber',allowBlank: false, minLength: 10, maxLength:10, regex:/^[7-9][0-9]{9}$/, regexText:"Invalid mobile number",msgTarget:"under"},
{
xtype: 'datefield',
fieldLabel: 'DOB'+'<span style="color:red;font-weight:bold" data-qtip="Required">*</span>',
name: 'dob',
id:'dob',
allowBlank: false,
value: '2 4 1978',
format: 'd m Y',
// value: new Date(),
maxValue: new Date(),
msgTarget:'side'
},
{
xtype:'radiogroup',
fieldLabel: 'Gender',
defaultType: 'radiofield',
anchor: '22.5%',
id:'gender1',
defaults:
{
flex: 1
},
layout: 'hbox',
items: [
{
boxLabel: 'Male',
name: 'rb',
inputValue: 'M',
checked: true
},
{
boxLabel: 'Female',
name: 'rb',
inputValue: 'F',
}]
},
{
xtype:'checkboxgroup',
fieldLabel: 'Known Technologies',
anchor: '50%',
id:'tech',
columns: 3,
vertical: true,
items:
[
{boxLabel: 'java', name: 'cb',inputValue: 'java', x:20, checked: true},
{boxLabel: 'c++', name: 'cb',inputValue: 'c++', x:20, checked: true},
{boxLabel: 'jsp', name: 'cb',inputValue: 'jsp', x:20, checked: false},
{boxLabel: 'javascript', name: 'cb',inputValue: 'javascript', checked: false},
{boxLabel: 'hadoop', name: 'cb',inputValue: 'hadoop', checked: false},
{boxLabel: 'spring', name: 'cb',inputValue: 'spring', checked: false}
]
},
{
xtype:'textarea',
fieldLabel: 'Hobbies',
name:'hobby',
id:'hobby',
anchor:'100%'
// padding:5
},
{
xtype:'fieldset',
title: 'Address',
collapsible:false,
items:
[
{
xtype:'combobox',
displayField:'cname',
valueField:'cid',
fieldLabel:'country'+'<span style =color:red;data-qtip="Required">*</span>',
queryMode:'local',
msgTarget: 'under',
name:'country',
id: 'country',
store: Ext.create('Ext.data.Store',{
fields:['cid','cname']
}),
listeners:
{
afterrender:function()
{
Ext.Ajax.request({
url:'./getRecords',
success: function(response)
{
var jarray = [];
jarray = Ext.JSON.decode(response.responseText);
Ext.getCmp('country').getStore().loadData(jarray);
},
failure: function(response)
{
Ext.Msg.alert('failed' + response.status);
}
});
},
change: function(a,b,c)
{
var countryID1 = Ext.getCmp('country').getValue();
Ext.Ajax.request({
url:'./getStates',
params:{countryID:countryID1},
success: function(response)
{
//alert(JSON.stringify(response));
var jarray = [];
jarray=Ext.JSON.decode(response.responseText);
Ext.getCmp('state').getStore().loadData(jarray);
},
failure: function(response)
{
Ext.Msg.alert('Failed' + response.status);
}
});
}
}
},
{
xtype:'combobox',
displayField:'sname',
valueField:'sid',
fieldLabel:'State',
name:'state',
id:'state',
queryMode:'local',
msgTarget: 'under',
store: Ext.create('Ext.data.Store',{
fields:['sid','sname']
}),
listeners:
{
change: function(a,b,c)
{
var StateID = Ext.getCmp('state').getValue();
Ext.Ajax.request({
url:'./getCities',
params: {StateID1:StateID},
success: function(response)
{
var jarray = [];
jarray = Ext.JSON.decode(response.responseText);
Ext.getCmp('city').getStore().loadData(jarray);
},
failure: function(response)
{
Ext.Msg.alert('failed' + response.status);
}
});
}
}
},
{
xtype:'combobox',
displayField:'cname',
valueField:'cid',
fieldLabel:'City',
name:'city',
id:'city',
queryMode:'local',
msgTarget: 'under',
store: Ext.create('Ext.data.Store',{
fields:['cid','cname','sid']
})
},
{
xtype:'textfield',
displayField:'PincodeName',
valueField:'pincodeID',
fieldLabel:'Pin-code',
id:'pincode',
allowBlank: false,
maskRe: /[0-9\-]/,
regex: /^[0-9]{3}(\-)?[0-9]{3}$/,
regexText:"invalid pincode",
msgTarget: 'under'
}
]
},
{
xtype:'fieldset',
title:'Education',
collasible: false,
items:
[
{
xtype:'combobox',
displayField:'QualificationName',
valueField:'QualificationID',
fieldLabel:'Qualification',
id:'qualification',
name:'qualification',
queryMode:'local',
msgTarget:'side',
store: Ext.create('Ext.data.Store',{
fields:['QualificationID','QualificationName'],
data:
[
{"QualificationID":"1","QualificationName":"B.Tech"},
{"QualificationID":"2","QualificationName":"Diploma"},
{"QualificationID":"3","QualificationName":"Advanced Diploma"}
]
}),
listeners:
{
change: function()
{
Ext.getCmp('DepartmentID').setVisible(true);
Ext.getCmp('PercentageID').setVisible(true);
}
}
},
{
xtype:'textfield',
name:'department',
id:'DepartmentID',
displayField:'Department',
valueField:'DeptID',
fieldLabel:'Department',
allowBlank: false,
hidden:true,
msgTarget: 'under'
},
{
xtype:'textfield',
name: 'percentage',
id: 'PercentageID',
displayField:'Percentage',
valueField:'PercentageID',
fieldLabel:'Percentage',
msgTarget: 'under',
regex:/^-?[0-9]{0,2}(\.[0-9]{1,2})?%?$|^-?(100)(\.[0]{1,2})?%?$/,
regexText:"invalid percentage",
hidden:true
}
]
}
],
buttons:
[
{text:'Submit',
handler: function()
{
var mail = Ext.getCmp('email').getValue();
var mnumber = Ext.getCmp('mobilenumber').getValue();
var gender = Ext.getCmp('gender1').getChecked()[0].inputValue;
var selection = [];
selection = Ext.getCmp('tech').getChecked();
var selections = "";
for(var i=0;i<selection.length;i++)
{
selections += selection[i].inputValue + " ";
}
var add = Ext.getCmp('country').getRawValue()+","+Ext.getCmp('state').getRawValue()+","+Ext.getCmp('city').getRawValue()+","+Ext.getCmp('pincode').getValue();
var edu = Ext.getCmp('qualification').getRawValue()+","+Ext.getCmp('DepartmentID').getValue()+","+Ext.getCmp('PercentageID').getValue();
var dob = Ext.getCmp('dob').getRawValue();
var hobby = Ext.getCmp('hobby').getValue();
var fname = Ext.getCmp('firstname').getValue();
var lname = Ext.getCmp('lastname').getValue();
//alert(this.up('form'));
var form = this.up('form').getForm();
if(form.isValid())
{
Ext.Ajax.request
({
url:'./Save_Records',
method: 'POST',
params: {mail1:mail,mnumber1:mnumber,gender2:gender,selections1:selections,add1:add,edu1:edu,dob1:dob,hobby1:hobby,fname1:fname,lname1:lname},
success: function(response)
{
Ext.Msg.alert("success" + response.status);
},
failure: function(response)
{
Ext.Msg.alert("failed" + response.status);
}
});
}
else
{
alert("Please fill in the form");
}
}
},
{
text:'Reset',
handler: function()
{
this.up('form').getForm().reset();
Ext.Ajax.request
({
url:'index.jsp',
method: 'POST',
success: function(response)
{
Ext.Msg.alert('Success' + " " + response.status);
},
failure: function(response)
{
Ext.Msg.alert('Failure' + " " + response.status);
}
});
}
}
]
});
}
});
Here is my Form2 with Actioncolumns:
Ext.onReady(function()
{
var store=Ext.create('Ext.data.Store',
{
autoload: true,
autosync: true,
data: [],
fields:
[
{name: 'firstname', id:'firstname'},
{name: 'email', id:'email'},
{name: 'mobileno', id:'mobileno'}
]
});
Ext.create('Ext.grid.Panel',
{
renderTo: Ext.getBody(),
height:150,
width:400,
x:200,
y:50,
store:store,
id: 'grid1',
columns:
[
{
header:'Firstname',
id:'firstname',
dataIndex:'firstname',
editor: {
xtype: 'textarea'
}
},
{
header:'Mobileno',
id:'mobileno',
dataIndex:'mobileno',
editor: {
xtype: 'textarea'
}
},
{
header:'Email',
id:'email',
dataIndex:'email',
editor: {
xtype: 'textarea'
}
},
{
header:'Action',
id:'action',
align:'center',
xtype:'actioncolumn',
sortable:false,
items:
[
{
icon:'images/view_icon.gif',
tooltip:'View',
handler: function(grid,rowIndex,colIndex)
{
var rec= grid.getStore().getAt(rowIndex);
}
},
{
icon:'images/edit_icon.gif',
tooltip:'Edit',
handler: function(grid,rowIndex,colIndex,e)
{
var rec= grid.getStore().getAt(rowIndex);
myForm.getForm().load({
// url: '/path/to/form/data',
params: { id: id},
method: 'POST',
waitMsg: 'Loading data...'
});
// Ext.Ajax.request(
// {
// url:'./RetrieveRecords',
// success: function(response)
// {
// Ext.Msg.alert("success" +" " + response.status);
// window.location.reload();
// },
// failure: function(response)
// {
// Ext.Msg.alert("failed" + response.status);
// }
// });
}
},
{
icon:'images/icons/cancel.png',
tooltip:'Delete',
handler: function(grid,rowIndex,colIndex)
{
var rec= grid.getStore().getAt(rowIndex);
var email = rec.get('email');
Ext.Ajax.request(
{
url:'./deleteRecords',
params:{email:email},
success: function(response)
{
Ext.Msg.alert("successfully deleted" +" " + response.status);
window.location.reload();
},
failure: function(response)
{
Ext.Msg.alert("failed" + response.status);
}
});
}
}
]
}
],
selType: 'cellmodel',
plugins:
[
Ext.create('Ext.grid.plugin.CellEditing',
{
clicksToEdit: 1
})
],
listeners:
{
afterrender:function()
{
Ext.Ajax.request(
{
params:{email:email},
url:'./RetrieveRecords',
success: function(response)
{
data = [];
data = Ext.JSON.decode(response.responseText);
Ext.getCmp('grid1').getStore().loadData(data);
},
failure: function(response)
{
Ext.Msg.alert("failure" + " " + response.status);
}
});
}
}
});
});
Try following as edit button:
handler: function(grid, rowIndex, colIndex, e) {
var rec = grid.getStore().getAt(rowIndex);
myForm.loadRecord(rec);
}