Sencha ExtJS RESTful grid example confusion - rest

I am very confused by the Sencha documentation for ExtJS. The documentation begins with a Getting Started guide which highlights and illustrates the importance on a suitable structure for the classes and source code of your application. But the provided examples then break all the conventions laid down by the Getting Started guide. Instead of code being broken down into appropriate Model, Store, View, etc. class files the examples are provided as a single file with example source code which is not easily re-usable in separate source files.
I started by following the Portal example (http://docs.sencha.com/ext-js/4-1/#!/example/portal/portal.html) as this is the sort of application I want to create. I wanted to enhance the Portal example and add in a screen which would display a grid and use a RESTful web service as the data backend. I have created the backend I just want to create the front-end. So I looked at the RESTful example (http://docs.sencha.com/ext-js/4-1/#!/example/restful/restful.html)
I have tried to copy the RESTful example into the recommended pattern of seperate classes e.g. Model, Store, View:
Model:
Ext.define('MyLodge.model.Member', {
extend: 'Ext.data.Model',
fields: [
{name: 'name', type: 'string'},
{name: 'email', type: 'string'},
{name: 'href', type: 'string'}
]
});
Store:
Ext.require('MyLodge.model.Member');
Ext.define('MyLodge.store.Members', {
autoLoad: true,
autoSync: true,
model: 'MyLodge.model.Member',
proxy: {
type: 'rest',
url: 'http://localhost:8888/rest/memberapi/members' ,
reader: {
type: 'json',
root: 'data'
},
writer: {
type: 'json'
}
},
listeners: {
write: function(store, operation){
var record = operation.getRecords()[0],
name = Ext.String.capitalize(operation.action),
verb;
if (name == 'Destroy' ) {
record = operation.records[0];
verb = 'Destroyed';
} else {
verb = name + 'd';
}
Ext.example.msg(name, Ext.String.format( "{0} member: {1}", verb, record.getId()));
}
}
});
View:
Ext.define('MyLodge.view.content.MemberGrid', {
extend: 'Ext.grid.Panel',
alias: 'widget.membergrid',
initComponent: function(){
var store = Ext.create('MyLodge.store.Members' );
Ext.apply( this, {
height: this.height,
store: store,
stripeRows: true,
columnLines: true,
columns: [{
id : 'name',
text : 'Name',
flex: 1,
sortable : true,
dataIndex: 'name'
},{
text : 'E-Mail',
width : 150,
sortable : true,
dataIndex: 'email'
},{
text : 'Href',
width : 200,
sortable : true,
dataIndex: 'href'
}],
dockedItems: [{
xtype: 'toolbar',
items: [{
text: 'Add',
iconCls: 'icon-add',
handler: function(){
// empty record
store.insert(0, new MyLodge.model.Member());
rowEditing.startEdit(0, 0);
}
}, '-', {
itemId: 'delete',
text: 'Delete',
iconCls: 'icon-delete',
disabled: true,
handler: function(){
var selection = grid.getView().getSelectionModel().getSelection()[0];
if (selection) {
store.remove(selection);
}
}
}]
}]
});
this.callParent(arguments);
}
});
But I am not sure where to put the code to control the grid row selection and enable the Delete button:
grid.getSelectionModel().on('selectionchange', function(selModel, selections){
grid.down('#delete').setDisabled(selections.length === 0);
});
Also when I press the Add button I get the following error:
Uncaught TypeError: Object [object Object] has no method 'insert'.
Any help would be appreciated.

You are having scoping issues. Basically the variable store is defined only in the initComponent function and therefore of local function scope.
Your handler function has it's own scope. It is firing in the scope of the toolbar button. So if you say this in the handler it would refer to the button. Hence you can say this.up('panel').store - and that gives you the correct reference to the store backing your grid panel.
Another advice is not to implement everything at once. Write a little bit to see if it works and then add to it little by little.

RE: the docs examples, I agree that it's frustrating, but there's not many options. Having a fully-MVC-style implementation of each example would not only be onerous to produce, but would also probably make point of the example get lost in the structure.
RE: your question about the where to "put" the code to control the grid, I would recommend setting up a controller with listeners for the events on the grid in the control() section. This will let you decouple the handling of the events that are fired by your grid from the view itself.

Related

Unable to Validate Field in Shopware Backend Form

I am trying to validate a field in my ExtJs file by sending a hit to my controller.. all works fine and I get the result back.. but the problem is that I am unable to get the me.article in the code as it shows undefined so my logic in the controller does not return the result as expected.
Any help would be highly appreciated.
Note: this only happens for Shopware v.5.4.6. It works fine for Shopware 5.2.
Shopware.apps.Article.view.detail.Base.prototype.createLeftElements = function() {
var me =this, articleId = null, additionalText = null;
console.log('article', me.article);
if (me.article instanceof Ext.data.Model && me.article.getMainDetail().first() instanceof Ext.data.Model) {
articleId = me.article.getMainDetail().first().get('id');
additionalText = me.article.getMainDetail().first().get('additionalText');
}
me.nameField = Ext.create('Ext.form.field.Text', {
name: 'name',
dataIndex: 'name',
fieldLabel: me.snippets.name,
allowBlank: false,
enableKeyEvents:true,
checkChangeBuffer:700,
labelWidth: 155,
anchor: '100%',
vtype:'remote',
validationUrl: '{url controller="MyController" action="check"}',
validationRequestParam: articleId,
validationErrorMsg: '{s name=detail/base/number_validation}Validation Message.{/s}'
});
// .. some code here which is irrelevant
return [
me.supplierCombo,
me.nameField,
me.mainDetailAdditionalText,
me.numberField,
{
xtype: 'checkbox',
name: 'active',
fieldLabel: me.snippets.active,
inputValue: true,
uncheckedValue:false
},
{
xtype: 'checkbox',
name: 'isConfigurator',
fieldLabel: me.snippets.configurator.fieldLabel,
inputValue: true,
uncheckedValue:false
}
];
};
I am not that deep into ExtJS, but perhaps the CSRF-protection causes this problem? Perhaps you need to whitelist your controller.
https://developers.shopware.com/developers-guide/csrf-protection/#addition-to-backend-token-validation

ExtJs 6 Store not visible in Grid

I'm trying to port existing application from ExtJs 4.2.1 to 6.0.1
The problem that in debugger I see that grid has 'ext-empty-store' store instead of 'store.accounting.Quota'
I can load the store directly in panel activation listener by doing
var store = Ext.data.StoreManager.lookup('QuotaKPI.store.accounting.Quota');
store.load();
In firebug I see request and perfect json in response but nothing appears in the grid
Here are code snippets
app/store/accounting/Quota.js
Ext.define('QuotaKPI.store.accounting.Quota', {
extend: 'Ext.data.JsonStore',
model: 'QuotaKPI.model.accounting.QuotaModel',
alias: 'store.accounting.Quota',
storeId: 'QuotaKPI.store.accounting.Quota',
autoLoad: false,
proxy: {
...
}
});
app/view/accounting/QuotaGrid.js
Ext.define('QuotaKPI.view.accounting.QuotaGrid', {
extend: 'Ext.grid.Panel'
,xtype: 'QuotaGrid'
,store: Ext.data.StoreManager.lookup('QuotaKPI.store.accounting.Quota')
,columns: [
...
]
,dockedItems : [
,{xtype: 'pagingtoolbar',
dock:'bottom',
store: Ext.data.StoreManager.lookup('QuotaKPI.store.accounting.Quota'),
displayInfo: true,
displayMsg: 'Displaying Quota Details {0} - {1} of {2}',
emptyMsg: "No Quota to display"
}
]
,initComponent: function() {
this.callParent(arguments);
}
});
Store, model and grid declared in controller
Ext.define('QuotaKPI.controller.accounting.AccountingController', {
extend: 'Ext.app.Controller',
stores: ['accounting.Quota'],
models: ['accounting.QuotaModel'],
views: ['accounting.QuotaGrid']
...
And controller itself listed in app.js
Ext.application({
name: 'QuotaKPI',
controllers: [
'accounting.AccountingController'
],
init: function(app){
},
autoCreateViewport: true
});
Any help, please?
I know storeId doesn't accept some character (for example "-"), I don't know for dot... in any case I suggest to make it simple.
Try "myStoreId"
In addition you can try:
Ext.define('QuotaKPI.view.accounting.QuotaGrid', {
extend: 'Ext.grid.Panel'
,xtype: 'QuotaGrid'
,store: "myStoreId",
,columns: [
...
]
,dockedItems : [
,{xtype: 'pagingtoolbar',
dock:'bottom',
store: "myStoreId",
displayInfo: true,
displayMsg: 'Displaying Quota Details {0} - {1} of {2}',
emptyMsg: "No Quota to display"
}
]
,initComponent: function() {
this.callParent(arguments);
}
});
In addition I suggest to ensure you have a proper schema configuration (see http://docs.sencha.com/extjs/6.0/6.0.1-classic/#!/api/Ext.data.schema.Schema)
And then, you could try also with ViewModel instead of storeId (see http://docs.sencha.com/extjs/5.0/application_architecture/view_models_data_binding.html)
Don't hesitate to do a https://fiddle.sencha.com/#home
Good Luck!
Transition is not easy...

Sencha touch 2 filterby() not updating records

I have a nested list on one of the pages of a Tabbed Panel app that is pulling data from "offices.json"
I should like to be able to filter this list when a user clicks on a toolbar button. However my filterBy() function doesn't update the store and the list of offices I can see, even though I can see in the console it is iterating the records and finding a match. What am I doing wrong?
(And yes I have tried doing s.load() both before and after the filterBy to no avail!)
toolbar:{
items:[{
text: 'Near you',
id: 'btnNearYou',
xtype: 'button',
handler: function() {
s = Ext.StoreMgr.get('offices');
s._proxy._url = 'officesFLAT.json';
console.log("trying to filter");
s.filterBy(function(record) {
var search = new RegExp("Altrincham", 'i');
if(record.get('text').match(search)){
console.log("did Match");
return true;
}else {
console.log("didnt Match");
return false;
}
});
s.load();
}
}]
For the record I'm defining my store like so:
store: {
type: 'tree',
model: 'ListItem',
id: 'offices',
defaultRootProperty: 'items',
proxy: {
type: 'ajax',
root: {},
url: 'offices.json',
reader: {
type: 'json',
rootProperty: 'items'
}
}
}
No need to recreate the regex each time, cache it outside.
You can simplify the code a lot (see below).
Why are you calling load directly after? That's going to send it to the server and it will just retrieve the same dataset.
toolbar: {
items: [{
text: 'Near you',
id: 'btnNearYou',
xtype: 'button',
handler: function() {
s = Ext.StoreMgr.get('offices');
s._proxy._url = 'officesFLAT.json';
var search = /Altrincham/i;
s.filterBy(function(record) {
return !!record.get('text').match(search);
});
}
}]
}

Custom proxies on Stores and Models seems inconsistent (and does not work on Models)

Am using Extjs 4, and have created a custom Rest Proxy to handle communication with my Zend backend api.
(See post http://techfrere.blogspot.com/2011/08/linking-extjs4-to-zend-using-rest.html)
When using a Store to handle communication, I was using Ext.require to load the proxy, and then referenced the proxy on the type field and all was good and it loaded my data: as per:
Ext.require('App.utils.ZendRest');
...
proxy : {
type : 'zest', // My custom proxy alias
url : '/admin/user'
...
}
I then decided to try to use the proxy directly on a model... and no luck. The above logic does not work.
Problems
1. When referencing zest, it does not find the previously loaded ZendRest class (aliased to proxy.zest)
2. It tries to load the missing class from App.proxy.zest (which did not exist.)
So I tried moving my class to this location and renaming to what it seemed to want. No luck.
It loads the class, but still does not initialize the app... I get no errors anywhere so v difficult to figure out where the problem is after this...
For now it seems I will have to revert to using my Zend Rest proxy always via the Store.
Question is... has anyone else seen the behavior? Is it a bug, or am I missing something?
Thanks...
Using your proxy definition, I've managed to make it work.
I am not sure why it doesn't work for you. I have only moved ZendRest to Prj.proxy namespace and added requires: ['Prj.proxy.ZendRest'] to the model.
Code:
// controller/Primary.js
Ext.define('Prj.controller.Primary', {
extend: 'Ext.app.Controller',
stores: ['Articles'],
models: ['Article'],
views: ['article.Grid']
});
// model/Article.js
Ext.define('Prj.model.Article', {
extend: 'Ext.data.Model',
fields: [
'title', 'author', {
name: 'pubDate',
type: 'date'
}, 'link', 'description', 'content'
],
requires: ['Prj.proxy.ZendRest'],
proxy: {
type: 'zest',
url: 'feed-proxy.php'
}
});
// store/Articles.js
Ext.define('Prj.store.Articles', {
extend: 'Ext.data.Store',
autoLoad: true,
model: 'Prj.model.Article'
});
// proxy/ZendRest.js
Ext.define('Prj.proxy.ZendRest', {
extend: 'Ext.data.proxy.Ajax',
alias : 'proxy.zest',
appendId: true,
batchActions: false,
buildUrl: function(request) {
var me = this,
operation = request.operation,
records = operation.records || [],
record = records[0],
format = me.format,
reqParams = request.params,
url = me.getUrl(request),
id = record ? record.getId() : operation.id;
if (me.appendId && id) {
if (!url.match(/\/$/)) {
url += '/';
}
url += 'id/' + id;
}
if (format) {
reqParams['format'] = format;
}
/* <for example purpose> */
//request.url = url;
/* </for example purpose> */
return me.callParent(arguments);
}
}, function() {
Ext.apply(this.prototype, {
actionMethods: {
create : 'POST',
read : 'GET',
update : 'PUT',
destroy: 'DELETE'
},
/* <for example purpose> */
reader: {
type: 'xml',
record: 'item'
}
/* </for example purpose> */
});
});
Here is working sample, and here zipped code.

Simple login form with SenchaTouch

Just diving into SenchaTouch which seems very promising.
I'm building my first application, a simple login form check source http://pastebin.com/8Zddr9cj
I'm looking for a way to do the following things :
Display 'nice' error message when the login/password is wrong. Can be in red to replace the 'Please enter your credentials); i don't know how to access this property.
If login success, close the form and load the application (probably another js file).
Quite simple, but i'm a newbie to this,
1) Fieldset has a method called setInstructions which you can call to update the instructions. So, you could specify an id configuration in your field set, then use that later on when you want to update the instructions.
...
items: [
{
xtype: 'fieldset',
id: 'fieldset',
title: 'Login',
instructions: 'Please enter your credentials',
defaults: {
required: true,
labelAlign: 'left',
labelWidth: '40%'
},
items: [
{
xtype: 'emailfield',
name : 'email',
label: 'Email',
placeHolder: 'your#email.com',
useClearIcon: true
}, {
xtype: 'passwordfield',
name : 'password',
label: 'Password',
useClearIcon: false
}]
}
],
...
//wherever you want to update the instructions
var fieldset = Ext.getCmp('fieldset');
fieldset.setInstructions('My new instructions!');
2) Here is a simple demo of this:
//create a panel, which is full screen, and will contain your form, and another item
//which you want to show at some point
var wrapper = new Ext.Panel({
fullscreen: true,
layout: 'card',
//my two items
items: [
form,
{
xtype: 'panel',
html: 'my second panel, which is not visible on render.'
}
]
});
//change the active card/item, when you need to
wrapper.setActiveItem(1); //starts at 0
Make sure you remove fullscreen from your form, as it is no longer fullscreen (this wrapper panel is).