I am struggling to find ways how to preserve data to local storage but seems no luck on my side now. I can successfully add/ remove items in store however, whenever i try to refresh nor reload the page (google chrome) looks like no data found in store.
Here is my code:
Model: Pendingmodel.js
Ext.define('mysample.model.PendingModel', {
extend: 'Ext.data.Model',
config: {
fields: [
{
name: 'id',
type: 'int'
},
{
name: 'ALIAS'
},
{
name: 'OBJECT'
},
{
name: 'DATETIME'
},
{
name: 'FIELDVALUE'
}
],
proxy: {
type: 'localstorage',
id: 'PendingModelProxy'
}
}
});
Store: Pendingstore.js
Ext.define('mysample.store.PendingStore', {
extend: 'Ext.data.Store',
requires: [
'mysample.model.PendingModel'
],
config: {
autoLoad: true,
model: 'mysample.model.PendingModel',
storeId: 'PendingStore'
}
});
Controller:
onDraftCommand: function (form, isTapped) {
var isValid = true;
var me = this, getForm = me.getLeadsView();
var pendingItems = getForm.getValues();
var cleanItems = getForm.getValues();
cleanItems['reset'] = function() {
for (var prop in this) {
delete this['reset'];
delete this['eventParameter'];
this[prop] = '';
}
}
if(isTapped == true && isValid == true) {
Ext.Msg.confirm('Message', 'Are you sure you want to save this on draft?', function (btn) {
switch (btn) {
case 'yes':
var date = new Date(), id = date.getUTCMilliseconds();
var obj = {
'ALIAS': 'leadsview',
'OBJECT': 'Leads Form',
'id': id,
'DATETIME': date,
'FIELDVALUE': pendingItems,
};
console.log('Leads pending store');
console.log(obj);
Ext.data.StoreManager.lookup('PendingStore').add(obj);
Ext.data.StoreManager.lookup('PendingStore').sync();
console.log(Ext.data.StoreManager.lookup('PendingStore'));
//clear form
cleanItems.reset();
getForm.setValues(cleanItems);
//Ext.getCmp('signatureField').removeImage();
break;
default:
break;
}
});
}
}
Add a identifier strategy inside your model as below.
Ext.define('mysample.model.PendingModel', {
extend: 'Ext.data.Model',
config: {
identifier: 'uuid', // add this
fields: [
{
name: 'id',
type: 'int'
}
],
proxy: {
type: 'localstorage',
id: 'PendingModelProxy'
}
}
You need to add the unique identifier in your model, like this:-
Ext.define('mysample.model.PendingModel', {
extend: 'Ext.data.Model',
requires: [
'Ext.data.identifier.Uuid'
],
config: {
identifier: {
type: 'uuid',
isUnique: true
},
fields: [
{
name: 'id',
type: 'int'
},
{
name: 'ALIAS'
},
{
name: 'OBJECT'
},
{
name: 'DATETIME'
},
{
name: 'FIELDVALUE'
}
],
proxy: {
type: 'localstorage',
id: 'PendingModelProxy'
}
}
});
Related
I'm using jquery-querybuilder to build out a query. I'm currently having an issue with adding in selectize as a plugin to allow for autocomplete inside the select inputs. I'm logging the data in the for loop and it prints out the correct data so I know its physically getting the data, but when typing in the input box, there is still no autocomplete and I'm not quite sure where I went wrong.
let totalMachines = [];
var rules_basic = {
condition: 'AND',
rules: [{
}, {
condition: 'OR',
rules: [{
}, {
}]
}]
};
let options = {
plugins: [],
allow_empty: true,
filters: [
{
id: 'machineName',
label: 'Machine Name',
type: 'string',
input: 'text',
operators: ['equal'],
plugin: 'selectize',
values: {
},
plugin_config: {
valueField: 'id',
labelField: 'machineName',
searchField: 'machineName',
sortField: 'machineName',
create: false,
maxItems:3,
plugins: ['remove_button'],
onInitialize: function() {
var that = this;
totalMachines.forEach(function(item) {
that.addOption(item);
console.log(item)
});
}
},
valueSetter: function(rule, value) {
rule.$el.find('.rule-value-container input')[0].selectize.setValue(value);
}
},
]
}
$.ajax({
url: '/api-endpoint',
type: 'GET',
contentType: 'application/json',
dataType: 'json',
success: function(response){
console.log(response)
response.forEach((res) => {
totalMachines.push(res[0])
})
console.log(totalMachines)
}
})
.then(() => {
// Fix for Selectize
$('#builder').on('afterCreateRuleInput.queryBuilder', function(e, rule) {
if (rule.filter.plugin == 'selectize') {
rule.$el.find('.rule-value-container').css('min-width', '200px')
.find('.selectize-control').removeClass('form-control');
}
});
$('#builder').queryBuilder(options)
})
It would be extremely helpful if someone could help me figure out how to properly configure this plugin, I've looked at every thread and haven't been able to figure it out.
Here is a simple example, using a local datasource, the namesList array
<script>
$(document).ready(function() {
let namesList = [{ id: '1', name: 'andrew' }, { id: '2', name: 'bob' }, { id: '3', name: 'charles' }, { id: '4', name: 'david' }];
let pluginConfig = {
preload: true,
valueField: 'id',
labelField: 'name',
searchField: 'name',
options: namesList,
items: ['2'],
allowEmptyOption: true,
plugins: ['remove_button'],
onInitialize: function () { },
onChange: function (value) {
console.log(value);
},
valueSetter: function (rule, value) {
rule.$el.find('.rule-value-container input')[0].selectize.setValue(value);
},
valueGetter: function (rule) {
var val = rule.$el.find('.rule-value-container input')[0].selectize.getValue();
return val.split(',');
}
}
let filterList = [{
id: 'age',
type: 'integer',
input: 'text'
},
{
id: 'id',
label: 'name',
name: 'name',
type: 'string',
input: 'text',
plugin: 'selectize',
plugin_config: pluginConfig
}];
let options = {
allow_empty: true,
operators: ['equal', 'not_equal', 'greater', 'greater_or_equal', 'less', 'less_or_equal'],
filters: filterList
}
$('#builder').queryBuilder(options);
// Fix for Selectize
$('#builder').on('afterCreateRuleInput.queryBuilder', function (e, rule) {
if (rule.filter.plugin == 'selectize') {
rule.$el.find('.rule-value-container').css('min-width', '200px').find('.selectize-control').removeClass('form-control');
}
});
});
Inside the ViewModel I've defined 2 stores and I'm using a gridpanel as view. Is there any chance to state if else condition for bind property inside gridpanel?
ViewModel:
stores: {
dataStore: {
model: 'MyApp.first.Model',
autoLoad: true,
session: true
},
listStore: {
model: 'MyApp.second.Model',
autoLoad: true,
session: true,
},
and on grid panel I want to do this condition;
Ext.define('MyApp.base.Grid', {
extend: 'Ext.grid.Panel',
// Currently binds directly to listStore
bind: '{listStore}',
// but I'm trying to implement a proper adjustment such as this;
// bind: function () {
// var username = localStorage.getItem('username');
// if (username === 'sample#adress.com') {'{dataStore}';} else {'{listStore}'}
// },
You can't use conditional expressions with bind, however, you can use ViewModel's formulas to select which store to use with grid. Here is example of such formula:
conditionalStore: function (get) {
var param = get('param');
if (param === 1) {
return get('simpsonsStore');
}
return get('griffinsStore');
}
And here is working fiddle, which you can play with: https://fiddle.sencha.com/#view/editor&fiddle/2eq2
You can use bindStore method of grid.
In this FIDDLE, I have created a demo using grid. I hope this will help/guide you to achieve your requirement.
CODE SNIPPET
Ext.application({
name: 'Fiddle',
launch: function () {
//defining store 1
Ext.define('Store1', {
extend: 'Ext.data.Store',
alias: 'store.store1',
autoLoad: true,
fields: ['name', 'email', 'phone'],
proxy: {
type: 'ajax',
url: 'data1.json',
reader: {
type: 'json',
rootProperty: ''
}
}
});
//defining store 2
Ext.define('Store2', {
extend: 'Ext.data.Store',
alias: 'store.store2',
autoLoad: true,
fields: ['name', 'email', 'phone'],
proxy: {
type: 'ajax',
url: 'data2.json',
reader: {
type: 'json',
rootProperty: ''
}
}
});
//defining view model
Ext.define('MyViewModel', {
extend: 'Ext.app.ViewModel',
alias: 'viewmodel.myvm',
stores: {
gridStore1: {
type: 'store1'
},
gridStore2: {
type: 'store2'
}
}
});
//creating grid
Ext.create({
xtype: 'grid',
title: 'Example of bind the store',
renderTo: Ext.getBody(),
viewModel: {
type: 'myvm'
},
columns: [{
text: 'Name',
dataIndex: 'name'
}, {
text: 'Email',
dataIndex: 'email',
flex: 1
}, {
text: 'Phone',
dataIndex: 'phone'
}],
tbar: [{
text: 'Load Store1',
handler: function (btn) {
var grid = this.up('grid');
grid.bindStore(grid.getViewModel().getStore('gridStore1'))
}
}, {
text: 'Load Store2',
handler: function (btn) {
var grid = this.up('grid');
grid.bindStore(grid.getViewModel().getStore('gridStore2'))
}
}]
});
}
});
I have a store with associated model and I need to include values of this associated model into selectfield component in Sencha Touch.
Here my parent model:
Ext.define('x.customer.model.CustomerModel', {
extend: 'Ext.data.Model',
requires:[
'x.customer.model.CustomerTemplateModel'
],
config: {
useCache: false,
idProperty: 'id',
fields: [
{
name: 'id',
type: 'string'
},
{
name: 'address',
type: 'string'
},
{
name: 'name',
type: 'string'
},
{
name: 'type',
type: 'int'
}
],
associations: [
{
type: 'hasMany',
associatedModel: 'Survey.customer.model.CustomerTemplateModel',
ownerModel: 'Survey.customer.model.CustomerModel',
associationKey: 'templates',
autoLoad: true,
name: 'templates'
}
]
}
});
and the children model:
Ext.define('x.customer.model.CustomerTemplateModel', {
extend: 'Ext.data.Model',
requires:[],
config: {
useCache: false,
rootProperty: 'templates',
fields: [
{
name: 'text',
type: 'string'
},
{
name: 'value',
type: 'string'
}
]
}
});
store:
requires: ['Survey.customer.model.CustomerModel'],
config: {
model: 'Survey.customer.model.CustomerModel',
proxy: {
type: 'ajax',
reader: {
type: 'json',
rootProperty: 'customers'
}
}
}
Currently the json has this structure:
{
"id": "00000001",
"address": "Antsy Road",
"name": "asfas",
"phone": "55555",
"openSurveys": 7,
"templates": [
{
"text": "123",
"value": "Template 1"
}
],
"type": 1,
"withSurveys": true
},
how to implement data included in the "templates" nested json in a selectfield?
thank you in advance
Once your store loaded and if you have one custommer:
var templatesData = []; // What will be inserted to the ComboBox
for (var i=0; i < custommers[0].get('templates').length; i++) { // Running threw the values and populating templatesData
var templateModel = custommers[0].get('templates')[i];
var templateCombo = {
text: templateModel.data.text,
value: templateModel.data.value
};
templatesData.push(templateCombo);
}
// Setting the values to the combobox
Ext.getCmp('myCombo').setStore(Ext.create("Ext.data.Store", {
model: 'x.customer.model.CustomerTemplateModel',
data :templatesData
}));
This is not a unique solution, you could create a new instance of store as well. Here is more information about how setting the "store" property for a combobox : http://docs.sencha.com/extjs/4.1.3/#!/api/Ext.form.field.ComboBox-cfg-store
I have created a tabpanel, with images as titles, and a custom component as html. Those custom components use stores, but I'm having an error when updating a single variable (status), all the variables change. Here I show the code:
SelectableButtons component:
Ext.require('Cat3.view.fsm.data.ButtonsStore');
/**
* Selectable button with image
*/
Ext.define('Cat3.view.fsm.components.SelectableButtons', {
extend: 'Ext.view.View',
cls: 'selectable-buttons',
alias: 'widget.selectable-buttons',
tpl: [
'<tpl for=".">',
'<div class="thumb-wrap button button-{status}">',
'<img src="resources/images/cards/{type}/{status}/{name}.png">',
'<img src="resources/images/icons/icon_mandatory.png" class="button-tick button-tick-{status}">',
'</div>',
'</tpl>'
],
// Set both to false if you want single select
multiSelect: true,
simpleSelect: true,
trackOver: false,
itemSelector: 'div.thumb-wrap',
listeners: {
select: function(ths, record, eOpts) {
record.set('status', 'active');
debugAmenaButtonStatus(this);
},
deselect: function(ths, record, eOpts) {
record.set('status', 'passive');
},
selectionchange: function(selection) {
this.refresh();
},
containerclick: function(ths, e, eOpts) {
return false; // Stops the deselection of items
}
},
initComponent: function() {
var store = Ext.create('Cat3.view.fsm.data.ButtonsStore');
this.setStore(store);
this.callParent(arguments);
}
});
debugAmenaButtonStatus = function(ref) {
ref.up().up().items.items.forEach(function(tab) { // Tab
console.log(tab.items.items[0].getStore().data.items[0].data.status); // Amena Button Status
});
};
SelectableButtonsCarousel component (Tab panel). It uses another store but it isn't related:
var cardsImagePath = 'resources/images/cards/';
var ImageModel = Ext.define('ImageModel2', {
extend: 'Ext.data.Model',
fields: [{
name: 'name',
type: 'string'
}, {
name: 'type',
type: 'string'
}, {
name: 'status',
type: 'string'
}, ]
});
var store = Ext.create('Ext.data.Store', {
model: 'ImageModel2',
data: [{
name: 'amena',
type: 'operator',
}, {
name: 'movistar',
type: 'operator',
}, {
name: 'orange',
type: 'operator',
}, {
name: 'simyo',
type: 'operator',
}, {
name: 'yoigo',
type: 'operator',
}, {
name: 'vodafone',
type: 'operator',
}]
});
Ext.define('Cat3.view.fsm.components.SelectableButtonsCarousel', {
extend: 'Ext.tab.Panel',
xtype: 'basic-tabs',
cls: 'selectable-buttons-carousel',
alias: 'widget.selectable-buttons-carousel',
store: store,
resizeTabs: false,
defaults: {
bodyPadding: 10,
layout: 'fit'
},
require: [
'Cat3.view.fsm.components.SelectableButtons',
'Cat3.view.fsm.data.ButtonsStore'
],
titleTpl: function(info) {
return '<img src="resources/images/cards/operator/' + info.status + '/' + info.name + '.png">';
},
listeners: {
render: function(p) {
var tabpanel = this;
this.store.data.items.forEach(function(item, index) {
item.data.status = index === 0 ? 'active' : 'passive';
var buttons = new Cat3.view.fsm.components.SelectableButtons();
tabpanel.add(Ext.create('Ext.Panel', {
id: 'tab-' + index,
title: tabpanel.titleTpl(item.data),
items: [ buttons ],
cls: item.data.status,
info: item.data,
listeners: {
render: function(p) {
console.log('render');
}
}
}));
});
tabpanel.setActiveTab(0);
},
tabchange: function(tabPanel, newCard, oldCard, eOpts) {
newCard.info.status = 'active';
newCard.setTitle(this.titleTpl(newCard.info));
newCard.items.items[0].refresh();
if (oldCard) {
oldCard.info.status = 'passive';
oldCard.setTitle(this.titleTpl(oldCard.info));
}
}
}
});
SelectableButtons Store:
var ImageModel = Ext.define('ImageModel', {
extend: 'Ext.data.Model',
fields: [
{name: 'name', type: 'string'},
{name: 'type', type: 'string'},
{name: 'status', type: 'string'},
]
});
Ext.define('Cat3.view.fsm.data.ButtonsStore', {
extend: 'Ext.data.Store',
model: 'ImageModel',
data: [
{name: 'amena', type: 'operator', status: 'passive'},
{name: 'movistar', type: 'operator', status: 'passive'},
{name: 'orange', type: 'operator', status: 'passive'},
{name: 'simyo', type: 'operator', status: 'passive'},
{name: 'yoigo', type: 'operator', status: 'passive'},
{name: 'vodafone', type: 'operator', status: 'passive'}
],
listeners: {
datachanged: function() {
console.log('store data changed');
}
}
});
All works fine, but when I select a button of SelectableButtons (one tab), the same button of each tab changes its status, and only the one selected of the active tab has to change. Any ideas why? I've checked each store is created separately and that each store has a different id.
Just an idea, for a better guess I'd need to see it working best at http://fiddle.sencha.com:
If "select one selects all", my first idea is that all buttons are just one button referred to from all places. One instance with different names.
Notice the line on your Cat3.view.fsm.components.SelectableButtons view:
initComponent: function() {
var store = Ext.create('Cat3.view.fsm.data.ButtonsStore');
...
}
You might wanna change it to
initComponent: function() {
var store = new Ext.create('Cat3.view.fsm.data.ButtonsStore');
...
}
This will create a new instance of Data Store for your view.
please I'm trying to get a list of all the contacts on my phone with the following code.
var App = new Ext.Application({
name: 'SmsthingyApp',
useLoadMask: true,
launch: function () {
Ext.data.ProxyMgr.registerType("contactstorage",
Ext.extend(Ext.data.Proxy, {
create: function(operation, callback, scope) {
},
read: function(operation, callback, scope) {
},
update: function(operation, callback, scope) {
},
destroy: function(operation, callback, scope) {
}
})
);
Ext.regModel("contact", {
fields: [
{name: "id", type: "int"},
{name: "givenName", type: "string"},
{name: "familyName", type: "string"},
{name: "emails", type: "auto"},
{name: "phoneNumbers", type: "auto"}
]
});
Ext.regStore('contacts',{
model: "contact",
proxy: {
type: "contactstorage",
read: function(operation, callback, scope) {
var thisProxy = this;
navigator.contacts.find(
['id', 'name', 'emails', 'phoneNumbers', 'addresses'],
function(deviceContacts) {
//loop over deviceContacts and create Contact model instances
var contacts = [];
for (var i = 0; i < deviceContacts.length; i++) {
var deviceContact = deviceContacts[ i ];
var contact = new thisProxy.model({
id: deviceContact.id,
givenName: deviceContact.name.givenName,
familyName: deviceContact.name.familyName,
emails: deviceContact.emails,
phoneNumbers: deviceContact.phoneNumbers
});
contact.deviceContact = deviceContact;
contacts.push(contact);
}
//return model instances in a result set
operation.resultSet = new Ext.data.ResultSet({
records: contacts,
total : contacts.length,
loaded : true
});
//announce success
operation.setSuccessful();
operation.setCompleted();
//finish with callback
if (typeof callback == "function") {
callback.call(scope || thisProxy, operation);
}
},
function (e) { console.log('Error fetching contacts'); },
{multiple: true}
);
}
}
});
Ext.regModel('Sms', {
idProperty: 'id',
fields: [
{ name: 'id', type: 'int' },
{ name: 'date', type: 'date', dateFormat: 'c' },
{ name: 'title', type: 'string' },
{ name: 'message', type: 'string' }
],
validations: [
{ type: 'presence', field: 'id' },
{ type: 'presence', field: 'title', message: 'Please select a contact for this sms.' }
]
});
Ext.regStore('SmsStore', {
model: 'Sms',
sorters: [{
property: 'date',
direction: 'DESC'
}],
proxy: {
type: 'localstorage',
id: 'sms-app-localstore'
},
getGroupString: function (record)
{
if (record && record.data.date)
{
return record.get('date').toDateString();
}
else
{
return '';
}
}
});
SmsthingyApp.views.ContactsList = new Ext.List({
id: 'ContactsList',
layout: 'fit',
store:'contacts',
itemTpl: '{givenName} {familyName}',
listeners: {'render': function (thisComponent)
{
SmsthingyApp.views.ContactsList.getStore().load();
}
},
onItemDisclosure: function (record) {
//Ext.dispatch({
// controller: SmsthingyApp.controllers.contacts,
// action: 'show',
// id: record.getId()
//});
}
});
SmsthingyApp.views.contactsListContainer = new Ext.Panel({
id: 'contactsListContainer',
layout: 'fit',
html: 'This is the sms list container',
items: [SmsthingyApp.views.ContactsList],
dockedItems: [{
xtype: 'toolbar',
title: 'Contacts'
}]
});
SmsthingyApp.views.smsEditorTopToolbar = new Ext.Toolbar({
title: 'Edit SMS',
items: [
{
text: 'Back',
ui: 'back',
handler: function () {
SmsthingyApp.views.viewport.setActiveItem('smsListContainer', { type: 'slide', direction: 'right' });
}
},
{ xtype: 'spacer' },
{
text: 'Save',
ui: 'action',
handler: function () {
var smsEditor = SmsthingyApp.views.smsEditor;
var currentSms = smsEditor.getRecord();
// Update the note with the values in the form fields.
smsEditor.updateRecord(currentSms);
var errors = currentSms.validate();
if (!errors.isValid())
{
currentSms.reject();
Ext.Msg.alert('Wait!', errors.getByField('title')[0].message, Ext.emptyFn);
return;
}
var smsList = SmsthingyApp.views.smsList;
var smsStore = smsList.getStore();
if (smsStore.findRecord('id', currentSms.data.id) === null)
{
smsStore.add(currentSms);
}
else
{
currentSms.setDirty();
}
smsStore.sync();
smsStore.sort([{ property: 'date', direction: 'DESC'}]);
smsList.refresh();
SmsthingyApp.views.viewport.setActiveItem('smsListContainer', { type: 'slide', direction: 'right' });
}
}
]
});
SmsthingyApp.views.smsEditorBottomToolbar = new Ext.Toolbar({
dock: 'bottom',
items: [
{ xtype: 'spacer' },
{
text: 'Send',
handler: function () {
// TODO: Send current sms.
}
}
]
});
SmsthingyApp.views.smsEditor = new Ext.form.FormPanel({
id: 'smsEditor',
items: [
{
xtype: 'textfield',
name: 'title',
label: 'To',
required: true
},
{
xtype: 'textareafield',
name: 'narrative',
label: 'Message'
}
],
dockedItems:[
SmsthingyApp.views.smsEditorTopToolbar,
SmsthingyApp.views.smsEditorBottomToolbar
]
});
SmsthingyApp.views.smsList = new Ext.List({
id: 'smsList',
store: 'SmsStore',
grouped: true,
emptyText: '<div style="margin: 5px;">No notes cached.</div>',
onItemDisclosure: function (record)
{
var selectedSms = record;
SmsthingyApp.views.smsEditor.load(selectedSms);
SmsthingyApp.views.viewport.setActiveItem('smsEditor', { type: 'slide', direction: 'left' });
},
itemTpl: '<div class="list-item-title">{title}</div>' +'<div class="list-item-narrative">{narrative}</div>',
listeners: {'render': function (thisComponent)
{
thisComponent.getStore().load();
}
}
});
SmsthingyApp.views.smsListToolbar = new Ext.Toolbar({
id: 'smsListToolbar',
title: 'Sent SMS',
layout: 'hbox',
items:[
{xtype:'spacer'},
{
id:'newSmsButton',
text:'New SMS',
ui:'action',
handler:function()
{
var now = new Date();
var smsId = now.getTime();
var sms = Ext.ModelMgr.create({ id: smsId, date: now, title: '', narrative: '' },'Sms');
SmsthingyApp.views.smsEditor.load(sms);
SmsthingyApp.views.viewport.setActiveItem('smsEditor', {type: 'slide', direction: 'left'});
}
}
]
});
SmsthingyApp.views.smsListContainer = new Ext.Panel({
id: 'smsListContainer',
layout: 'fit',
html: 'This is the sms list container',
dockedItems: [SmsthingyApp.views.smsListToolbar],
items: [SmsthingyApp.views.smsList]
});
SmsthingyApp.views.viewport = new Ext.Panel({
fullscreen: true,
layout: 'card',
cardAnimation: 'slide',
items:[
SmsthingyApp.views.contactsListContainer,
SmsthingyApp.views.smsListContainer,
SmsthingyApp.views.smsEditor
]
});
}
})
I'm using eclipse and LogCat tab keeps marking this red
02-08 11:11:58.741: E/Web Console(13886): Uncaught TypeError: Cannot read property 'contacts' of undefined at file:///android_asset/www/app.js:35
I'm guessing this has something to with why I can't see the contacts in the contactsListContainer.
Any help please?
I'm not a Sencha expert but I do know that this line:
var App = new Ext.Application({
will cause problems with PhoneGap as we also declare a variable called App. It would be better to change that line to be something like:
var myApp = new Ext.Application({
to avoid the name conflict.
If that doesn't resolve your problem I suggest you read over my post on searching contacts. I'd make sure I could successfully search for contacts before adding in Sencha.