ExtJs deleting element from store doesn't work - javascript

I'm working with ExtJs 6.2.0 and Java Spring MVC for the REST API.
I'm trying to delete an object from one of my store but I'm having a problem : instead of using my id named idCamp, extjs is using the field named id that contains an extjs generated id (for example: extModel47-1).
I'm working on the delete part but I didn't try to update a camp nor fetch one, but I think the configuration is the same for these three operations that need the id.
Here is my store:
Ext.define('XXXXXX.store.Camps', {
extend: 'Ext.data.Store',
alias: 'store.camps',
model: 'XXXXXX.model.Camp',
fields: [
'idCamp', // More irrelevant fields
],
autoLoad : true,
autoSync: true,
storeId: 'storeCamp',
proxy: {
type: 'rest',
idParam: 'idCamp',
url: // irrelevant,
reader: {
type: 'json',
rootProperty: 'data'
},
writer: {
type: 'json'
}
}
});
Here is my model:
Ext.define('XXXXXX.model.Camp', {
extend: 'Ext.data.Model',
idProperty: 'idCamp',
fields: [
{ name: 'idCamp', type: 'int' },
// More irrelevant fields
]
});
I also tried to put an idProperty inside the writer/reader inside the proxy but it didn't do anything.
Forgive my poor usage of the English language since I'm a French people.
Best regards,
Morony

The issue is using a combination of fields/model in your store definition. They are in competition with each other. Remove the fields definition.

Related

How to save, load and delete from database using a single ExtJS model?

Using ExtJS 6 one can have a store bind to the model and use the methods sync to save or load to load data.
I imagine that if a data is removed from store, upon calling sync the data will be removed from database too.
In my use case, I have different URLs and mandatory Ajax query fields for each action of create/update, load and delete data.
I have only seen examples showing load or save to storage, how can I declare the load, save and delete using Ajax in the same model?
Another doubt I have is that stores themselves can have a proxy, so they can perform those operations too, at least the load operation that I have seen in use. What's the difference between having these on the model or store? What's the best practice?
Example model from Sencha docs (is this only for read?):
Ext.define('MyApp.model.Base', {
extend: 'Ext.data.Model',
fields: [{
name: 'id',
type: 'int'
}],
schema: {
namespace: 'MyApp.model', // generate auto entityName
proxy: { // Ext.util.ObjectTemplate
type: 'ajax',
url: '{entityName}.json',
reader: {
type: 'json',
rootProperty: '{entityName:lowercase}'
}
}
}
});
Another example I found on https://examples.sencha.com/extjs/6.0.1/examples/classic/writer/writer.html using the proxy config, this seems more like what I would need as it specifies a URL for each operation:
var store = Ext.create('Ext.data.Store', {
model: 'Writer.Person',
autoLoad: true,
autoSync: true,
proxy: {
type: 'ajax',
api: {
read: 'app.php/users/view',
create: 'app.php/users/create',
update: 'app.php/users/update',
destroy: 'app.php/users/destroy'
},
reader: {
type: 'json',
successProperty: 'success',
root: 'data',
messageProperty: 'message'
},
writer: {
type: 'json',
writeAllFields: false,
root: 'data'
},
listeners: {
exception: function(proxy, response, operation){
Ext.MessageBox.show({
title: 'REMOTE EXCEPTION',
msg: operation.getError(),
icon: Ext.MessageBox.ERROR,
buttons: Ext.Msg.OK
});
}
}
},
listeners: {
write: function(proxy, operation){
if (operation.action == 'destroy') {
main.child('#form').setActiveRecord(null);
}
Ext.example.msg(operation.action, operation.getResultSet().message);
}
}
});
I believe I can have something like this in my case (this is just an example not tested!):
Ext.define('My.Person.Model', {
proxy: {
type: 'ajax',
api: {
read: 'http://myapiserver/getuser',
create: 'http://myapiserver/upsertuser',
update: 'http://myapiserver/upsertuser',
destroy: 'http://myapiserver/removeuser'
},
reader: {
type: 'json',
successProperty: 'success',
root: 'data',
messageProperty: 'message'
},
writer: {
type: 'json',
writeAllFields: false,
root: 'data'
},
// How can I have the parameters for each one?
extraParams : {
isuserUnderage : ' '
, query : '%'
}
}
});
I have no idea how to do this, specially specifying parameters for each type of Ajax request (read, create, update, destroy), I can have an upsert request that will send all fields, but the remove request will require only the ID, the get request can have optional fields for filtering, like filtering persons by name.
Example to be more clear of the problem.
Example data:
[
{
"id": "1",
"name": "Fred",
"age": 21,
"sex": "m"
},
{
"id": "2",
"name": "Susan",
"age": 12,
"sex": "f"
},
{
"id": "3",
"name": "Marcus",
"age": 22,
"sex": "m"
},
{
"id": "4",
"name": "Alex",
"age": 32,
"sex": "m"
}
]
Endpoints example:
Endpoints have parameters, these are mandatory, this means that calling an enpoint without a parameter will cause a server error, also passing a parameter that is not specified will cause a server error! If a parameter is not necessary one can pass a string with a single whitespace .
To read:
Endpoint: http://myapiserver/getuser?query={query}
Name is a filter by name, for example http://myapiserver/getuser?query=fred will bring users with name that has the string fred.
To write, we usually have an upsert, so it works for both insert and update:
Endpoint: http://myapiserver/upsertuser?id={id}&name={name}&age={age}&sex={sex}
So to update we can pass the ID: http://myapiserver/upsertuser?id=1&name=Frederick&age=21&sex=m and to insert we pass an empty string for ID: http://myapiserver/upsertuser?id= &name=Maurice&age=41&sex=m
To remove:
Endpoint: http://myapiserver/removeuser?id={id}
Example: http://myapiserver/removeuser?id=1, removes person with ID 1.
Because you say it's mandatory to use GETs with query params, I would encourage you to rethink your tech stack because the RESTful verbs really make it more clear what your action is, and you remove the actual action from your URL routes. However, I know sometimes this is totally out of our control, so I'll try my best here... I have to say, I've never experienced something like this, so I don't know if what I'm showing here is a best practice.
I can't show a true implementation because Sencha Fiddle is a simple sandbox, not meant for actual server-side implementations. I'm also assuming that you're using the classic toolkit, but if you need it in modern, it's a fairly easy port that you can do.
I prefer the proxy inside of the model for several reasons... if I need to use this model in several different stores throughout my app, then each store will inherit the same proxy. If I want to use the same model, but I don't want its proxy, I can simply override it when defining the store. Also, if the proxy doesn't exist on the model, then the framework assumes what your URL should be, which doesn't work when I want to use models individually.
I think I've come up with what you're asking for in this Fiddle. Really the core of what you want is in GETUser.js.
// We need to create our own proxy that will handle this for us
Ext.define('AjaxGet', {
extend: 'Ext.data.proxy.Ajax',
alias: 'proxy.ajaxGet',
// Per your requirement, we want to send individual requests
batchActions: false,
createOperation: function (action, config) {
// This means we're doing an action against one of our records
if (config && config.records) {
if (action === 'destroy') {
config.params = config.records[0].getDeleteParams();
} else if (action === 'create' || action === 'update') {
config.params = config.records[0].getUpsertParams();
}
}
return this.callParent(arguments);
}
});
// This is the desired, "GET" User model that uses GETs and query params for all actions
Ext.define('GETUser', {
extend: 'Ext.data.Model',
idProperty: 'Id',
fields: [{
name: 'Name',
type: 'string'
}, {
name: 'Id',
type: 'int'
}, {
name: 'Age',
type: 'int'
}, {
name: 'Sex',
type: 'string'
}],
proxy: {
type: 'ajaxGet',
api: {
read: 'Users',
create: 'upsertuser',
update: 'upsertuser',
destroy: 'removeuser'
},
actionMethods: {
create: 'GET',
update: 'GET',
destroy: 'GET'
}
},
getUpsertParams: function () {
const data = this.getData();
// Means this record hasn't been saved, so we're in the CREATE state
if (this.phantom) {
// We don't want to send the ID with what the framework sets as the ID
data.Id = undefined;
}
return data;
},
getDeleteParams: function () {
return {
Id: this.get('Id')
};
}
});
So what I ended up doing was creating a custom proxy that overrides the createOperation method to check which operation we're doing... based on that operation, we use the methods in the model to retrieve the params we want to send to the API. You need actionMethods in the proxy because otherwise, they default to POSTs.

sencha extjs run when storemanager has finished loading?

While developping an application I run some code on application launch:
Ext.application({
extend: 'TestApp.Application',
name: 'TestApp',
requires: [
'TestApp.*'
],
// The name of the initial view to create.
launch: async function () {
const store_org = Ext.getStore('Organizations');
const store_event = Ext.getStore('Events');
//more stuff here
}
});
Both stores are well defined:
Ext.define('TestApp.store.Organization', {
extend: 'Ext.data.Store',
storeId: 'Organizations',
alias: 'store.organizations',
model: 'TestApp.model.Organization',
autoLoad: true,
pageSize: 0,
proxy: {
type: 'ajax',
url: TestApp.util.Config.getHost() + '/organization/get-organizations',
withCredentials: true,
reader: {
type: 'json',
rootProperty: '',
},
},
});
I do notice however that while launching the Ext.getStore() function always returns undefined for any store. Is there any way I can "delay" this to the point where the storemanager has fully loaded and these stores do no longer return undefined? (The stores themselves won't be filled with data...).
Just add this to the Ext.application class or to the TestApp.application (which is better)
stores:['TestApp.store.Organization'],
this is an array of all your stores,so if you need to add more just use a comma and write the class path name of the new file
Here is a working example Fiddle

Save nested form data back to server in ExtJS

I have a Model that contains an association to another Model. I am able to display the nested data into a form by using the mapping attribute on the field. Example:
Ext.define('Example.model.Request', {
extend: 'Ext.data.Model',
fields: [
{
name: 'id',
type: Ext.data.Types.NUMBER,
useNull: false
}
{
name: 'plan_surveyor',
mapping: 'plan.surveyor',
type: Ext.data.Types.STRING
}
],
associations: [
{type: 'hasOne', associationKey: 'plan', getterName:'getPlan', model: 'Specs.model.Plan'}
],
proxy: {
type: 'direct',
api: {
read: requestController.load,
update: requestController.update,
},
reader: {
type: 'json',
root: 'records'
},
writer: {
type: 'json',
writeAllFields: true,
nameProperty: 'mapping'
}
}
});
Using this method, I can display the plan.surveyor value in the form by reference plan_surveyor. I call Form.loadRecord(model) to pull the data from the model into the form.
However, now that I'm trying to send the data back to the server, I get the error:
Error performing action. Please report the following: "Unrecognized field "plan.surveyor"
I am attempting to save to the server by first calling Form.updateRecord(model), then model.save(). Is there a way to have the Writer understand that 'plan.surveyor' is not a property name but instead to properly handle nesting?
Am I doing this the right way to start with, or should I just be handling the setting of the form data and loading back into the model in a more manual fashion? It seems that nested data is not all that well supported in general - any recommendations?
Ext.define('Example.model.Request', {
extend: 'Ext.data.Model',
fields: [
{
name: 'id',
type: Ext.data.Types.NUMBER,
useNull: false
}
{
name: 'plan_surveyor',
mapping: 'plan.surveyor',//change to 'plan_surveyor'
type: Ext.data.Types.STRING
}
],
change that show in comment ,because data index is given in above format because ur give ur format thata time that is not dataindex it's a column or extjs preparatory ,so please change that may it's work well
it's not work u will send hole code

Map ExtJS Proxy AJAX response to model

UPDATE:
here is my reader/store - not sure what to add to the reader to make this work
Ext.define('YT.store.Videos', {
extend: 'Ext.data.Store',
model: 'YT.model.Video',
autoLoad: true,
proxy: {
type: 'ajax',
url: 'https://gdata.youtube.com/feeds/api/videos',
reader: {
type: 'json',
root: 'feed',
record: 'entry',
successProperty: 'success'
},
listeners: {
exception: function(store, response, app){
console.log('exception...');
console.log(response);
}
}
}
});
Here is my model:
Ext.define('YT.model.Video', {
extend: 'Ext.data.Model',
autoLoad: true,
fields: [
'title',
'published',
'content'
]
});
Here is a sample response:
{
version: '1.0',
encoding: 'UTF-8',
feed: {
junk: 'blahblahblahblah',
entry: [
title: {
$t: 'title'
},
content: {
encoding: 'flash/application',
src: 'http://youtube.com/watch?q=someCatVideo'
},
published: {
$t: '12-28-2012'
}
]
}
}
I'm not sure how to reconcile the two.
I've tried...
Ext.define('YT.model.Video', {
extend: 'Ext.data.Model',
autoLoad: true,
fields: [
{name: 'title', mapping: 'title.$t'},
{name: 'published', mapping: 'published.$t'},
{name: 'content', mapping: 'content.src'}
]
});
Bonus:
Definitely looking for tips on how to debug the implementation of these techniques, I'm rather new to JavaScript MVC.
You are on the right track with mapping, but you also need to define a reader where you specify where your records are in the JSON you get back - see official docs for good examples.
Incidentally, who thought $t was a good idea for a map key?
EDIT:
After your edits here is your working code:
http://jsfiddle.net/dbrin/mSJg3/
As far as debugging: the key for your issue was to clearly see the payload from the service (I used FireBug to inspect JSON object returned). Then mapping your Model class to fit the JSON object through mapping attribute and finally adjust JSON reader to let it know how to navigate your JSON payload (see my code example).
Once your exception listeners are not firing anymore (see code example for those again) that means you got your data into the store. To actually see the data I used Illuminations firebug plugin to inspect the data store. I saw only one record. What the heck? I observed id Property being set to some funky URL. This was happening by default as i did not specify an id attribute on the model. I resorted to spacifying idProperty to undefined to get around this funky behavior (see model code).
I used jsfiddle to quickly iterate through changes and running to see errors in the reader. Once I had no more errors I had jsfiddle show me the app I just build in such a way that I could use Illuminations plugin by using the show/light url: http://jsfiddle.net/dbrin/mSJg3/show/light/

ExtJS4 Changing data store parameters

If I have a data store on a grid like so:
store = Ext.create('Ext.data.Store', {
fields: [{
name: 'id'
}, {
name: 'filename'
}
// other fields here ...
],
proxy: {
type: 'ajax',
url: 'http://myniftyurl.com/blah',
simpleSortMode: true,
reader: {
type: 'json',
totalProperty: 'total',
root: 'result'
},
extraParams: {
'limit': Ext.get('itemsPerPage').getValue(),
'to': Ext.get('to_date').getValue()
// other params
}
},
model: 'Page',
remoteFilter: true,
remoteSort: true
});
The 'limit' and 'to' value will change based on user input, therein lies the problem. The data store keeps using the original parameters instead of the new inputs. How can I fix this?
Thanks in advance!
I normally load my grids manually by executing the store.load() in the controller.
That way prior to it I can change the store's params like so:
//getForm() retrieves the Ext.basic.Form (from Ext.panel.Form)
var params = this.getForm().getValues();
//Write over
grid.getStore().getProxy().extraParams = params;
//load
grid.getStore().load();
I'm using buffered grids which required a decent amount of rework to get completely working in 4.0.7. But that should work for you.
Another options is to use a beforeload listener but I'm not sure if changing the extraParams by then will do anything. You may be able to modified the Ext.data.Operation object that gets passed to the event handler?
Let me know how that works out for you.
Good luck!

Categories