How to show Total number of pages in YUI Paginator? - javascript

I am using YUI Paginator API for pagination and I need to show Total number of pages on screen. I saw that there is a function getTotalPages() in API but I am unsure about how to use it, there isn't enough documentation. Also after looking at some other documentation I tried using {totalPages} but didn't work.
Can somebody help me out in this issue? Thanks in advance!!
Below is the code snippet I am using. Please refer to template object from config:
config = {
rowsPerPage: 100,
template :
'<p class="klass">' +
'<label>Total pages: {totalPages}</label>'+
'<label>Page size: {RowsPerPageDropdown}</label>'+
'</p>',
rowsPerPageDropdownClass : "yui-pg-rpp-options",
rowsPerPageOptions : [
{ value : 100 , text : "100" },
{ value : 250 , text : "250" },
{ value : 500 , text : "500" },
{ value : 1000 , text : "1000" },
{ value : tstMap[tabName].length , text : "All" }
],
};
var myPaginator = new YAHOO.widget.Paginator(config);

The Paginator utility allows you to display an item or a group of items depending on the number of items you wish to display at one time.
Paginator's primary functionality is contained in paginator-core and is mixed into paginator to allow paginator to have extra functionality added to it while leaving the core functionality untouched. This allows paginator-core to remain available for use later on or used in isolation if it is the only piece you need.
Due to the vast number of interfaces a paginator could possibly consist of, Paginator does not contain any ready to use UIs. However, Paginator is ready to be used in any Based-based, module such as a Widget, by extending your desired class and mixing in Paginator. This is displayed in the following example:
YUI().use('paginator-url', 'widget', function (Y){
var MyPaginator = Y.Base.create('my-paginator', Y.Widget, [Y.Paginator], {
renderUI: function () {
var numbers = '',
i, numberOfPages = this.get('totalPages');
for (i = 1; i <= numberOfPages; i++) {
// use paginator-url's formatUrl method
numbers += '' + i + '';
}
this.get('boundingBox').append(numbers);
},
bindUI: function () {
this.get('boundingBox').delegate('click', function (e) {
// let's not go to the page, just update internally
e.preventDefault();
this.set('page', parseInt(e.currentTarget.getContent(), 10));
}, 'a', this);
this.after('pageChange', function (e) {
// mark the link selected when it's the page being displayed
var bb = this.get('boundingBox'),
activeClass = 'selected';
bb.all('a').removeClass(activeClass).item(e.newVal).addClass(activeClass);
});
}
});
var myPg = new MyPaginator({
totalItems: 100,
pageUrl: '?pg={page}'
});
myPg.render();
});

Related

How to create customized list item with checkbox?

I've created a qooxdoo list with customized items containing checkbox and label.
My problem is: when I check the check box, it gets bigger which gives an ugly user experience. Also when I check some first items and scroll down, I see many items checked which should be unchecked by default.
Here's the code that someone can paste into play ground for qooxdoo:
// Create a button
var button1 = new qx.ui.form.Button("click to see list!", "icon/22/apps/internet-web-browser.png");
// Document is the application root
var doc = this.getRoot();
// Add button to document at fixed coordinates
doc.add(button1,
{
left : 100,
top : 50
});
var popup;
// Add an event listener
button1.addListener("execute", function(e) {
if (!popup) {
popup = new myApp.list();
}
popup.placeToWidget(button1);
popup.show();
});
/*
* class: list inside popup.
*/
qx.Class.define("myApp.list",
{
extend : qx.ui.popup.Popup,
construct : function()
{
this.base(arguments);
this.__createContent();
},
members : {
__createContent : function(){
this.set({
layout : new qx.ui.layout.VBox(),
minWidth : 300
});
//prepare data
var zones = [];
for (var i=0; i<100; i++){
zones.push({"LZN" : "ZONE " + i, "isChecked" : false});
}
var lstFences = new qx.ui.list.List();
this.add(lstFences, {flex : 2});
var delegate = {
createItem : function() {
return new myApp.customListItem();
},
bindItem : function(controller, item, id) {
controller.bindProperty("isChecked", "isChecked", null, item, id);
controller.bindPropertyReverse("isChecked", "isChecked", null, item, id);
controller.bindProperty("LZN", "LZN", null, item, id);
}
};
lstFences.setDelegate(delegate);
lstFences.setModel(qx.data.marshal.Json.createModel(zones));
lstFences.setItemHeight(50);
}
}
})
/**
* The custom list item
*/
qx.Class.define("myApp.customListItem", {
extend : qx.ui.core.Widget,
properties :
{
LZN:
{
apply : "__applyLZN",
nullable : true
},
isChecked :
{
apply : "__applyChecked",
event : "changeIsChecked",
nullable : true
}
},
construct : function()
{
this.base(arguments);
this.set({
padding : 5,
decorator : new qx.ui.decoration.Decorator().set({
bottom : [1, "dashed","#BBBBBB"]
})
});
this._setLayout(new qx.ui.layout.HBox().set({alignY : "middle"}));
// create the widgets
this._createChildControl(("isChecked"));
this._createChildControl(("LZN"));
},
members :
{
// overridden
_createChildControlImpl : function(id)
{
var control;
switch(id)
{
case "isChecked":
control = new qx.ui.form.CheckBox();
control.set({
padding : 5,
margin : 8,
value : false,
decorator : new qx.ui.decoration.Decorator().set({
width : 2,
color : "orange",
radius : 5
})
});
this._add(control);
break;
case "LZN":
control = new qx.ui.basic.Label();
control.set({allowGrowX : true});
this._add(control, {flex : 2});
break;
}
return control || this.base(arguments, id);
},
__applyLZN : function(value, old) {
var label = this.getChildControl("LZN");
label.setValue(value);
},
__applyChecked : function(value, old)
{
var checkBox = this.getChildControl("isChecked");
console.log(value, old);
checkBox.setValue(value);
}
}
});
There are two problems here:
The first one is the fact that by creating the checkbox as a subwidget via _createChildControlImpl makes the checkbox loosing its appearance (in sense of qooxdoo theme appearance) leading to the lost minWidth attribute which makes the checkbox having a width of 0 when unchecked and a width which is needed to show the check mark when it's checked. The solution here is to add an appearance to the myApp.customListItem class like this:
properties : {
appearance: {
refine : true,
init : "mycustomlistitem"
}
}
and afterward add a corresponding appearance to your theme:
appearances :
{
"mycustomlistitem" : "widget",
"mycustomlistitem/isChecked" : "checkbox"
}
You could also add all the styling you've done when instantiating the checkboxes (orange decorator etc.) within the appearance definition.
The second problem is that you’ve defined only a one way binding between the checkbox subwidget of the custom list item and its "isChecked" sub widget. You need a two way binding here, thus if the value of the property "isChanged" changes it’s value it prpoagates that to the checkbox and vice versa.
I've modified your playground sample accordingly by creating the missing appearance on the fly and by creating a two way binding between the checkbox and the list items “isChecked” property. Note that I've created the list directly in the app root for simplicity:
https://gist.github.com/level420/4662ae2bc72318b91227ab68e0421f41

jQuery jTable pagination is not working properly

I'm using jquery jTable in my web-based project. Its pagination work fine when the number of rows less than 10,000. But when the number of rows exceeded from 10000, it causes an unfamiliar issue in its pagination. The pagination start skipping odd page numbering. You can see it in picture below:
My javaScript code for jTable is:
$("#AllProductTable").jtable({
paging: true,
pageSize: 10,
columnSelectable: false,
actions: {
listAction: '/ProductDefinition/Select'
},
fields: {
ProductId: { visibility: 'hidden', listClass: 'right-align' },
ProductCode: { title: 'Product Code' },
// more fields...
},
recordsLoaded: function (event, data) {
}
});
while my html tag for jTable is:
<div id="AllProductTable" style="width:400%;"></div>
I explored a lot\, but didn't find the solution related to it. I'm further unable to understand this miss behavior.
And at last, I got succeeded to solve this issue. I go through the jquery.jtable.js whole file and find something strange in one of its function. The function was;
_refreshGotoPageInput: function() {
// different logic statements
//...
//Skip some pages is there are too many pages
var pageStep = 1;
if (currentPageCount > 10000) { // if you having more than 10,000 pages
pageStep = 100;
} else if (currentPageCount > 5000) { // if you having more than 5000 pages
pageStep = 10;
} else if (currentPageCount > 2000) { // if you having more than 2000 pages
pageStep = 5;
} else if (currentPageCount > 1000) { // if you having more than 1000 pages
pageStep = 2;
}
//....
// Differnet logic statements
}
All you need is just to comment this portion of the above given function, or modify it according to your own implementation logic.
In my above mentioned case, my no_of_pages were increasing from 1000, that's why its taking 2-steps on changing page and so on.

Jquery - Add hyperlink to datatables

Using the DataTable plugin I am able to generate a table just fine but I want a custom hyperlink on one of the columns that links to another page but taking information from the rest of the row...for example in row 1 I want a hyperlink: http://url/?data['imdata'][i]['faultInst']["attributes"]["code"] or something like that. I've seen a lot of complicated examples from other forms but couldn't get it to work. Looking for the simplest solution as this is a side project and I need it to be completed.
$(document).ready(function(){
$.getJSON('/static/faults.json', function (data) {
var test = $('#table5').DataTable({
});
var tr;
for (var i = 0; i < data["totalCount"]; i++) {
test.row.add([
data['imdata'][i]['faultInst']["attributes"]["code"],
data['imdata'][i]['faultInst']["attributes"]["cause"],
data['imdata'][i]['faultInst']["attributes"]["descr"],
data['imdata'][i]['faultInst']["attributes"]["created"],
data['imdata'][i]['faultInst']["attributes"]["changeSet"],
data['imdata'][i]['faultInst']["attributes"]["childAction"],
data['imdata'][i]['faultInst']["attributes"]["dn"],
data['imdata'][i]['faultInst']["attributes"]["domain"],
data['imdata'][i]['faultInst']["attributes"]["highestSeverity"],
data['imdata'][i]['faultInst']["attributes"]["lastTransition"],
data['imdata'][i]['faultInst']["attributes"]["lc"],
data['imdata'][i]['faultInst']["attributes"]["occur"],
data['imdata'][i]['faultInst']["attributes"]["origSeverity"],
data['imdata'][i]['faultInst']["attributes"]["prevSeverity"],
data['imdata'][i]['faultInst']["attributes"]["rule"],
"test",
//data['imdata'][i]['faultInst']["attributes"]["Severity"],
data['imdata'][i]['faultInst']["attributes"]["subject"],
data['imdata'][i]['faultInst']["attributes"]["type"],
//data['imdata'][i]['faultInst']['attributes']["ack"]
"test",
"test"
])
}
test.draw();
});
});
When you have a setup like this, just avoid to define data, by that you get the proper value you can turn into a link. dataTables know which data it should pass to the render function by the targets value. Example :
var table = $('#example').DataTable({
columnDefs : [
{ targets : [0],
render : function(data) {
return '<a href="'+data+'" target_blank>'+data+'</a>'
}
}
]
})
table.row.add(['https://example.com', 'david', 'programmer']).draw()
demo -> http://jsfiddle.net/47k7nhkb/

Froala editor custom dropdown with dynamic values

I am using Froala and I am stuck creating a custom drop down with dynamic option sets in it. I have used their common way to create the drop down but that is useless if we have to fetch the values from db.
I want to make a "Templates" dropdown with 10 options to select which will be created dynamically.
Currently we create a custom drop down this way,
options: {
'Template One': function(e){
_this.editable('insertHTML', "<p>This is template one</p>", true);
},
}
I want this to be dynamic, meaning I will fetch the names and content of the templates from database and add them in the option set accordingly.
something like,
options : {
$.each(alltemplates, function(i, h){
i: function(e){ /// "i" will be the name of the template fetched from db
_this.editable('insertHTML', h, true); // h is the html fetched from db
},
})
}
which will create the drop down dynamically. Any help please ?
Expanding on #c23gooey's answer, here's what we came up with for a similar problem (inserting dynamically-generated mail-merge placeholders).
var commandName = 'placeholders',
iconName = commandName + 'Icon',
buildListItem = function (name, value) {
// Depending on prior validation, escaping may be needed here.
return '<li><a class="fr-command" data-cmd="' + commandName +
'" data-param1="' + value + '" title="' + name + '">' +
name + '</a></li>';
};
// Define a global icon (any Font Awesome icon).
$.FroalaEditor.DefineIcon(iconName, { NAME: 'puzzle-piece' });
// Define a global dropdown button for the Froala WYSIWYG HTML editor.
$.FroalaEditor.RegisterCommand(commandName, {
title: 'Placeholders',
type: 'dropdown',
icon: iconName,
options: {},
undo: true,
focus: true,
refreshAfterCallback: true,
callback: function (cmd, val, params) {
var editorInstance = this;
editorInstance.html.insert(val);
},
refreshOnShow: function ($btn, $dropdown) {
var editorInstance = this,
list = $dropdown.find('ul.fr-dropdown-list'),
listItems = '',
placeholders = editorInstance.opts.getPlaceholders();
// access custom function added to froalaOptions on instance
// use a different iteration method if not using Angular
angular.forEach(placeholders, function (placeholder) {
listItems += buildListItem(placeholder.name, placeholder.value);
});
list.empty().append(listItems);
if (!editorInstance.selection.inEditor()) {
// Move cursor position to end.
editorInstance.selection.setAtEnd(editorInstance.$el.get(0));
editorInstance.selection.restore();
}
}
});
We ran this method by Froala support and were told:
The editor doesn't have any builtin mechanism for using dynamic
content when showing the dropdown, but your solution is definitely a
good one.
Use the refreshOnShow function to change the options dynamically.

How to change cell formatting dynamically

I hava implemented a datagrid using dojo which get updated every 5 seconds. I use following code to update the datagrid.
jsonStore.fetch({
query: {id:'*'},
onComplete: function(items, result){
dojo.forEach(items, function(item){
jsonStore.setValue(item, "time" , data.update[0].netchange);
.....
'data' is the new data i need to set to the grid which is an json object as follows
var data = {"update":[{...}]}
what I need to do if the netchage is negative i need set cell color to red. if netchange is positive it should be green. So I need a way to change cell formatting dynamically. can some one please tell me how to this. thanks in advance
grid4 = new dojox.grid.DataGrid({
query : {
Title : '*'
},
id : "grid",
jsId : "grid",
clientSort : true,
rowSelector : '0px',
structure : layout4
}, document.createElement('div'));
grid4.setStore(jsonStore);
dojo.byId("gridContainer4").appendChild(grid4.domNode);
var layout4 = [ {
field : 'time',
name : 'time',
width : '40px',
formatter: geticon()
}, {
field : 'netchange',
name : 'netchange',
width : '30px'
} ];
Before I answer the question, just a trivial misnomer when you say, "change the cell formatting dynamically".
You aren't changing the cell formatter, you are changing how the cell is styled.
Every time a value is loaded into a cell, the formatter is called. Additionally, the onStyleROw function is called for the row that the cell is within.
This means that you have two options for changing the color of the cell. You can do it on a cell wide basis, or you can have your formatter do something simple like wrapping the value with a <span> that has a different style color. I'll show you both.
Here is the first solution without changing any of your existing grid code and it will change the entire row using onStyleRow.
Solution 1 using onStyleRow
Step 1. (Connect the onStyleRow)
dojo.connect( grid4, "onStyleRow", styleRowGridPayment );
Step 2. (Create you styleRowGridPayment method.)
var styleGridPayment = function(inRow) {
if( null !== grid4.getItem( inRow.index ) ) {
item = grid4.getItem( inRow.index );
if( item.netchange < 0 ) {
inRow.customStyles += "color:red;";
} else {
inRow.customStyles += "color:green;";
}
}
}
That should do it for using onStyleRow.
Solution 2, using the formatter
In your field declaration, you would have
{
field : 'netchange',
name : 'netchange',
width : '30px'
formatter: formatNetchange
}
Notice that I have added the formatNetchange as the formatter.
Then you just create your formatter.
formatNetchange = function(value){
if(value < 0){
color = "red";
} else {
color = "green";
}
return "<span style='color:" + color "'>" + value "</span>";
}

Categories