Connecting dojo dgrid to solr - javascript

I'm trying to connect a dojo dgrid to a solr data service and need some help.
When I use jsonp I can get connected to the solr data and output the data result to the screen with something like this:
dojo.require("dojo.io.script");
function searchGoogle(){
// Look up the node we'll stick the text under.
var targetNode = dojo.byId("output");
// The parameters to pass to xhrGet, the url, how to handle it, and the callbacks.
var jsonpArgs = {
url: "myExternalSolrURL",
callbackParamName: "json.wrf",
content: {
wt: "json",
rows: "12",
start: "1",
q: "*"
},
load: function(data){
// Set the data from the search into the viewbox in nicely formatted JSON
targetNode.innerHTML = "<pre>" + dojo.toJson(data, true) + "</pre>";
},
error: function(error){
targetNode.innerHTML = "An unexpected error occurred: " + error;
}
};
dojo.io.script.get(jsonpArgs);
}
dojo.ready(searchGoogle);
But, when I try to use jsonrest to connect to the solr data and get it to show up in a dgrid nothing appears to happen. This is the code I have for that:
<script>
var myStore, dataStore, grid;
require([
"dojo/store/JsonRest",
"dojo/store/Memory",
"dojo/store/Cache",
"dgrid/Grid",
"dojo/data/ObjectStore",
"dojo/query",
"dijit/form/Button",
"dojo/domReady!"
], function (JsonRest, Memory, Cache, Grid, ObjectStore, query, Button, domReady) {
myStore = Cache(JsonRest({
target: "myExternalSolrURL",
idProperty: "id"
}),
Memory({ idProperty: "id" }));
grid = new Grid({
store: dataStore = ObjectStore({ objectStore: myStore }),
structure: [
{ name: "Thing id", field: "id", width: "50px" },
{ name: "Name", field: "name", width: "200px" },
{ name: "detail", field: "detail", width: "200px" }
]
}, "grid"); // make sure you have a target HTML element with this id
grid.startup();
});
</script>
<div style="height: 300px; width: 600px; margin: 10px;">
<div id="grid">
</div>
</div>
Does anyone see what I am missing?

You changed your code to use dgrid, but it looks like you are still attempting to use a dojo/data store with dgrid. dgrid only supports the dojo/store API, so stop wrapping your store in ObjectStore.
dgrid/List and dgrid/Grid do not contain store logic. You will want to either use dgrid/OnDemandGrid or mix in dgrid/extensions/Pagination.
Make sure the service you are using with dojo/store/JsonRest actually behaves as the store implementation expects (or use or write a diffrent dojo/store implementation)

Apparently part of the problem is that a Solr index is not a flat data structure like a grid or dgrid can deal with. When you have nested data returned like a Solr or ElasticSearch index will return it must be "flattened" to go into a grid. However, this sort of hierarchy of data will work with a tree vs a grid. So the next challenge is to connect to the index and flatten it.

Related

Custom parameters for bootstrap-table server side pagination

I have a service created with spring boot, for which I am trying to display its data using the bootstrap-table library.
My service allows pagination with the query parameters ?page=x&size=y, where page starts at 0.
The response for the query returns something that looks like this:
{
"_embedded": {
"catalogueOrders": [ .... ]
},
"page": {
"size": 20,
"totalElements": 11,
"totalPages": 1,
"number": 0
}
}
Where _embedded.catalogueOrders contains all the data, and page contains the totals.
I tried configuring my table as following:
$('#orderTable').bootstrapTable({
url: "http://localhost:8088/catalogueOrders?orderStatus=" + orderState,
columns: [
{
field: 'orderId',
title: 'Order ID'
},
{
field: 'priority',
title: 'Priority'
}
],
pagination: true,
sidePagination: 'server',
totalField: 'page.totalElements',
pageSize: 5,
pageList: [5, 10, 25],
responseHandler: function(res) {
console.log(res)
return res["_embedded"]["catalogueOrders"]
}
})
This is able to retrieve and display the data, however it returns all the results, clearly due to it not knowing how to apply the pagination. Total elements doesn't seem to be retrieved either, as the table displays Showing 1 to 5 of undefined rows. Also, if I replace the responseHandler with dataField: '_embedded.catalogueOrders', it's no longer displaying the data.
How do I configure the query parameters needed for pagination?
And am I doing anything wrong when I try and configure dataField and totalField?
Figured it out:
Not sure what was wrong with the dataField and totalField, but it seems to not work with nested fields. To resolve this, I formatted the response into a new object inside responseHandler:
dataField: 'data',
totalField: 'total',
responseHandler: function(res) {
return {
data: res["_embedded"]["catalogueOrders"],
total: res["page"]["totalElements"]
}
}
As for the query parameters, by default, bootstrap-table provides the parameters limit and offset. To customize that and convert to size and page like in my case, the queryParams function can be provided:
queryParams: function(p) {
return {
page: Math.floor(p.offset / p.limit),
size: p.limit
}
}
one, yes, it doesn’t work with nested fields. if you want to use nested fields, try on sass code (get the compiler, just search up on web, there’s plenty of posts on the web).
two, i’m not exactly sure what you’re talking about, but you can set up a css variable
:root{
/*assign variables*/
—-color-1: red;
—-color-2: blue;
}
/*apply variables
p {
color: var(-—color-1):
}
you can find loads of info on this on the web.

Populating a grid using kendo js

I am working on a web app which needs to populate a grid with some data. I have a button wired with a onClick method which opens a new modal window for the grid to be displayed. I am using a jquery post call to the controller. However, I am unable to get the json data and assign it to my variable.
My code is as follows:
var grid_ds;
$.post('${ctx}/class/student/details?studentId=${student.studentId}', function(data){
}, 'json');
$('#student_grid').kendoGrid({
dataSource: grid_ds,
columns: [
{field: "studentName", title: "Student Name"},
{field: "studentClass", title: "Class"}
],
dataBound: function () {
emptyGrid($('#student_grid'));
}
}).data('kendoGrid');
My controller sends json back. I can see the data coming. How should I assign the json data to grid_ds and student_grid and make the values populate in the grid.
You could try using a kendo.data.DataSource with a custom transport function like so:
$('#student_grid').kendoGrid({
dataSource: dataSource = new kendo.data.DataSource({
transport: {
read: function (e) {
$.post('${ctx}/class/student/details?studentId=${student.studentId}', 'json')
.done(function (data) {
e.success(data);
});
}
}
}),
columns: [
{
field: "studentName",
title: "Student Name"
},
{
field: "studentClass",
title: "Class"
}
]});
I think the problem may be with how you're fetching the data. Since $.post is an ajax call operating out of band, grid_ds is most likely undefined when being passed to the .kendoGrid() function.
I wasn't able to locate the dataBound configuration property that you specify in your question in the kendo.ui.Grid. Do you happen to know where this configuration setting came from?

extjs ServerProxy error on save

I'm trying to update a field value from a grid row icon. But I get this error:
Uncaught Ext.data.proxy.Server.buildUrl(): You are using a ServerProxy but have not supplied it with a url.
I'm using a RestProxy, this is the store definition:
Ext.define('SF.store.Contents', {
requires: [
'SF.Config',
'SF.store.RestProxy'
],
extend: 'Ext.data.Store',
model: 'SF.model.Content',
autoLoad: false,
proxy: Ext.create('SF.store.RestProxy', {
url: (new SF.Config()).getApiBaseUrl() + "admin/contents"
}),
});
column code on GridPanel definition
....
store: 'Contents',
.....
{ xtype: 'actioncolumn', header: 'Action'
, width: 40
, items: [{ // Delete button
icon: '......./cancel.png'
, handler: function(grid, rowIndex, colindex) {
var record = grid.getStore().getAt(rowIndex);
record.set('status',6);
record.save(); //THIS CALL THROWS THE ERROR
grid.store.remove(record);
}
},......
In addition, the proxy is working fine for GET request. Does anyone knows what should I define on the proxy?
I've read the official doc but it is not clear for me.
You have to provide a proxy for you model. In the button´s handler you are calling the model's save method (SF.model.Content) then, your SF.model.Content model has to provide a proxy.

Response Header with a JsonRestStore (with Dgrid/Dojo)

Trying to build a dynamic grid with my json store, but for some reason there's a range constraint and I guess it's part of the dgrid/store implementation, but I should scroll down my grid and get more result from the example at dgrid site.
I'll put some code in here. First, I tried to be very modular in my code, so I have a file that gets my store (content.js), a file that build my grid (gridlayout.js) and main.js (create my instance and pass my store).
content.js
define([
"dojo/_base/xhr",
"dojo/store/Memory",
"dojo/store/JsonRest",
"dojo/store/Cache"
],
function(
xhr,
Memory,
JsonRest,
Cache
){
var contentMemoryStore = new Memory();
var contentJsonRestStore = new JsonRest({target: "http://dev.mpact.tv:30087/rest/contenus/"});
contentStore = new Cache(contentJsonRestStore, contentMemoryStore);
return contentStore;
});
GridLayout.js
define([
"dojo/_base/declare",
"dijit/_WidgetBase",
"dgrid/OnDemandGrid",
"dgrid/Keyboard",
"dgrid/Selection",
"dgrid/extensions/ColumnHider",
"dgrid/editor",
], function(
declare,
_WidgetBase,
Grid,
Keyboard,
Selection,
Hider,
editor
){
return declare([Grid, Keyboard, Selection, Hider], {
columns: {
selected: editor({
label: " ",
autoSave: true,
sortable: false
}, "checkbox"),
nom: "Name",
autodelete: "Auto-delete",
groupe_id: "Groupe ID",
global: "Global",
date: "Date",
duree: "Lenght",
description: "Description",
fichier: "Filename",
pleinecran: "Fullscreen",
repertoire: "Folder",
taille: "Size",
expiration: "Expired",
id: "id",
catergorie: "Category",
brouillon: "Example"
},
});
});
and my main.js:
var gridLayout = new GridLayout({}, "placeholder");
gridLayout.set("store", contentStore);
So far, I just 25 result and if I scroll down, I don't get the rest of my items.
The answer in your browser shows items 0-24/25. That means the total number of items server side is 25. Hence the grid won't try to fetch more than that.
If it were returning 0-24/1000, then there would be multiple calls when you would scroll.
So I think you should check server side why it only returns 25 as total number of items.
Check this: http://dojotoolkit.org/reference-guide/1.7/dojo/store/JsonRest.html#id7

Dynamic Models, Stores, and Views -- Best way to

NOTE: Author is new to EXT JS and is trying to use MVC in his projects
imagine i have a web service whose data model is not fixed. I would want to have my models dynamically created, from which i dynamically create stores and hence dynamic components whose data is in those stores.
Lets start by seeing a sample class definition of a model:
Ext.define('MNESIA.model.User', {
extend: 'Ext.data.Model'
});
In this model definition, i have left out the 'fields' parameter in the config object. This is because whwnever i create an instance of a model of the type above, i want to dynamically give it its fields definition, in other words i can have many instances of this model yet all having different definition of their 'fields' parameter.
From here i create a definition of the store, like this:
Ext.define('MNESIA.store.Users', {
extend: 'Ext.data.Store',
autoLoad: true
}
});
There, i have a store definition. I have left out the 'model' parameter because i will attach it to every instance of this class dynamically. Infact, even the 'data' and 'proxy' settings are not mentioned as i would want to asign them during the instantiation of this store.
From there, i would want to have dynamic views, driven by dynamic stores. Here below i have a definition of a Grid
Ext.define('MNESIA.view.Grid' , {
extend: 'Ext.grid.Panel',
alias : 'widget.mygrid',
width: 700,
height: 500
});
I have left out the following parameters in the Grid specification: 'columns', 'store' and 'title' . This is because i intend to have many Grids created as instances of the specification above yet having dynamic stores, titles and column definitions.
Some where in my controller, i have some code that appears like this:
function() {
var SomeBigConfig = connect2Server();
/*
where:
SomeBigConfig = [
{"model":[
{"fields":
["SurName","FirstName","OtherName"]
}
]
},
{"store":[
{"data":
{"items":[
{"SurName":"Muzaaya","FirstName":"Joshua","OtherName":"Nsubuga"},
{"SurName":"Zziwa","FirstName":"Shamusudeen","OtherName":"Haji"},
...
]
}
},
{"proxy": {
"type": "memory",
"reader": {
"type": "json",
"root": "items"
}
}
}
]
},
{"grid",[
{"title":"Some Dynamic Title From Web Service"},
{"columns": [{
"header": "SurName",
"dataIndex": "SurName",
"flex": 1
},{
"header": "FirstName",
"dataIndex": "FirstName",
"flex": 1
},
{
"header": "OtherName",
"dataIndex": "OtherName",
"flex": 1
}
]}
]
}
]
*/
var TheModel = Ext.create('MNESIA.model.User',{
fields: SomeBigConfig[0].model[0].fields
});
var TheStore = Ext.create('MNESIA.store.Users',{
storeId: 'users',
model: TheModel,
data: SomeBigConfig[1].store[0].data,
proxy: SomeBigConfig[1].store[1].proxy
});
var grid = Ext.create('MNESIA.view.Grid',{
store: TheStore,
title: SomeBigConfig[2].grid[0].title,
columns: SomeBigConfig[2].grid[1].columns
});
// From here i draw the grid anywhere on the, page say by
grid.renderTo = Ext.getBody();
// end function
}
Now this kind of dynamic creating of models, then stores, and then grids does result into memory wastage and so this would require the destroy methods of each component to be called each time we want to destroy that component.
Questions:
Qn 1: Does the MVC implementation of EXT JS 4 permit this ?
Qn 2: How would i gain the same functionality by using the xtypes of my new classes. Say for example:
{
xtype: 'mygrid',
store: TheStore,
title: SomeBigConfig[2].grid[0].title,
columns: SomeBigConfig[2].grid[1].columns
}
Qn 3: If what i have written above really works and is pragmatically correct, can i apply this to all components like Panels, TabPanels, Trees (whereby their Configs are sent by a remote server) ?
Qn 4: If i have Controllers A and B, with controller A having a specification of views: [C, D] and Controller B having views: [E, F], would it be correct if actions generated by view: E are handled by Controller A ? i.e. Can a controller handle actions of a view which is not registered in its views config ?
NOTE: am quite new to Ext JS but would love to learn more. Advise me on how to improve my EXT JS learning curve. Thanks
In my option ,your model must map onto the store that is to be rendered to the view like for example,if implement the model part like this
{"model":[{"fields":[{name:'name',type:'string'},
{name:'id',type:'string'}]}]} ,this will be easily mapped onto the store for the view render it.

Categories

Resources