Position a specific row of a grid as the first row - extjs

How to set a particular row in grid as the first row in the grid I have tried selecting the row as shown below
var grid = interface.down('directorReviewGrid');
store.removeAll();
store.load({
params: {
workflow_stage: workflow_stage
},
callback: function(records, operation, success) {
var rowIndex = this.find('id', id);
/*where 'id': the id field of your model,
record.getId() is the method automatically created by Extjs.
You can replace 'id' with your unique field.. And 'this' is your store.*/
grid.getView().scrollRowIntoView(rowIndex);
grid.getView().select(rowIndex);
}
});

You can implement using store.insert( 0, records ) and for go to particular that, you can use grid.getView().focusRow(rowIdx).
You can check in this working FIDDLE. Hope this will help/guide you to achieve your requirement.
CODE SNIPPET
var char = 'ABCDEFGHJKLIMNOPQRSTUVWXYZ';
function getRandomNumber() {
return Math.floor(Math.random() * 26);
}
function getRandomName() {
let name = '';
for (let i = 0; i < 6; i++) {
name += char.charAt(getRandomNumber());
}
return name;
}
function getData() {
let data = [];
for (let key = 0; key < 100; key++) {
data.push({
id: key,
name: getRandomName()
})
}
return data
}
Ext.create('Ext.data.Store', {
storeId: 'gridstore',
fields: ['id', 'name'],
data: getData()
});
Ext.create('Ext.grid.Panel', {
title: 'Focus to Row',
store: 'gridstore',
columns: [{
text: 'ID',
dataIndex: 'id'
}, {
text: 'Name',
dataIndex: 'name',
flex: 1
}],
height: window.innerHeight,
renderTo: Ext.getBody(),
tbar: ['->', {
text: 'Move Selected Row to First',
handler: function () {
var grid = this.up('grid'),
store = grid.getStore(),
selctionM = grid.getSelectionModel(),
rec = selctionM.getSelection()[0];
//If selected record is available
if (rec) {
store.remove(rec) //First the remove the store
store.insert(0, rec); //Insert into 1st postion
selctionM.select(rec); //Select same record
grid.getView().focusRow(rec); //Focuses a particular row and brings it into view. Will fire the rowfocus event.
} else {
Ext.Msg.alert('Info', 'Please select any row');
}
}
}]
});

Related

Best way to use checkboxes inside a Extjs Pivot Grid

I have a pivot grid which display if the users have create,read,update,delete" permissions, the users are agrouped in this way departaments > estabilishments > sectors > users and i want the user to be able to edit this fields.
I already tried using with a renderer:
aggregate: [{
renderer: function(value, record, dataIndex, cell, column) {
var id = Ext.id();
Ext.defer(function() {
Ext.widget('checkbox', {
renderTo: id,
checked: value,
listeners: {
change: {
fn: function(event, target) {
//some function here
}
}
}
});
}, 100);
return Ext.String.format('<div id="{0}"></div>', id);
},
aggregator: 'aggCheckBoxR',
dataIndex: 'Incluir',
header: 'Incluir'
}]
and with a widget column:
aggregate: [{
aggregator: 'aggCheckBoxR',
column: {
xtype: 'widgetcolumn',
widget: {
xtype: 'checkbox',
listeners: {
change: function(cb) {
//some function here
}
}
}
},
dataIndex: 'Incluir',
header: 'Incluir'
}]
My Aggregator:
aggCheckBoxR: function(records, measure, matrix, rowGroupKey, colGroupKey) {
if (records.length > 1) {
let checkAllTrue = true;
for (var i = 0; i < records.length; i++) {
if (records[i].get('Incluir') === false || records[i].get('Incluir') === 0) {
checkAllTrue = false;
}
}
return checkAllTrue;
} else {
return records[0].get('Incluir');
}
}
The checkbox apears on the grid but my problem is the data "dont persist", whenever i expand or collapse a left axis on the pivot grid the value of the checkbox returns to its original value, how can i persist this data?
Already tried update the record manualy
change: function(cb) {
var nomeCmp = cb.getWidgetRecord().data._compactview_;
Ext.getStore('acesso.ColabStore').findRecord('Nome', nomeCmp).data.Incluir = true;
}
But still, it doestn't work.
EDIT: Had to change the column object event listener to:
{
xtype: 'widgetcolumn',
widget: {
xtype: 'checkbox',
listeners: {
afterrender: function(component, eOpts) {
console.log('after,render');
component.getEl().on('change', function(e, el) {
console.log('change func here');
})
}
}
}
}
With this, the change event is only fired when the users check a checkbox, and finally, I could use
norbeq's answer
You can update the record manually using:
record.set('Incluir',true);
and if you dont wan't to send changes to server:
record.commit();

ToolTip in Grid cell - ExtJs 6

I am using below code to display Tool Tip for Grid cell In ExtJS 6
{
header: 'Name',
cls: 'nameCls',
locked: true,
tdCls: 'nameTdCls',
dataIndex: 'name',
renderer: function (value, metaData, record, rowIndex, colIndex, store, view) {
metaData.tdAttr = 'data-qtip= "' + value + '" data-qclass="tipCls" data-qwidth=200';
return value;
}}
When i run the application it doesnt show the tooltip and display below error message.
Any idea guys??
Thanks in advance guys.
Regards,
Mahendra
Have you tried creating an Ext.tip.ToolTip? You can create a single one to serve as tooltip for each name cell (using delegate) and update it with the value of that cell. Set up a grid render listener to create the tooltip like this:
render: function(grid) {
var view = grid.getView();
grid.tip = Ext.create('Ext.tip.ToolTip', {
target: view.getId(),
delegate: view.itemSelector + ' .nameTdCls',
trackMouse: true,
listeners: {
beforeshow: function updateTipBody(tip) {
var tipGridView = tip.target.component;
var record = tipGridView.getRecord(tip.triggerElement);
tip.update(record.get('name'));
}
}
});
}
For a working example, see this Fiddle.
Thanks for Robert Klein Kromhof!
grid columns:
columns: [{..., tdCls: 'tip'}]
grid listeners:
render: function (grid) {
var view = grid.getView();
grid.tip = Ext.create('Ext.tip.ToolTip', {
target: view.getId(),
delegate: view.itemSelector + ' .tip',
trackMouse: true,
listeners: {
beforeshow: function (tip) {
var tipGridView = tip.target.component;
var record = tipGridView.getRecord(tip.triggerElement);
var colname = tipGridView.getHeaderCt().getHeaderAtIndex(tip.triggerElement.cellIndex).dataIndex;
tip.update(record.get(colname));
}
}
});
},
destroy: function (view) {
delete view.tip;
}
Create independent function and call when you need.
var grid = Ext.getCmp('your_grid_id'); // Enter your grid id
initToolTip(grid); // call function
initToolTip: function(grid) {
var view = grid.view;
// record the current cellIndex
grid.mon(view, {
uievent: function(type, view, cell, recordIndex, cellIndex, e) {
grid.cellIndex = cellIndex;
grid.recordIndex = recordIndex;
}
});
grid.tip = Ext.create('Ext.tip.ToolTip', {
target: view.el,
delegate: '.x-grid-cell',
trackMouse: true,
renderTo: Ext.getBody(),
listeners: {
beforeshow: function updateTipBody(tip) {
if (!Ext.isEmpty(grid.cellIndex) && grid.cellIndex !== -1) {
header = grid.headerCt.getGridColumns()[grid.cellIndex];
columnText = grid.getStore().getAt(grid.recordIndex).get(header.dataIndex);
tip.update(columnText);
}
}
}
});
}

Preselect items in EXT JS 4.2 Grid

I am trying to preselect items in my EXT grid based on the value of one of the items in the data store.
In my data store I fetch 7 items, the last item I grab 'installed' is a BOOLEAN and I would like to use that to preselect items in my grid.
Here is the code I have so far that is not working...
Ext.require([
'Ext.grid.*',
'Ext.data.*',
'Ext.selection.CheckboxModel'
]);
Ext.onReady(function(){
Ext.QuickTips.init();
var sb = $('#sb_id').val();
// Data store
var data = Ext.create('Ext.data.JsonStore', {
autoLoad: true,
fields: [ 'name', 'market', 'expertise', 'id', 'isFull', 'isPrimary', 'installed'],
proxy: {
type: 'ajax',
url: '/opsLibrary/getLibraryJsonEdit',
extraParams: {
sb_id: sb
},
actionMethods: 'POST'
},
sorters: [{
property: 'market',
direction: 'ASC'
}, {
property: 'expertise',
direction: 'ASC'
}]
});
data.on('load',function(records){
Ext.each(records,function(record){
var recs = [];
Ext.each(record, function(item, index){
console.log(item.data);
if (item.data['installed'] == true) {
console.log('Hi!');
recs.push(index);
}
});
//data.getSelectionModel().selectRows(recs);
})
});
// Selection model
var selModel = Ext.create('Ext.selection.CheckboxModel', {
columns: [
{xtype : 'checkcolumn', text : 'Active', dataIndex : 'id'}
],
listeners: {
selectionchange: function(value, meta, record, row, rowIndex, colIndex){
var selectedRecords = grid4.getSelectionModel().getSelection();
var selectedParams = [];
// Clear input and reset vars
$('#selected-libraries').empty();
var record = null;
var isFull = null;
var isPrimary = null;
// Loop through selected records
for(var i = 0, len = selectedRecords.length; i < len; i++){
record = selectedRecords[i];
// Is full library checked?
isFull = record.get('isFull');
// Is this primary library?
isPrimary = record.get('isPrimary');
// Build data object
selectedParams.push({
id: record.getId(),
full: isFull,
primary: isPrimary
});
}
// JSON encode object and set hidden input
$('#selected-libraries').val(JSON.stringify(selectedParams));
}}
});
I was trying to use an on.load method once the store was populated to go back and preselect my items but am not having any luck.
Im a Python guy and don't get around JS too much so sorry for the noobness.
Any help would be appreciated.
Thanks again!
You should be able to do something like:
//create selModel instance above
data.on('load', function(st, recs) {
var installedRecords = Ext.Array.filter(recs, function(rec) {
return rec.get('installed');
});
//selModel instance
selModel.select(installedRecords);
});
Select can take an array of records.
http://docs.sencha.com/extjs/4.2.1/#!/api/Ext.selection.Model-method-select
//data.getSelectionModel().selectRows(recs);
Didn't work because store's don't have a reference to selection models it is the other way around. You can get a selection model from a grid by doing grid.getSelectionModel() or
you can just use the selModel instance you created
var selModel = Ext.create('Ext.selection.CheckboxModel', {

Extjs Grid - Delete all record has a conditional

I have a grid and a button will delete in http://jsfiddle.net/9zB8R/
My field like fields: ['id', 'name', 'type']. If type == delete i will delete it.
I init data like:
var simpleData = [];
var store = new Ext.data.ArrayStore({
fields: ['id', 'name', 'type'],
data: simpleData
});
for (i = 0; i < 20; i++) {
simpleData.push({id:''+i+'', name: 'name'+i, type: 'delete'});
}
//this record will not delete
simpleData.push({id:'20', name: 'enable', type: 'enable'});
store.loadData(simpleData);
I have a tbar like below but that can't delete all record have type == delete. How can i fix that. Thanks.
tbar:[
{
text:'Delete all type = delete',
handler:function(){
store.each(function(item, idx) {
if (item && item.get('type')=='delete') {
store.removeAt(idx);
}
});
}
}
]
The problem is with the "each" loop. Removing items in the loop is changing store size and hence only some of the items are getting deleted.
To get around it, you can loop through the store in reverse order and then delete as below:
var grid = new Ext.grid.GridPanel({
width: 400,
height: 600,
store: store,
loadMask: true,
renderTo: Ext.getBody(),
tbar:[
{
text:'Delete all type = delete',
handler:function(){
var i = store.getCount()-1;
for (i; i>=0; i--) {
if (store.getAt(i).get('type')=='delete') {
store.removeAt(i);
}
}
}
}
],

remember after refresh selected row in extjs grid

I have a problem. I use extjs grid. This grid will be refreshed every seconds.
I refresh with this function:
ND.refresh = function() {
ND.commList.load();
}
var refreshSeconds = refreshRate * 1000;
var t = setInterval('ND.refresh()', refreshSeconds);
But when someone selected a row to highlight it it reset this selection.
How can I remember the selected row and highlight it again after refresh?
This is my grid:
var grid = Ext.create('Ext.grid.Panel', {
autoscroll: true,
region: 'center',
store: ND.dashBoardDataStore,
stateful: true,
forceFit: true,
loadMask: false,
stateId: 'stateGrid',
viewConfig: {
stripeRows: true
},
columns: [{
text: 'Vehicle',
sortable: true,
flexible: 1,
width: 60,
dataIndex: 'vehicle'
}, {
text: 'CCU',
sortable: true,
flexible: 0,
width: 50,
renderer: status,
dataIndex: 'ccuStatus'
}]
});
Thanks guys
I wrote simple Ext.grid.Panel extension that automatically selects back rows that were selected before store reload. You can try it in this jsFiddle
Ext.define('PersistantSelectionGridPanel', {
extend: 'Ext.grid.Panel',
selectedRecords: [],
initComponent: function() {
this.callParent(arguments);
this.getStore().on('beforeload', this.rememberSelection, this);
this.getView().on('refresh', this.refreshSelection, this);
},
rememberSelection: function(selModel, selectedRecords) {
if (!this.rendered || Ext.isEmpty(this.el)) {
return;
}
this.selectedRecords = this.getSelectionModel().getSelection();
this.getView().saveScrollState();
},
refreshSelection: function() {
if (0 >= this.selectedRecords.length) {
return;
}
var newRecordsToSelect = [];
for (var i = 0; i < this.selectedRecords.length; i++) {
record = this.getStore().getById(this.selectedRecords[i].getId());
if (!Ext.isEmpty(record)) {
newRecordsToSelect.push(record);
}
}
this.getSelectionModel().select(newRecordsToSelect);
Ext.defer(this.setScrollTop, 30, this, [this.getView().scrollState.top]);
}
});
The straightforward solution is just save somewhere in js index of selected row. Then after reload you could easily select this row by index using grid's selection model.
Get selection model: http://docs.sencha.com/ext-js/4-0/#!/api/Ext.grid.Panel-method-getSelectionModel
var selectionModel = grid.getSelectionModel()
Get selected rows: http://docs.sencha.com/ext-js/4-0/#!/api/Ext.selection.Model-method-getSelection
var selection = selectionModel.getSelection()
Set selected row back: http://docs.sencha.com/ext-js/4-0/#!/api/Ext.selection.Model-method-select
selectionModel.select(selection)
Here is another way to select the previously selected record:
var selectionModel = grid.getSelectionModel()
// get the selected record
var selectedRecord = selectionModel.getSelection()[0]
// get the index of the selected record
var selectedIdx = grid.store.indexOfId(selectedRecord.data.id);
// select by index
grid.getSelectionModel().select(selectedIdx);
For some reason the grid.getSelectionModel().select(record) method wasn't working for me, but selecting by index seems to work.
Edit: found out why grid.getSelectionModel().select(record) method wasn't working. Apparently the store is reloaded, the record instances aren't the same (they have different automatically generated Ext IDs). You have to use selectAt() in this case.
for extjs 4.1.7 users
need a workarround about the statement in
refreshSelection() {
...
Ext.defer(this.setScrollTop, 30, this,
[this.getView().scrollState.top])
}
thus setScrollTop no longer exists
so a working soluction is add
me.getView().preserveScrollOnRefresh = true;
in initComponent
Ext.define('PersistantSelectionGridPanel', {
extend: 'Ext.grid.Panel',
selectedRecords: [],
initComponent: function() {
this.callParent(arguments);
this.getStore().on('beforeload', this.rememberSelection, this);
this.getView().on('refresh', this.refreshSelection, this);
//-------------------------------------------
me.getView().preserveScrollOnRefresh = true;
//-------------------------------------------
},
rememberSelection: function(selModel, selectedRecords) {
if (!this.rendered || Ext.isEmpty(this.el)) {
return;
}
this.selectedRecords = this.getSelectionModel().getSelection();
this.getView().saveScrollState();
},
refreshSelection: function() {
if (0 >= this.selectedRecords.length) {
return;
}
var newRecordsToSelect = [];
for (var i = 0; i < this.selectedRecords.length; i++) {
record = this.getStore().getById(this.selectedRecords[i].getId());
if (!Ext.isEmpty(record)) {
newRecordsToSelect.push(record);
}
}
this.getSelectionModel().select(newRecordsToSelect);
}
});
i have make modification on this code.
If you make selection, and aplys a filter on the store and reload it, the selection model have a first empty array in this selected collection ( at index 0 ).
This modification is in the last line of the "refreshSelection" function.
if (newRecordsToSelect.length >= 1){
this.getSelectionModel().select(newRecordsToSelect);
Ext.defer(this.setScrollTop, 30, this, [this.getView().scrollState.top]);
}

Resources