How to remove field in websql - extjs

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.

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

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

ExtJS: Custom ComboBox

I'm just trying to create a custom ComboBox to reduce some boilerplate:
Ext.define('App.AutoComboBox', {
extend: 'Ext.form.field.ComboBox',
alias: 'widget.autocombobox',
states: null,
initComponent: function() {
this.callParent(arguments);
if (!this.states) {
this.queryMode = 'remote';
} else {
this.queryMode = 'local';
this.bindStore(Ext.create('Ext.data.Store', {
type: 'array',
fields: ['_placeholder_'],
data: _.map(this.states, function(state) {
return {_placeholder_ : state}; })
}));
this.displayField = this.valueField = '_placeholder_'
}
this.validator = function(v) {
var field = this.displayField,
index = this.getStore().findExact(field, v);
return (index!==-1) ? true : 'Invalid selection';
};
},
listeners: {
select: function(combo, records) {
console.log(combo.getStore().indexOf(records[0])); // !== -1
}
}
});
So that I can use it like:
requires: ['App.AutoComboBox'],
...
items: [{
xtype: 'autocombobox',
name: 'test_local',
fieldLabel: 'test_local',
states: [ 'cat', 'dog' ] // local
}, {
xtype: 'autocombobox',
name: 'test_remote',
fieldLabel: 'test_remote',
store: 'Chipmunks', // a remote store
displayField: 'chipmunk_name'
}]
...
But something is amiss. The AutoComboBox renders OK, shows dropdown of records fine, but when I select an item from the dropdown, the combobox's display field is not set. The store seems to find the selected record (as seen by the select listener), but the value is still not set...
Help? thanks.
Edit: FIXED by moving this.callParent(arguments) after the new store is bound. Now accepting answers that explain why this fixes it... (I don't know why it works.. but it does)
In the parent initComponent method, the displayField is used to create the displayTpl:
if (!me.displayTpl) {
me.displayTpl = new Ext.XTemplate(
'<tpl for=".">' +
'{[typeof values === "string" ? values : values["' + me.displayField + '"]]}' +
'<tpl if="xindex < xcount">' + me.delimiter + '</tpl>' +
'</tpl>'
);
} else if (Ext.isString(me.displayTpl)) {
me.displayTpl = new Ext.XTemplate(me.displayTpl);
}
The bindStore call has probably nothing to do with it, I believe that this is this line that must be put before the call to the parent method:
this.displayField = this.valueField = '_placeholder_';

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

Using buffered store + infinite grid with dynamic data

The goal is to use buffered store for the dynamic data set.
The workflow is below:
Some data is already present on server.
Clients uses buffered store & infinite grid to handle the data.
When the application runs the store is loading
and 'load' event scrolls the grid to the last message.
Some records are added to server.
Client gets a push notification and runs store reload.
topic.store.load({addRecords: true});
The load event runs and tries to scroll to the last message again but failes:
TypeError: offsetsTo is null
e = Ext.fly(offsetsTo.el || offsetsTo, '_internal').getXY();
Seems that the grid view doesn't refreshes and doesn't show the added records, only the white spaces on their places.
Any ideas how can I make the grid view refresh correctly?
The store initialization:
Ext.define('orm.data.Store', {
extend: 'Ext.data.Store',
requires: ['orm.data.writer.Writer'],
constructor: function (config) {
Ext.apply(this, config);
this.proxy = Ext.merge(this.proxy, {
type: 'rest',
batchActions: true,
reader: {
type: 'json',
root: 'rows'
},
writer: {
type: 'orm'
}
});
this.callParent(arguments);
}
});
Ext.define('akma.chat.model.ChatMessage', {
extend:'Ext.data.Model',
fields:[
{ name:'id', type:'int', defaultValue : undefined },
{ name:'createDate', type:'date', dateFormat:'Y-m-d\\TH:i:s', defaultValue : undefined },
{ name:'creator', type:'User', isManyToOne : true, defaultValue : undefined },
{ name:'message', type:'string', defaultValue : undefined },
{ name:'nameFrom', type:'string', defaultValue : undefined },
{ name:'topic', type:'Topic', isManyToOne : true, defaultValue : undefined }
],
idProperty: 'id'
});
Ext.define('akma.chat.store.ChatMessages', {
extend: 'orm.data.Store',
requires: ['orm.data.Store'],
alias: 'store.akma.chat.store.ChatMessages',
storeId: 'ChatMessages',
model: 'akma.chat.model.ChatMessage',
proxy: {
url: 'http://localhost:8080/chat/services/entities/chatmessage'
}
});
var store = Ext.create('akma.chat.store.ChatMessages', {
buffered: true,
pageSize: 10,
trailingBufferZone: 5,
leadingBufferZone: 5,
purgePageCount: 0,
scrollToLoadBuffer: 10,
autoLoad: false,
sorters: [
{
property: 'id',
direction: 'ASC'
}
]
});
Grid initialization:
Ext.define('akma.chat.view.TopicGrid', {
alias: 'widget.akma.chat.view.TopicGrid',
extend: 'akma.chat.view.grid.DefaultChatMessageGrid',
requires: ['akma.chat.Chat', 'akma.UIUtils', 'Ext.grid.plugin.BufferedRenderer'],
features: [],
hasPagingBar: false,
height: 500,
loadedMsg: 0,
currentPage: 0,
oldId: undefined,
forceFit: true,
itemId: 'topicGrid',
selModel: {
pruneRemoved: false
},
multiSelect: true,
viewConfig: {
trackOver: false
},
plugins: [{
ptype: 'bufferedrenderer',
pluginId: 'bufferedrenderer',
variableRowHeight: true,
trailingBufferZone: 5,
leadingBufferZone: 5,
scrollToLoadBuffer: 10
}],
tbar: [{
text: 'unmask',
handler: function(){
this.up('#topicGrid').getView().loadMask.hide();
}
}],
constructor: function (config) {
this.topicId = config.topicId;
this.store = akma.chat.Chat.getMessageStoreInstance(this.topicId);
this.topic = akma.chat.Chat.getTopic(this.topicId);
var topicPanel = this;
this.store.on('load', function (store, records) {
var loadedMsg = store.getTotalCount();
var pageSize = store.pageSize;
store.currentPage = Math.ceil(loadedMsg/pageSize);
if (records && records.length > 0) {
var newId = records[0].data.id;
if (topicPanel.oldId) {
var element;
for (var i = topicPanel.oldId; i < newId; i++) {
element = Ext.get(i + '');
topicPanel.blinkMessage(element);
}
}
topicPanel.oldId = records[records.length-1].data.id;
var view = topicPanel.getView();
view.refresh();
topicPanel.getPlugin('bufferedrenderer').scrollTo(store.getTotalCount()-1);
}
});
this.callParent(arguments);
this.on('afterrender', function (grid) {
grid.getStore().load();
});
var me = this;
akma.UIUtils.onPasteArray.push(function (e, it) {
if(e.clipboardData){
var items = e.clipboardData.items;
for (var i = 0; i < items.length; ++i) {
if (items[i].kind == 'file' && items[i].type.indexOf('image/') !== -1) {
var blob = items[i].getAsFile();
akma.chat.Chat.upload(blob, function (event) {
var response = Ext.JSON.decode(event.target.responseText);
var fileId = response.rows[0].id;
me.sendMessage('<img src="/chat/services/file?id=' + fileId + '" />');
})
}
}
}
});
akma.UIUtils.addOnPasteListener();
},
sendMessage: function(message){
if(message){
var topicGrid = this;
Ext.Ajax.request({
method: 'POST',
url: topicGrid.store.proxy.url,
params:{
rows: Ext.encode([{"message":message,"topic":{"id":topicGrid.topicId}}])
}
});
}
},
blinkMessage: function (messageElement) {
if (messageElement) {
var blinking = setInterval(function () {
messageElement.removeCls('red');
messageElement.addCls('yellow');
setTimeout(function () {
messageElement.addCls('red');
messageElement.removeCls('yellow');
}, 250)
}, 500);
setTimeout(function () {
clearInterval(blinking);
messageElement.addCls('red');
messageElement.removeCls('yellow');
}, this.showInterval ? this.showInterval : 3000)
}
},
columns: [ {
dataIndex: 'message',
text: 'Message',
renderer: function (value, p, record) {
var firstSpan = "<span id='" + record.data.id + "'>";
var creator = record.data.creator;
return Ext.String.format('<div style="white-space:normal !important;">{3}{1} : {0}{4}</div>',
value,
creator ? '<span style="color: #' + creator.chatColor + ';">' + creator.username + '</span>' : 'N/A',
record.data.id,
firstSpan,
'</span>'
);
}
}
]
});
upd: Seems that the problem is not in View. The bufferedrenderer plugin ties to scroll to the record.
It runs a callback function:
callback: function(range, start, end) {
me.renderRange(start, end, true);
targetRec = store.data.getRange(recordIdx, recordIdx)[0];
.....
store.data.getRange(recordIdx, recordIdx)[0]
tries to get the last record in the store.
....
Ext.Array.push(result, Ext.Array.slice(me.getPage(pageNumber), sliceBegin, sliceEnd));
getPage returns all records of the given page, but the last record is missing i.e. the store was not updated perfectly.
Any ideas how to fix?
The problem is that store.load() doesn't fill up store PageMap with the new data. The simplest fix is using store.reload() instead.
Maybe you are to early when listening to the load event. I am doing roughly the same in my application (not scrolling to the end, but to some arbitrary record after load). I do the view-refresh and bufferedrender-scrollTo in the callback of the store.load().
Given your code this would look like:
this.on('afterrender', function (grid) {
var store = grid.getStore();
store.load({
callback: function {
// snip
var view = topicPanel.getView();
view.refresh();
topicPanel.getPlugin('bufferedrenderer').scrollTo(store.getTotalCount()-1);
}
});
});

Resources