UI layer pagination and sorting in extjs - pagination

I have my extjs application. As of now i am getting all my records from backend, full record set in 1 service request. I need to implement the pagination and sorting at UI level. Sorting seems be simple. How do i implement UI level pagination? Any example for this? I am getting 10-20k records so it is fine if i implement pagination at UI level? Can extjs6 handle the load?

I'd recommend you handle paging server-side. Right now you might only have 10-20k records, but what if it grows to 100k? or 1 million?
Take a look at this guide from Sencha: Grids - Paging. It explains a lot.
Good luck!

Sorting is implemented out of box. This is simple pagination example based on default ExtJs 6.2.0 application.
YourAppName.view.main.List
...
// bottom paging-bar definition. Use "tbar" for top bar, or define both.
bbar: {
xtype: 'pagingtoolbar',
displayInfo: true,
emptyMsg: 'No data to display',
items: ['->'],
prependButtons: true
}
...
items: [{
title: 'Home',
iconCls: 'fa-home',
layout: 'fit', // needed for scrolling
scrollable: true, // for scrollable items
items: [{
xtype: 'mainlist'
}]
}, {
...
YourAppName.store.Personnel
Ext.define('YourAppName.store.Personnel', {
extend: 'Ext.data.Store',
alias: 'store.banners',
autoLoad: true, // run ajax-query right after grid rendering
loadMask: true, // show preload image
pageSize: 100,
model: 'YourAppName.model.Person',
proxy: {
type: 'ajax',
url: '/personnel',
reader: {
type: 'json',
rootProperty: 'items',
totalProperty: 'total'
}
}
});
Create in app/model folder file Person.js with:
YourAppName.model.Person
Ext.define('YourAppName.model.Person', {
extend: 'Ext.data.Model',
fields: [
{ name: 'name', type: 'string', defaultValue: '' },
{ name: 'email', type: 'string', defaultValue: '' },
{ name: 'phone', type: 'string', defaultValue: '' }
]
});
As of store definition your web-server must be able to response on HTTP GET-request on URI /personnel with json like this:
{
"success": true,
"total": 20000,
"items": [
{ "name": "Jean Luc", "email": "jeanluc.picard#enterprise.com", "phone": "555-111-1111" },
{ "name": "Worf", "email": "worf.moghsson#enterprise.com", "phone": "555-222-2222" },
{ "name": "Deanna", "email": "deanna.troi#enterprise.com", "phone": "555-333-3333" },
{ "name": 'Data', "email": "mr.data#enterprise.com", "phone": "555-444-4444" }
...
]
}

Related

Sequelize included Model result keys are strings

Forgive my limited knowledge im about a week into using Sequelize,
Models.PlannerModel.Builds.findAll({
raw: true,
where: {
ProposedDelivery: { [Op.gt]: moment().format("YYYY-MM-DD") },
description: { [Op.ne]: null },
description: { [Op.ne]: " " },
description: { [Op.not]: null },
},
include: [
{
model: Models.PlannerModel.Unit,
required: true
},
],
the result from the above is as you would expect except all the keys for the fields in the includes are as strings so referencing them in my Pug template/class has to be done with brackets
overall not the end of the world just wondering if im doing something wrong ?
Cheers!
Turn off raw to get nested model objects and also to get plain objects use get({ plain: true}) for each returned model instance:
const builds = await Models.PlannerModel.Builds.findAll({
where: {
ProposedDelivery: { [Op.gt]: moment().format("YYYY-MM-DD") },
[Op.and]: [{
description: { [Op.ne]: null },
}, {
description: { [Op.ne]: " " },
}, {
description: { [Op.not]: null },
}
]
},
include: [
{
model: Models.PlannerModel.Unit,
required: true
},
]
})
const plainBuilds = builds.map(x => x.get({ plain: true }))
Please pay attention that I changed conditions with description. In your version of conditions only the last one will work because JS saves only the last key if there are several same keys in the same object.

How to add a field from associated model using Sequelize?

I'm making a web API using Node, Express, and Sequelize. I have models Users and Teams (shown below). Users has a teamId that references Teams.id, and there is an association between the two to reflect that.
User definition
const User = sequelize.define('User', {
id: {
autoIncrement: true,
type: DataTypes.INTEGER,
allowNull: false,
primaryKey: true
},
displayName: {
type: DataTypes.STRING,
allowNull: false
},
teamId: {
type: DataTypes.INTEGER,
allowNull: false,
references: {
model: 'Team',
key: 'id'
}
}
}
Team definition
const Team = sequelize.define('Team', {
id: {
autoIncrement: true,
type: DataTypes.INTEGER,
allowNull: false,
primaryKey: true
},
name: {
type: DataTypes.STRING,
allowNull: false
}
}
Association
User.belongsTo(Team, { as: 'team', foreignKey: 'teamId' });
Query
Users.findAll({
include: [
{
model: Team,
as: 'team'
}
]
});
As expected, this returns a list of User objects, with the added "team" property the respective Team objects embedded like so:
[
{
"id": 1,
"displayName": "John Smith",
"teamId": 1,
"team": {
"id": 1,
"name": "My Awesome Team"
}
}
]
My goal is to return User objects, but instead of embedding the entire Team object under the team property, I'd like to add just the name of the team as the value of the property, like this:
[
{
"id": 1,
"displayName": "John Smith",
"teamId": 1,
"team": "My Awesome Team"
}
]
Is there a way to accomplish this with Sequelize?
Well, through typing up my question I thought of better ways to search for the answer, and I think I found one right off the bat...
I found this StackOverflow question where the asker was doing what I am trying to do.
The solution is to use attributes.include and Sequelize.col() to include the attribute I want, and in my include options, use attributes: [] to hide the Team objects.
Going off the examples I included in the original post, this is what works for me, giving me nearly the exact output I wanted:
Users.findAll({
attributes:{
include: [[Sequelize.col(team.name), 'teamName']]
}
include: [
{
model: Team,
as: 'team',
attributes: []
}
]
});
Output
[
{
"id": 1,
"displayName": "John Smith",
"teamId": 1,
"teamName": "My Awesome Team"
}
]
Since the association uses the alias "team", I had to name my property something different, and went with "teamName" which is perfectly fine and probably preferable since it is more descriptive.

sequelize: Not include model if where conditon of included model matches

I want to get all RecurringEvents that have no excludeDates for today.
I have following models:
Recurring events
const RecurringEvent = sequelize.definge('recurringEvent,{
id: {type: Sequelize.INTEGER, primaryKey:true},
title: Sequelize.STRING
});
And ExcludeDates with a foreign key recurringEventId
const ExcludeDate = sequelize.define('exclude_date',{
id: {type: Sequelize.INTEGER, primaryKey:true},
recurringEventId: Sequelize.INTEGER,
date: Sequelize.DATE
});
As a relationship i defined
RecurringEvent.hasMany(ExcludeDate, {foreignKey: 'recurringEventId'});
I can get all my RecurringEvents including the the excludeDates with
RecurringEvent.findAll({include:[{model:ExcludeDate}]});
That will give me an output like:
[
{
"id": 1,
"title": "Event1",
"exclude_dates": [
{
"id": 1,
"date": "2019-02-13",
"recurringEventId": 1,
},
{
"id": 2,
"date": "2019-02-14",
"recurringEventId": 1,
}
]
Now i would like to get the Recurring events but only if there is no exclude date for today.
so far i have tried
RecurringEvent.findAll({
include: [{
model: ExcludeDate,
where: {
date: {
[Op.ne]: moment().format('YYYY-MM-DD')
}
}
}]
})
But that only leaves out the ExcludeDate entry with the current Date like that :
[
{
"id": 1,
"title": "Event1",
"exclude_dates": [
{
"id": 2,
"date": "2019-02-14",
"recurringEventId": 1,
}
]
How can i exclude the whole RecurringEvent if and ExcludeDate for it is set for today?
Edit:
I also read in the docs
To move the where conditions from an included model from the ON condition to the top level WHERE you can use the '$nested.column$'
So i have tried this:
RecurringEvent.findAll({where:{
'$exclude_dates.date$':{
[Op.ne]: moment().format('YYYY-MM-DD')
}
},
include: [{model: ExcludeDate}]
})
But without any luck, i'm still getting RecurringEvents just without the one exclude date in the exclude_dates property
Try to add required: true, to your include model to make inner join instead of left join. e.g.
RecurringEvent.findAll({
include: [{
model: ExcludeDate,
required: true,
where: {
date: {
[Op.ne]: moment().format('YYYY-MM-DD')
}
}
}]
})

Export To Excel filtered data with Free jqgrid 4.15.4 in MVC

I have a question regarding Export to Excel in free-jqgrid 4.15.4. I want to know how to use this resultset {"groupOp":"AND","rules":[{"field":"FirstName","op":"eq","data":"Amit"}]} into my Business Logic Method.
Just for more clarification, I've using OfficeOpenXml and if I don't use filtered resultset(aforementioned) it is working fine and I'm able to download file with full records in an excel sheet. But I'm not sure what to do or how to utilize the resultset {"groupOp":"AND","rules":[{"field":"FirstName","op":"eq","data":"Amit"}]}
If required I can share my controller and BL code.
I have added a fiddle which shows implementation of Export to Excel button in jqGrid pager.
Before coming to here, I've read and tried to understand from following questions:
1] jqgrid, export to excel (with current filter post data) in an asp.net-mvc site
2] Export jqgrid filtered data as excel or CSV
Here is the code :
$(function () {
"use strict";
var mydata = [
{ id: "10", FirstName: "test", LastName: "TNT", Gender: "Male" },
{ id: "11", FirstName: "test2", LastName: "ADXC", Gender: "Male" },
{ id: "12", FirstName: "test3", LastName: "SDR", Gender: "Female" },
{ id: "13", FirstName: "test4", LastName: "234", Gender: "Male" },
{ id: "14", FirstName: "test5", LastName: "DAS", Gender: "Male" },
];
$("#list").jqGrid({
data: mydata,
colNames: ['Id', 'First Name', 'Last Name', 'Gender'],
colModel: [
{
label: "Id",
name: 'Id',
hidden: true,
search: false,
},
{
label: "FirstName",
name: 'FirstName',
searchoptions: {
searchOperators: true,
sopt: ['eq', 'ne', 'lt', 'le','ni', 'ew', 'en', 'cn', 'nc'],
}, search: true,
},
{
label: "LastName",
name: 'LastName',
searchoptions: {
searchOperators: true,
sopt: ['eq', 'ne', 'lt', 'ni', 'ew', 'en', 'cn', 'nc'],
}, search: true,
},
{
label: "Gender",
name: 'Gender',
search: true, edittype: 'select', editoptions: { value: 'Male:Male;Female:Female' }, stype: 'select',
},
],
onSelectRow: function (id) {
if (id && id !== lastsel) {
jQuery('#list').restoreRow(lastsel);
jQuery('#list').editRow(id, true);
lastsel = id;
}
},
loadComplete: function (id) {
if ($('#list').getGridParam('records') === 0) {
//$('#grid tbody').html("<div style='padding:6px;background:#D8D8D8;'>No records found</div>");
}
else {
var lastsel = 0;
if (id && id !== lastsel) {
jQuery('#list').restoreRow(lastsel);
jQuery('#list').editRow(id, true);
lastsel = id;
}
}
},
loadonce: true,
viewrecords: true,
gridview: true,
width: 'auto',
height: '150px',
emptyrecords: "No records to display",
iconSet:'fontAwesome',
pager: true,
jsonReader:
{
root: "rows",
page: "page",
total: "total",
records: "records",
repeatitems: false,
Id: "Id"
},
});
jQuery("#list").jqGrid("navButtonAdd", {
caption: "",
buttonicon: "fa-table",
title: "Export To Excel",
onClickButton: function (e) {
var projectId = null;
var isFilterAreUsed = $('#grid').jqGrid('getGridParam', 'search'),
filters = $('#grid').jqGrid('getGridParam', 'postData').filters;
var Urls = "/UsersView/ExportToExcel_xlsxFormat?filters="+ encodeURIComponent(filters); //' + encodeURIComponent(filters);/
if (totalRecordsCount > 0) {
$.ajax({
url: Urls,
type: "POST",
//contentType: "application/json; charset=utf-8",
data: { "searchcriteria": filters, "projectId": projectId, "PageName": "MajorsView" },
//datatype: "json",
success: function (data) {
if (true) {
window.location = '/UsersView/SentFiletoClientMachine?file=' + data.filename;
}
else {
$("#resultDiv").html(data.errorMessage);
$("#resultDiv").addClass("text-danger");
}
},
error: function (ex) {
common.handleAjaxError(ex.status);
}
});
}
else {
bootbox.alert("There are no rows to export in the Participant List")
if (dialog) {
dialog.modal('hide');
}
}
}
});
});
https://jsfiddle.net/ap43xecs/10/
There are exist many option to solve the problem. The simplest one consist of sending ids of filtered rows to the server instead of sending filters parameter. Free jqGrid supports lastSelectedData parameter and thus you can use $('#grid').jqGrid('getGridParam', 'lastSelectedData') to get the array with items sorted and filtered corresponds to the current filter and sorting criteria. Every item of the returned array should contain Id property (or id property) which you can use on the server side to filter the data before exporting.
The second option would be to implement server side filtering based on the filters parameter, which you send currently to the server. The old answer (see FilterObjectSet) provides an example of filtering in case of usage Entity Framework. By the way, the answer and another one contain code, which I used for exporting grid data to Excel using Open XML SDK. You can compare it with your existing code.
In some situations it could be interesting to export grid data to Excel without writing any server code. The corresponding demo could be found in the issue and UPDATED part of the answer.

node.js odata-server mongodb unable to post related entity

I have been working on a node.js odata server based on this example: How to set up a nodejs OData endpoint with odata-server
I have everything working... I can read, update, insert, delete. But I am trying to associate a Journal with a Tasks and I am having problems.
I have tried several different ways outlined here: Operations (OData Version 2.0)
Here is my code:
/* global $data */
require('odata-server');
$data.Class.define("Task", $data.Entity, null, {
Id: { type: "id", key: true, computed: true, nullable: false },
Title: { type: "string", required: true, maxLength: 200 },
Journals: { type: "array", elementType: "Journal"
, inverseProperty: "Task" }
});
$data.Class.define("Journal", $data.Entity, null, {
Id: { type: "id", key: true, computed: true, nullable: false },
Entry: { type: "string" },
DateInserted: { type: "string" },
Task: { type: "object", elementType: "Task" , inverseProperty: "Journals" }
});
$data.EntityContext.extend("obb", {
Tasks: { type: $data.EntitySet, elementType: Task },
Journals: { type: $data.EntitySet, elementType: Journal }
});
$data.createODataServer(obb, '/api-v0.1', 2046, 'localhost');
Question:
Is this feature even available from odata-server what would the post look like to link a Journal to a Task?
I am using fiddler2 and composing a POST I have tried these urls:
//localhost:2046/api-v0.1/Tasks('the-id-of-a-task')/Journals
//localhost:2046/api-v0.1/Tasks('the-id-of-a-task')/Journals/$link
post body's I have tried:
{"Entry":"This is a test"}
{"url":"http://localhost:2046/api-v0.1/Journals('id-of-a-journal-in-the-db')"}
I have even tried to build out and post a Task with journals together and that didn't work.
Any help would be greatly appreciated. Thanks.

Resources