ExtJS: Added grid rows wont de-highlight - extjs

When adding a rows to a grid, and then clicking on it, it gets selected (and highlighted). Then, clicking elsewhere but the new row remains highlighted (so now there are to highlighted rows).
Please, does anyone know what the problem could be? How to make it behave normally, i.e. clicking a row deselects (de-highlights) the other one?
After I reload the page (so the new row is not new anymore), everything works as expected.
Edit: Here's the code for adding rows:
var rec = new store.recordType({
test: 'test'
});
store.add(rec);
Edit 2: The problem seems to be listful: true. If false, it works! But I need it to be true so I'm looking at this further... It looks like as if the IDs went somehow wrong... If the ID would change (I first create the record and then the server returns proper ID, that would also confuse the row selector, no?)

(Note, correct as ExtJS 3.3.1)
First of all, this is my quick and dirty hack. Coincidentally I have my CheckboxSelectionModel extended in my system:-
Kore.ux.grid.CheckboxSelectionModel = Ext.extend(Ext.grid.CheckboxSelectionModel, {
clearSelections : function(fast){
if(this.isLocked()){
return;
}
if(fast !== true){
var ds = this.grid.store,
s = this.selections;
s.each(function(r){
//Hack, ds.indexOfId(r.id) is not correct.
//Inherited problem from Store.reader.realize function
this.deselectRow(ds.indexOf(r));
//this.deselectRow(ds.indexOfId(r.id));
}, this);
s.clear();
}else{
this.selections.clear();
}
this.last = false;
}
});
And this is the place where the clearSelections fails. They try to deselect rows by using ds.indexOfId(r.id) and it will returns -1 because we do not have the index defined remapped.
And this is why we can't find the id:-
http://imageshack.us/photo/my-images/864/ssstore.gif/
Note that the first item in the image is not properly "remapped". This is because we have a problem in the "reMap" function in our Ext.data.Store, read as follow:-
// remap record ids in MixedCollection after records have been realized. #see Store#onCreateRecords, #see DataReader#realize
reMap : function(record) {
if (Ext.isArray(record)) {
for (var i = 0, len = record.length; i < len; i++) {
this.reMap(record[i]);
}
} else {
delete this.data.map[record._phid];
this.data.map[record.id] = record;
var index = this.data.keys.indexOf(record._phid);
this.data.keys.splice(index, 1, record.id);
delete record._phid;
}
}
Apparently, this method fails to get fired (or buggy). Traced further up, this method is called by Ext.data.Store.onCreateRecords
....
this.reader.realize(rs, data);
this.reMap(rs);
....
It does look fine on the first look, but when I trace rs and data, these data magically set to undefined after this.reader.realize function, and hence reMap could not map the phantom record back to the normal record.
I don't know what is wrong with this function, and I don't know how should I overwrite this function in my JsonReader. If any of you happen to be free, do help us trace up further for the culprit that causes this problem
Cheers
Lionel

Looks like to have multi select enabled for you grid. You can configure the selection model of the grid by using the Ext.grid.RowSelectionModel.
Set your selection model to single select by configuring the sm (selection model) in grid panel as show below:
sm: new Ext.grid.RowSelectionModel({singleSelect:true})
Update:
Try reloading the grid using the load method or loadData method of the grid's store. Are you updating the grid on the client side? then maybe you can use loadData method. If you are using to get data from remote.. you can use load method. I use load method to update my grid with new records (after some user actions like add,refresh etc). Or you could simply reload as follows:
grid.getStore().reload();

Related

Toggle cell editor after record programmatically added to grid in ExtJS

I'm using ExtJS 4.2.1 and have a fairly simple setup: JSON-based store and a gridpanel that reads from that store. An add button's click event calls out to the function below.
My goal is to add a blank row to the grid and immediately begin editing it using the Ext.grid.plugin.CellEditing plugin that's enabled on the gridpanel.
var addNewRow = function() {
// start add logic
var row = {
'name': '',
'email': '',
'description': ''
};
store.add(row);
// start auto-edit logic
var index = store.indexOf(row); // -1
var grid = Ext.ComponentQuery.query('gridpanel[itemId=upperPane]')[0];
var plugin = grid.getPlugin('upperPaneEditor');
plugin.startEdit( index, 0 );
};
While debugging this, index is set to -1 and that does not work. I tested the plugin.startEdit()'s functionality with (0, 0) to edit the first column of the first row and it works fine. I tried moving the auto-edit logic to various event handlers try to get it to work:
The store's add event fired after the add and reflected the correct index but the element wasn't present yet in the gridpanel for the plugin to grab it.
The gridpanel's afterrender event didn't fire after the add
The gridpanel's add event fired but only after double-clicking on a cell manually to edit it. It also ended up in a loop with itself.
I'm not sure of what else to try at this point.
Your row is a model config object, not a model instance, therefore store.indexOf returns -1.
Try:
var inst = store.add(row)[0];
...
var index = store.indexOf(inst);

How to get only deleted records from an Ext js Grid store?

I have a grid store and I am able to get modified data using
var modifiedData = store.getModifiedData();
Now I want to get deleted records (I am using ExtJs 3).
I tried using var deletedData = store.getRemovedRecords(); but I guess this property is available in ExtJs 4.
I just want to fetch the records that are deleted from the grid.
Any help would be appreciated.
By default this is not possible.
ExtJS 3.x is only capable of tracking modified records (out of the box). Deleted (removed) records get removed completely. But there is one thing you can do; The store will fire the remove event for each record with the record itself as second argument. You may use this to create your own array of removed records. The implementation would be really simple I guess. You can do it per instance or create a whole new storetype by extending. But I guess the later is not really needed here.
Here is a example. Note that you might need take care of other events to clear the removedList.
var myStore = new Ext.data.Store({
removedList: [],
listeners: {
clear: function(store) {
store.removedList = [];
},
load: function(store) {
store.removedList = [];
},
remove: function(store, record, index) {
store.removedList.push(record);
}
}
});
Check these two links out. They might be helpful.
http://www.sencha.com/forum/showthread.php?58888-Store-find-deleted-added-records
mi
http://www.sencha.com/forum/showthread.php?15671-Ext.data.Store-with-persistence

Extjs 4.0.7, Editor Grid - how to get updated cell value?

I need to get(retrieve) updated cell value in controller. (MVC)
So I tried this,
var modified = this.getItemGrid().getStore().getUpdatedRecords();
console.log(modified); // return [] empty array
var modified = this.getItemList_Store().getUpdatedRecords();
console.log(modified); // return [] empty array
but always it returns empty array even I updated some cell value.
anybody know what I am doing wrong?
Here is my part of view code,
Ext.define("App.view.orders.ItemList_view", {
extend: "Ext.grid.Panel",
alias: "widget.itemList_view",
plugins: [
Ext.create('Ext.grid.plugin.CellEditing', {
clicksToEdit: 1
})
],
initComponent: function () {
this.store = "ItemList_store";
this.columns = [
{
xtype: 'checkcolumn', text: "Ship", width: 50, dataIndex: "DR"
},
{ header: "test", width: 100, dataIndex: "test",
editor: {
xtype : 'textfield'
}
}
];
this.selModel = Ext.create("Ext.selection.CheckboxModel");
//this.selModel = Ext.create("Ext.selection.CellModel"); // It does not works either.
this.callParent(arguments);
},
.
.
.
Thank you!
[EDIT]
Thank you very much for your answer! I have some more question about editor grid.
Its much different from Ext3. so I'm very confusing now :(
Q1. How to collect edited record data (once click button)?
the event fired once the grid cell be changed.
but I want collect edited grid record once I click the 'Update edited cell' button, and I want to update all together at the once.
In Ext3, I did like this,
(button) click : function(){
var modified = mygridStore.getModifiedRecords();
var recordsToSend = [];
Ext.each(modified, function(record){
recordsToSend.push(record.data);
});
var grid = Ext.getCmp('grid');
grid.el.mask('Updating','x-mask-loading');
grid.stopEditing();
recordsToSend = Ext.encode(recordsToSend);
Ext.Ajax.request({
url : '/test/test',
params : {
data : recordsToSend
},
success : function(response){
grid.el.unmask();
alert(response.responseText);
mygridStore.commitChanges();
},
failure : function(response){
mygridStore.rejectChanges();
}
});
}
How can I change the code for Extjs4 ?
Q2. I don't know still how to find out for changed checkcolumn.
I tried this, but I does not work for checkcolumn (of cause I tested after change checkbox)
// grid coumn
{
xtype: 'checkcolumn', header: "My Check Column", width: 50, dataIndex: "CH"
}
-
// in control
'myGrid': {
validateedit: function (plugin, edit) {
console.log(edit);
},
checkchange: function (plugin, edit) {
console.log(edit);
console.log(edit.value);
}
}
Q3. When I click the cell to edit, the show some HTML tag in -_-;;
I really appreciate for your help. and thank you very much for your valuable time!
The editors (cell editors or row editors) do not commit their values to the store until you complete the edit - which means pressing ENTER or blurring the active cell editor by clicking elsewhere on the page, or clicking the save button on the row editor form .
If your purpose for reading the updated value in your editor is to perform some kind of validation I would suggest simply listening to the validateedit event in your grid's controller, as described here.
The second argument that this event passes to your handler contains a lot of data about the edit that you can then perform validation with. If the edit doesn't pass your validation you can return false from your handler and the value in the celleditor will revert to it's original value. The validateedit event gets fired from the editor grid itself so you would add an event handler in your controller for it like this:
Ext.define('MyApp.controller.MyController', {
init: function() {
this.control({
'mygridpanel': {
validateedit: function(plugin, edit) {
// silly validation function
if (edit.value != 'A Valid Value') {
return false;
}
},
},
});
},
});
But you should check out the link above to see all the different objects available in that second argument I named edit.
The validateedit event is fired right before the record is committed into the store - after the user has already clicked ENTER or blurred the editor, i.e., while the editor is closing.
If you are trying to get the celleditor's value before it starts to close, for some reason other than validation for example, you could get the active celleditor's value like this:
// myGrid is a reference to your Ext.grid.Panel instance
if (myGrid.editingPlugin.editing) {
var value = myGrid.editingPlugin.getActiveEditor().field.value
console.log('value: ' + value);
}
If there is no active editor then myGrid.editingPlugin.getActiveEditor().field would throw an error, that's why I wrapped a conditional around it.
One other point I should make, for validation in editor grids, I found that it is easiest to just put a validator config in the grid column's editor definition. That will give you all the handy validation CSS while the user is setting the field's value and alert him if there is a problem with the value before he tries to save it.
To get an idea of what I mean, try entering letters in the date column of this example. Mouse over the editor cell and you will get the error message.
EDIT
It seems I misunderstood you original question, I'll break down my answers to your questions above though,
Question 1
Once you have completed an edit (clicked ENTER or ), your call to mygridStore.getModifiedRecords() should be working fine because the record will have been committed to the store. I see that it was not working, I will cover that in a moment.
I should point out that ExtJS4 has a store.sync() method as covered here.
Instead of extracting the modified records from the store, encoding them, manually doing an ajax request to save them to the server and then manually committing them you can call this sync method and it will take care of all of these actions for you.
If you have different URLs to handle the different create, read, update, destroy operations fired off by your store's load and sync methods, you can use the store's proxy api config to map your URLs to these operations as covered here. Or you can set-up your server side controller to be able to differentiate between your store's load request (read operations default to HTTP GET) and it's sync requests (create, update and delete operations default as HTTP POST).
There could be many different ways to go about doing this on the server side, the way I usually do it is to have one SQL stored procedure for GET requests and one for POST requests for any given store. I include the store name as an extra param and then my server side controller runs the appropriate stored procedure based on whether it is a GET or a POST request.
Question 2
Cell editing doesn't support checkcolumn edits. You have to make a different handler to listen to changes on that, something like this:
checkchange: function (column, rowIndex, checked) {
var record = store.getAt(rowIndex),
state = checked ? 'checked' : 'unchecked'
console.log('The record:');
console.log(record)
console.log('Column: ' + column.dataIndex);
console.log('was just ' + state)
}
Your call to mygridStore.getModifiedRecords() should be able to pick up the check changes also however, they get committed to the grid's store right away after being checked. store.sync() would also pick up changes to checkcolumn.
Question 3
I can't completely tell what is causing that problem but it may be something strange going on with your validateedit event, your handler should be returning true or false.
As I said earlier, I misunderstood the reason you originally asked this question. I thought you were trying to do some kind of validation while an edit was in progress. Now I understand that you are trying to get all of the modified records from the store after all the editing is completed in order to save them to the database, I was thrown off because in ExtJS 4 a store is usually saved to the database with the sync method as I mentioned.
In other words, you don't need the validateedit event or checkchange event to get a list of modified records.
The actual problem you are having might be trouble with the store's getter methods (getModifiedRecords, getUpdatedRecords) in some 4.07 versions, take a look at this post and this one.
So with all that said, the best advice I can give you is 1) try out the stores sync method for saving modified data to the database and 2) upgrade to ExtJS 4.1, there were a lot of bugs that were straightened out between 4.07 and 4.1 which you should be able to take advantage of, I cut out about 75% of the overrides I was using to make things work when I switched over to 4.1.
EditedGrid.plugins[0].completeEdit();
This will make the active changes commit and call edit event also.
listeners: {
validateedit: function (editor, e) {
//console.log(editor);
var oldVal = editor.originalValue;
var newVal = editor.value;
}
}

extjs 4 form still has record set after form.reset();

I have a grid bound to a form the forms submit action is to update the loaded record if there is one and add a new record if its a blank form. but if I select a record first and then call
myGrid.getSelectionModel().deselectAll();
myform.getForm().reset();
to clear the form so I can add a new record it overwrites the previously selected record with an update.
record = myform.getRecord();
if(record){
record.set(values);
}
shouldn't myform.getRecord(); be null after a reset? how do I clear the record selection?
In short, no, it shouldn't and you don't have legal approaches to clear the record after the first time you load anything via loadRecord.
Although, you could still do myform.getForm()._record = null assignment, I would strongly object against that, as it may break some internal functionality by ExtJS.
Here is an extract from ExtJS API:
getRecord() : Ext.data.Model
Returns the last Ext.data.Model instance
that was loaded via loadRecord
And it does exactly that, returns the last record loaded via loadRecord.
Here are some sources:
getRecord: function() {
return this._record;
},
loadRecord: function(record) {
this._record = record;
return this.setValues(record.data);
},
Actually, those are the only methods of Ext.form.Basic (an instance of which is returned by getForm()) dealing with this._record field.
As for reset
reset: function() {
var me = this;
me.batchLayouts(function() {
me.getFields().each(function(f) {
f.reset();
});
});
return me;
},
As you could see, reset has nothing to do with the record returned by getRecord(), it's just resetting field values.
For anyone interested, you can override the default form panel to add functionality to clear form fields. Add the following to your code:
Ext.override(Ext.form.Panel, {
clearForm:function(){
Ext.each(this.getForm().getFields().items, function(field){
field.setValue('');
});
}
});
You can then clear a form using:
myForm.clearForm()
Where myForm is your form panel.
This is what you looking for:
form.getForm().reset(true);
True to unbind any record set by loadRecord.
See Ext.form.Basic.reset() syntax
I find this question because I have a similar scenario but slightly different:
ExtJS 4.1.1
TreePanel
In ExtJS 4.1 in sync() method you can use an options object in which you can define a callback, success and failure functions. Since I'm sure I'm only synchronozing just one record, I loaded the returned record:
me.getHelpItemsStore().sync({
success: function(batch) {
// We expect single operation so...
var record = batch.operations[0].getRecords()[0];
form.loadRecord(record);
}
});
Little late but hope helps you.

How to clear the store and update a paging toolbar?

i need to reset paging toolbar parameters as "page", "start", "limit" when i click on a search button to re-load grid store with different parametres!
how can i do it?
the problem is that when i am on the next page, and i do a new search, i have the parameters page=2, start=25, limit=25 dirty, instead i need to reset this parametres.
my code:
listeners: {
click: function(){
Ext.getCmp('GrlGio').getStore().removeAll();
Ext.getCmp('GrlGio').store.load({
params:{
mode: "RIC",
DataRicerca: dd,
Pit: Ext.getCmp('cmbPiattaforma').getValue()
}
});
}
}
thanks!
In Ext 4, I found loadPage() worked pretty well for resetting the data store and making the paging toolbar go back to the first page. Example:
store.loadPage(1) // note: 1-based, not 0-based
Guys currentPage=1 did the trick for me
before loading the store every time call the below
By the way i am getting 500 results and loading in cache
Pagination is for local, any way you can try this before any new search
var store = Ext.getStore('MyStoreS');
store.proxy.extraParams = { employeeId : searchStr};
store.currentPage = 1;
store.load();
you can manualy reset the params
Ext.getCmp('GrlGio').getStore().getProxy().pageParam =1;
Ext.getCmp('GrlGio').getStore().getProxy().startParam =0;
and then do the store load. I know it looks hardcoded but it's the only solution i found...
Try this -
pagingToolbar.moveFirst();
Define following function "resetStartParam" , by overriding ext.data.store:
Ext.override(Ext.data.Store, {
resetStartParam:function(){
//get the latest store options
var storeOptions=this.lastOptions;
if(storeOptions!=undefined){
//get the param names
var pn = this.paramNames;
//get the params from options
var params=storeOptions.params;
//change the param start value to zero
params[pn.start] = 0;
//reset options params with this new params
storeOptions.params=params;
//apply this new options to store options
this.storeOptions(storeOptions);
}
}
});
Now call this function on click of your search button:
Ext.getCmp('GrlGio').getStore().resetStartParam();
Thats it.It should work.
I know that this is an old post but I thought I'd add in my pennies work. I'm using EXTJS 4 and had a similar problem. When I did a new search the page number etc did not reset. The solution I found, which appears to work with the nav bar automatically is using the currentPage attribute of the store. I do have a slight odd setup but doing this.currentPage = 1 when I do a new search works fine for me
try this in your handler
Ext.getCmp('gridpanel').getStore().removeAll();
Ext.getCmp('PagingToolbar').moveFirst();
after this, put your search query and load the store accordingly
Ext.getCmp('gridpanel').getStore().load({params : { start : 0, limit : maxRecords, searchText : _searchText } });
hope it helps
just call pagingToolbar.onLoad() after removeAll(). Plain and simple.
Here is how I achieved search with paging. It only does 1 request and it refreshes the paging data.
onExecuteSearch: function(){
var params = this.getSearchForm().getForm().getFieldValues()
, proxy = this.getSomeGrid().getStore().getProxy();
proxy.extraParams = params;
this.getPagingToolbar().moveFirst();
}
getFieldValues() documentation: http://docs.sencha.com/ext-js/4-0/#!/api/Ext.form.Basic-method-getFieldValues
For more about the proxy "extraParams" look here: ExtJs4 - Store baseParams config property?
This work fine (refresh correctly the paging info):
myStore.removeAll();
myStore.fireEvent('load', myStore, [], {});
Had to change the page size to 500 for printing the WHOLE store/grid, and once printed, restore the grid to the original page size of 25.
// 500 records are now in the store and on the grid
ux.core.grid.Printer.print(this.getOrderList());
store.pageSize = this.displaySize; // new page size is 25
this.getPagingToolbar().doRefresh(); // equivalent of pressing a refresh button on the toolbar
does the trick - reloads store with the same sorters/filters/currentPage

Resources