Using dgrid/dstore's REST store with a filter - dojo

I would like to extend dstore/Rest to take a parameter that is used to filter the store. This article suggests this is the desired method to alter the query of a dstore: http://www.sitepen.com/blog/2014/11/17/introducing-dstore/
Example:
new MyExtendedRestStore({color: 'red'});
I would like the internals of MyExtendedRestStore to alter the GET query so that color would now be set in the filter so any refresh calls would stick to adding color=red to the query. If I understand this correctly, it should also force the dstore/Trackable mixin to obey the filter.

In dgrid 0.4, instances using OnDemandList or Pagination can accept any collection - whether it be a root store, or a collection generated as a result of performing operations on that store. filter is one such operation.
In your case you state you want the grid to always show only red items, so you could very easily pass the grid a filtered collection, and no custom extension of Rest is required:
var TrackableRestStore = declare([ Rest, Trackable ]);
var store = new TrackableRestStore({ target: '...' });
var filteredCollection = store.filter({ color: 'red' });
var grid = new OnDemandGrid({
collection: filteredCollection,
columns: ...
});
This is also discussed towards the end of dgrid's Grids and Stores tutorial.

Related

Getting id from row clicked on a dgrid List

I just started using dgrid, and going through the dTunes sample, I'm unable to find the id associated with each row in the list. This is pretty remedial on my part, but how would I also get the id I sent from the datasource?
define([
'require',
'dgrid/List',
'dgrid/OnDemandGrid',
'dgrid/Selection',
'dgrid/Keyboard',
'dgrid/extensions/ColumnHider',
'dojo/_base/declare',
'dojo/_base/array',
'dojo/Stateful',
'dojo/when',
'dstore/RequestMemory',
'put-selector/put',
'dojo/domReady!'
], function (require, List, Grid, Selection,
Keyboard, Hider, declare, arrayUtil, Stateful,
when, RequestMemory, put) {
var cstsNode = put(listNode, 'div#cstsCars');
...
var cstsList = new TunesList({}, cstsNode);
var dataCSTS = new RequestMemory({ target: require.toUrl('./dataCSTS.json') });
...
dataCSTS.fetch().then(function (cars) {
cstsCars = arrayUtil.map(cars, pickField('Description'));
cstsCars.unshift('All (' + cstsCars.length + ' CSTS Cars' + (cstsCars.length !== 1 ? 's' : '') + ')');
cstsList.renderArray(cstsCars);
});
...
cstsList.on('dgrid-select', function (event) {
var row = event.rows[0];
console.log(row.id); // shows row number. How do I get the real id or other fields?
console.log(row.data); // shows row text that is displayed ("sample text 1")
console.log(row.data.id); // undefined
});
Here is a snippet of sample data like I'm supplying:
[{"id":"221","Description":"sample text 1"},
{"id":"222","Description":"sample text 2"},
{"id":"223","Description":"sample text 3"}]
I'd like to see the id. Instead, row.id returns 1,2 and 3, ie the row numbers (or id dgrid created?).
You haven't really shown a complete example, but given that you're using a store anyway, you'd have a much easier time if you let dgrid manage querying the store for you. If you use dgrid/OnDemandList (or dgrid/List plus dgrid/extensions/Pagination), you can pass your dataCSTS store to the collection property, it will render it all for you, and it will properly pick up your IDs (since Memory, and RequestMemory by extension, default to using id as their identity property).
The most appropriate place to do what you're currently doing prior to renderArray would probably be in the renderRow method if you're just using List, not Grid. (The default in List just returns a div with a text node containing whatever is passed to it; you'll be passing an object, so you'd want to dig out whatever property you actually want to display, first.)
If you want a header row, consider setting showHeader: true and implementing renderHeader. (This is false in List by default, but Grid sets it to true and implements it.)
You might want to check out the Grids and Stores tutorial.
I think the problem might be that I was modeling my code based on the dTunes sample code, which has 3 lists that behave a little differently than a regular grid.
For now, I'm using the cachingStore that is available in the lists. So the way I get the id:
cstsList.on('dgrid-select', function (event) {
var row = event.rows[0];
var id = storeCSTS.cachingStore.data[row.id - 1].id; // -1 because a header was added
console.log(id);
});
I'm not sure whether this will work if I ever try to do sorting.

AngularJS: Take a single item from an array and add to scope

I have a ctrl that pulls a json array from an API. In my code I have an ng-repeat that loops through results.
This is for a PhoneGap mobile app and I'd like to take a single element from the array so that I can use it for the page title.
So... I'm wanting to use 'tool_type' outside of my ng-repeat.
Thanks in advance - I'm just not sure where to start on this one.
Example json data
[{ "entry_id":"241",
"title":"70041",
"url_title":"event-70041",
"status":"open",
"images_url":"http://DOMAIN.com/uploads/event_images/241/70041__small.jpg",
"application_details":"Cobalt tool bits are designed for machining work hardening alloys and other tough materials. They have increased water resistance and tool life. This improves performance and retention of the cutting edge.",
"product_sku":"70041",
"tool_type": "Toolbits",
"sort_group": "HSCo Toolbits",
"material":"HSCo8",
"pack_details":"Need Checking",
"discount_category":"102",
"finish":"P0 Bright Finish",
"series_description":"HSS CO FLAT TOOLBIT DIN4964"},
..... MORE .....
Ctrl to call API
// Factory to get products by category
app.factory("api_get_channel_entries_products", function ($resource) {
var catID = $.url().attr('relative').replace(/\D/g,'');
return $resource(
"http://DOMAIN.com/feeds/app_productlist/:cat_id",
{
cat_id: catID
}
);
});
// Get the list from the factory and put data into $scope.categories so it can be repeated
function productList ($scope, api_get_channel_entries_products, $compile) {
$scope.products_list = [];
// Get the current URL and then regex out everything except numbers - ie the entry id
$.url().attr('anchor').replace(/\D/g,'');
$scope.products_list = api_get_channel_entries_products.query();
}
Angular works as following:
Forgiving: expression evaluation is forgiving to undefined and null, unlike in JavaScript, >where trying to evaluate undefined properties can generate ReferenceError or TypeError.
http://code.angularjs.org/1.2.9/docs/guide/expression
so you only need to write:
<title>{{products_list[0].tool_type}}</title>
if there is a zero element the title will be the tool_type, if not, there is no title.
Assuming you want to select a random object from the list to use something like this should work:
$scope.product-tool_type = products_list[Math.floor(Math.random()*products_list.length)].tool_type
Then to display the result just use
<h1>{{product-tool_type}}</h1>
Or alternatively:
<h1>{{products_list[Math.floor(Math.random()*products_list.length)].tool_type}}</h1>

Sencha Touch 2: Load a List from a store.queryBy result

I had a List that used to work when it was bound directly to a store but now I want that list to get it's data from a queryBy on the original store.
Looking at the documentation is seems like setItems should do what I want.
var myStore = Ext.getStore('myStoreData');
var myData = myStore.queryBy(function(item) {
return item.get('status') !== null;
});
// At this point myData looks valid and has the data I want.
// Ext.apply.create.Class {all: Array[5], items: Array[5], keys: Array[5], indices: Object, map: Object…}
Ext.getCmp('myListComponent').setItems(myData.items);
I keep getting the error "Object [object Object] has no method 'getItemId'". I tried various other incantations but without success. I also took a look at setData and add but without success.
========================
After getting Thiem's answer I just ended up creating a function that would create a filtered copy of an existing store and then just setting the List store to that. Code below for others edification...
storeCopy: function(store, filterBy) {
var records = [];
var allRecords = null;
if(filterBy)
allRecords= store.queryBy(filterBy);
else
allRecords= store.queryBy(function(){return true;});
allRecords.each(function(r){
var rec = r.copy();
rec.setId(r.getId());
records.push(rec);
});
var store2 = new Ext.data.Store({
recordType: store.recordType
});
store2.add(records);
return store2;
},
Thanks all.
setItems method does a totally different thing. For example, says you have an Ext.Container which consists of a form, some fields, and some interaction buttons. These things are call child components, or items of the container. They are oftenly declared in the items config of the parent container and setItems is designed to programmatically set the value of that config. So it has nothing to do with the store logic.
In your situation, here is one of the solutions:
Create a store instance which contains filtered data.
Use this command: yourList.setStore('yourFilteredStore')
And it should reload... hope this helps

how to select single column data in infragistics igniteui grid

how to select data of single column from a grid data.
The grid data is passed as following:
var url = "/Main/Grid?tbname="+parameter;
var jsonp = new $.ig.JSONPDataSource({
dataSource: url, paging: {
enabled: true, pageSize: 10,
type: "remote"
}
});
$("#listingGrid").igGrid("dataSourceObject", jsonp).igGrid("dataBind");
I have to retrieve data in another page from this grid and select one column from this data.
and i have retrieved data like this
var ds = window.parent.$("#listingGrid").igGrid("option", "dataSource");
but not able to access one column data.
I'm assuming that since you are using the DataSource directly that you don't want the actual columns in the grid, which might differ from the columns in the data source depending on how you have the grid set up.
The easiest way to go about this would probably be to call the data function off of the data source once you retrieve it from your other page. This function returns an array of objects that are the items in each row. Once you have that you can iterate over each of the items and query the individual property.
var ds = window.parent.$('#listingGrid').igGrid('option', 'dataSource');
$.each(ds.data(), function (i, item) {
var itemProperty = item.Property;
// ...
});
You'll need to make sure that the data is all loaded from the service first though or data will possibly return an empty array.

How to refresh datagrid

I create dojox.grid.datagrid and I fill content from array like on example last example on page. During time, I change value of that array in code. How to refresh content of that grid ? How to load new data from changed array ?
To change values in the grid, you will need to change the value in the grid's store. The grid data is bound to the store data, and the grid will update itself as needed.
So the key is to understand Dojo's data api and how stores work in Dojo. Rather than manipulating the data directly in the grid, manipulate it in the store.
Ideally, the store is your array that you manipulate as the application runs and you should not be needing to sync the array to the grid. Just use the ItemFileWriteStore as your data holder unless thats not possible.
Also, using the dojo data identity api makes it much simple to find items in the grid if that is possible. Assuming you know when an item is updated, deleted, or changed in your application you should be able to modify the grid store as needed when the action happens. This is definitely the preferred approach. If you can't do that you will have to do a general fetch and use the onComplete callback to manually sync your arrays which will be very slow and won't scale well, in which case you may as well just create a new store all together and assign it to the grid with grid.setStore(myNewStore)
Here is a fiddle with a basic create, update, and delete operation: http://jsfiddle.net/BC7yT/11/
These examples all take advantage of declaring an identity when creating the store.
var store = new dojo.data.ItemFileWriteStore({
data: {
identifier : 'planet',
items: itemList
}
});
UPDATE AN EXISITNG ITEM:
//If the store is not in your scope you can get it from the grid
var store = grid.store;
//fetchItemByIdentity would be faster here, but this uses query just to show
//it is also possible
store.fetch({query : {planet : 'Zoron'},
onItem : function (item ) {
var humans = store.getValue(item, 'humanPop');
humans += 200;
store.setValue(item, 'humanPop', humans);
}
});
INSERT A NEW ITEM:
store.newItem({planet: 'Endron', humanPop : 40000, alienPop : 9000});
} catch (e) {
//An item with the same identity already exists
}
DELETE AN ITEM:
store.fetchItemByIdentity({ 'identity' : 'Gaxula', onItem : function (item ) {
if(item == null) {
//Item does not exist
} else {
store.deleteItem(item);
}
}});
The following code snippet can be used to update the grid:
var newStore = new dojo.data.ItemFileReadStore({data: {... some new data ...});
var grid = dijit.byId("gridId");
grid.setStore(newStore);
EDIT:
Dogo data grid reference guide (add/remove rows example, updating grid data examples )
(I suppose you already have a working grid and you want to completely change the grid's store)
Create a new datastore with your new value :
dataStore = new ObjectStore({ objectStore:new Memory({ data: data.items }) });
(data is the reponse from an ajax request for me)
Change your grid's store with the new one :
grid.store = dataStore;
Render :
grid.render();
This Will update Grid Store and refresh the View of the Grid in latest Version of Dojo 1.9
grid.store = store;
grid._refresh();
I had a server-side filtered EnhancedGrid, which was refreshing happily by changing the store, and shown in the other answers.
However I had another EnhancedGrid that would not refresh when a filter was applied. It may have been to do with the fact it was filtered client side (but data still coming from server using JsonRest store), but I don't really know the cause. Eitherway, the solution was to refresh with the following code:
grid.setFilter(grid.getFilter());
It's hacky and strange, but if it all else fails...
with this i can update a specifi row. this example is for a treegrid.
var idx = this.treeGrid.getItemIndex(item);
if(typeof idx == "string"){
this.treeGrid.updateRow(idx.split('/')[0]);
}else if(idx > -1){
this.treeGrid.updateRow(idx);
}