Preselect items in EXT JS 4.2 Grid - extjs

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', {

Related

Position a specific row of a grid as the first row

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');
}
}
}]
});

Extjs Combobox store value from another object

I have a object that has some values that i want to display in a combobox that i am adding to a form panel inside a for loop.
this is the contents of the object object
but in my combobox i get data as [object Object]
here is what i am currently doing
for(var i = 0; i < data.length ; i++)
{
console.log('ad');
var storeStates = new Ext.data.ArrayStore({
fields: ['optionText'],
data : [data[i].data.selectOptions.list[i].optionText]
});
var cb = new Ext.form.ComboBox({
fieldLabel: data[i].data.name,
hiddenName: 'fieldTypeName',
id: data[i].data.name.toString(),
valueField: 'optionText',
displayField: 'optionText',
typeAhead: true,
allowBlank: false,
mode: 'local',
selectOnFocus: true,
triggerAction: 'all',
emptyText: 'Survey Field Type',
disabled: this.existingField,
width: 190,
store: storeStates,
listeners: {
'select': function (combo, newValue, oldValue) {
}
}
});
Ext.getCmp('survey-field-form').add(cb);
//Ext.getCmp('survey-field-form').doLayout();
console.log('added');
}
You need to change your store definition from Ext.data.ArrayStore to Ext.data.Store & data as data[i].data.selectOptions.list
var storeStates = new Ext.data.Store({
fields: ['optionText'],
data : data[i].data.selectOptions.list
});
I think you need to define your store like that to get the correct display:
var storeStates = new Ext.data.JsonStore({
data: data[i].data.selectOptions.list,
fields: [{name: "optionText", type: "string"}]
});
I solved it by creating a reader and a store and pushing data into the store and then loading the store like this
// create a Record constructor:
var rt = Ext.data.Record.create([
{name: 'optionValue'},
{name: 'optionText'}
]);
var myStore = new Ext.data.Store({
// explicitly create reader
reader: new Ext.data.ArrayReader(
{
idIndex: 0 // id for each record will be the first element
},
rt // recordType
)
});
var myData = [];
for(var j = 0; j < data[i].data.selectOptions.list.length; j++)
{
var optionText = data[i].data.selectOptions.list[j].optionText.toString();
var optionValue = data[i].data.selectOptions.list[j].optionValue.toString();
myData.push([optionValue, optionText]);
}
myStore.loadData(myData);
Hope this helps someone else

Need solution for Multi Select in Extjs tree

Am complete stranger to Extjs. I have a requirement to allow multi select in the Extjs tree. Below piece of code is doing single select. i need to change the code to make it multi select with semi-colon between selected ids. Can anyone please change the code as per the requirement. Also if you could tell me to which field or variable the selected value of the tree is written into. Thanks in advance
Ext.onReady(function() {
Ext.QuickTips.init();
var str='';
var switch_flag = '';
var approvals = '';
var active_mode = '';
var json = null;
Ext.Ajax.request({
url: 'Dmscategorytree/ajax/Message',
method: 'POST',
params:{
lifecycle_id: str,
switch_flag: switch_flag,
approvals: approvals,
active_mode: active_mode
},
success: function(response, options) {
var path='';
var id='';
var text='';
json=response.responseText;
alert(json);
json = json.replace(/"/g,'\"');
json=Ext.util.JSON.decode(json);
var flag=true;
var myloader = new Ext.tree.TreeLoader();
myloader.load = function(node, cb,scope) {
if(this.clearOnLoad){
while(node.firstChild){
node.removeChild(node.firstChild);
}
}
if(this.doPreload(node)){
this.runCallback(cb, scope || node, [node]);
}
cb();
}
var tree = new Ext.tree.TreePanel({
animate:true,
autoScroll:true,
//loader: new Tree.TreeLoader({dataUrl:'get-nodes.php'}),
containerScroll: true,
border: false,
loader:myloader,
rootVisible: false,
listeners:{
checkchange:function(node){
if(flag){
toggleCheck(tree.root,false,node.id);
path=node.attributes.value;
id=node.attributes.ID;
text=node.attributes.text;
path=path.replace(/\^/g,'/');
}
}
}
});
function SelectToParent()
{
try
{
parent.window.opener.callParent(path,id);
parent.window.opener.focus();
parent.window.close();
}
catch(e){
alert('got exception');
window.close();
}
}
function toggleCheck(node,isCheck,nodeId)
{
flag=false;
if(node)
{
var args=[isCheck];
node.cascade(function(){
c=args[0];
if(nodeId!=this.id){
this.ui.toggleCheck(c);
this.attributes.checked=c;
}
},null,args);
}
flag=true;
return true;
}
var root = new Ext.tree.AsyncTreeNode({
text: 'Ext JS',
draggable:false, // disable root node dragging
id:'src',
children: json
});
tree.setRootNode(root);
var topbar = new Ext.Toolbar({
region : 'north',
height:30,
margins: '0 0 0 5',
items:[
{
xtype: 'box',
id: 'title',
autoEl: {
html: '#label.chooseCat#'
}
,width:525
},
{
text: '#label.Done#',
id: 'doneBtn',
tooltip: 'Done',
handler: SelectToParent
}
]
});
topbar.render('tree');
tree.render('tree');
tree.getRootNode().expand();
}
});
});
Please refer the following links,
pass two id s in extjs 4 tree multiSelect and pass one id in single click
Multiselect Tree & Drag and Drop
Drag and Drop between Grid and “multiselect” control in EXTJS
Demo

How to remove field in websql

I have created a table in my websql using Sencha. Adding values to table works fine,
but removing doesn't work.
I've tried
getStore('favorite').removeAt(1);
but it gave no result. Are there are ways to handle sql requests like
"Delete from favorite where id = 1"
I've been Googling all day long. Any ideas? the code is below:
dockedItems: [
{
xtype: 'toolbar',
dock: 'top',
items: [
{
text: '+',
ui: 'decline',
handler: function(){
var s_name = post.get('list');
var s_image = post.get('image');
//var s_type = record.get('code');
//var c_content = post.get('filmpage');
//alert('РаботаетЬ');
Ext.require(['Ext.data.proxy.SQL']);
Ext.define("Favorite", {
extend: "Ext.data.Model",
config: {
fields: ["id","name","ftype","image","link","res"]
}
});
Ext.create("Ext.data.Store", {
model: "Favorite",
storeId: 'Favorite',
proxy: {
type: "sql"
}
});
var store = Ext.getStore('Favorite');
Ext.getStore('Favorite').removeAt(1);
Ext.getStore('Favorite').sync();
var record = Ext.getStore('Favorite').findExact('id', 1);
Ext.getStore('Favorite').remove(record);
Ext.getStore('Favorite').sync();
/*Ext.getStore('Favorite').add([{
name: s_name,
ftype: cat,
image: s_image,
link: '',
res : '',
}]);
Ext.getStore('Favorite').sync();*/
//Ext.getStore("Users").getModel("Users").getProxy("Users").dropTable("Favorite");
//Ext.getStore("Favorite").getModel("Ext.data.Model").getProxy().dropTable();
}
}
]
}
]
find solution using js that works, still thank you very much for your help.
db = openDatabase("Sencha", "1.0", "Sencha", 200000);
if(!db)
alert("Failed to connect to database.");
else
alert('yeah');
db.transaction(function(tx) {
tx.executeSql("DELETE FROM Favorite WhERE id = 3 ", [], function(result){}, function(tx, error){});
});
You should sync after removing record
var store = Ext.getStore('favorite');
store.removeAt(1);
store.sync();
Update
var index = store.findExact('id', 1);
store.remove(store.getAt(index));
store.sync();
How to debug
console.log(index); // Should return value 0 if there is a match else returns -1.
console.log(store.getAt(index)); // Should return the record with id value 1.

Fill the combo ExtJS by the custom data

I have Combo ExtJS, that should be filled by the data from Spring MVC - like this:
var LongRecord = Ext.data.Record.create([
{name: 'id', mapping: 'id'}
]);
var comboStore = new MyDataStore.data.Store({
proxy: new MyDataStore.data.DwrProxy({
invoker: function(params, arg, cb) {
// data from server
AssetScreener.getEntityOwnerIds(cb);
console.log("invoker has been called");
}
}),
reader: new Ext.data.ArrayReader({}, LongRecord),
listeners: {
'load': function(s, recs) {
alert("!");
}
}
});
Combo code:
new Ext.form.ComboBox({
store: comboStore,
typeAhead: true,
triggerAction: 'all',
editable: false,
width: 100,
displayField: 'id',
valueField: 'id'
});
Problem is that data, that I'm getting from server, looks like this
'5','0',["1","8","133"]
I need to slice the array ["1","8","133"] and show this in combo (change backend java-code is unwishable way).
In combo after this code is executed I see the three empty items. Need hints, please.
In the load event, you'll get the ["1","8","133"] from the recs parameter after slicing. Use store.loadData() to replace the current store records with the correct ones.
You can create a model out of the array to feed the store like so:
var i, item, feed = [];
for(i=0; i<array.length; i++)
{
item = array[i];
feed.push(Ext.create('com.your.Model', {
id : item
}));
}
store.loadData(feed);

Resources