Upgrade to ExtJS 3.2.0 - Released 03/30/2010
[extjs.git] / docs / source / PagingToolbar.html
1 <html>
2 <head>
3   <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />    
4   <title>The source code</title>
5     <link href="../resources/prettify/prettify.css" type="text/css" rel="stylesheet" />
6     <script type="text/javascript" src="../resources/prettify/prettify.js"></script>
7 </head>
8 <body  onload="prettyPrint();">
9     <pre class="prettyprint lang-js">/*!
10  * Ext JS Library 3.2.0
11  * Copyright(c) 2006-2010 Ext JS, Inc.
12  * licensing@extjs.com
13  * http://www.extjs.com/license
14  */
15 <div id="cls-Ext.PagingToolbar"></div>/**
16  * @class Ext.PagingToolbar
17  * @extends Ext.Toolbar
18  * <p>As the amount of records increases, the time required for the browser to render
19  * them increases. Paging is used to reduce the amount of data exchanged with the client.
20  * Note: if there are more records/rows than can be viewed in the available screen area, vertical
21  * scrollbars will be added.</p>
22  * <p>Paging is typically handled on the server side (see exception below). The client sends
23  * parameters to the server side, which the server needs to interpret and then respond with the
24  * approprate data.</p>
25  * <p><b>Ext.PagingToolbar</b> is a specialized toolbar that is bound to a {@link Ext.data.Store}
26  * and provides automatic paging control. This Component {@link Ext.data.Store#load load}s blocks
27  * of data into the <tt>{@link #store}</tt> by passing {@link Ext.data.Store#paramNames paramNames} used for
28  * paging criteria.</p>
29  * <p>PagingToolbar is typically used as one of the Grid's toolbars:</p>
30  * <pre><code>
31 Ext.QuickTips.init(); // to display button quicktips
32
33 var myStore = new Ext.data.Store({
34     reader: new Ext.data.JsonReader({
35         {@link Ext.data.JsonReader#totalProperty totalProperty}: 'results', 
36         ...
37     }),
38     ...
39 });
40
41 var myPageSize = 25;  // server script should only send back 25 items at a time
42
43 var grid = new Ext.grid.GridPanel({
44     ...
45     store: myStore,
46     bbar: new Ext.PagingToolbar({
47         {@link #store}: myStore,       // grid and PagingToolbar using same store
48         {@link #displayInfo}: true,
49         {@link #pageSize}: myPageSize,
50         {@link #prependButtons}: true,
51         items: [
52             'text 1'
53         ]
54     })
55 });
56  * </code></pre>
57  *
58  * <p>To use paging, pass the paging requirements to the server when the store is first loaded.</p>
59  * <pre><code>
60 store.load({
61     params: {
62         // specify params for the first page load if using paging
63         start: 0,          
64         limit: myPageSize,
65         // other params
66         foo:   'bar'
67     }
68 });
69  * </code></pre>
70  * 
71  * <p>If using {@link Ext.data.Store#autoLoad store's autoLoad} configuration:</p>
72  * <pre><code>
73 var myStore = new Ext.data.Store({
74     {@link Ext.data.Store#autoLoad autoLoad}: {params:{start: 0, limit: 25}},
75     ...
76 });
77  * </code></pre>
78  * 
79  * <p>The packet sent back from the server would have this form:</p>
80  * <pre><code>
81 {
82     "success": true,
83     "results": 2000, 
84     "rows": [ // <b>*Note:</b> this must be an Array 
85         { "id":  1, "name": "Bill", "occupation": "Gardener" },
86         { "id":  2, "name":  "Ben", "occupation": "Horticulturalist" },
87         ...
88         { "id": 25, "name":  "Sue", "occupation": "Botanist" }
89     ]
90 }
91  * </code></pre>
92  * <p><u>Paging with Local Data</u></p>
93  * <p>Paging can also be accomplished with local data using extensions:</p>
94  * <div class="mdetail-params"><ul>
95  * <li><a href="http://extjs.com/forum/showthread.php?t=71532">Ext.ux.data.PagingStore</a></li>
96  * <li>Paging Memory Proxy (examples/ux/PagingMemoryProxy.js)</li>
97  * </ul></div>
98  * @constructor Create a new PagingToolbar
99  * @param {Object} config The config object
100  * @xtype paging
101  */
102 (function() {
103
104 var T = Ext.Toolbar;
105
106 Ext.PagingToolbar = Ext.extend(Ext.Toolbar, {
107     <div id="cfg-Ext.PagingToolbar-store"></div>/**
108      * @cfg {Ext.data.Store} store
109      * The {@link Ext.data.Store} the paging toolbar should use as its data source (required).
110      */
111     <div id="cfg-Ext.PagingToolbar-displayInfo"></div>/**
112      * @cfg {Boolean} displayInfo
113      * <tt>true</tt> to display the displayMsg (defaults to <tt>false</tt>)
114      */
115     <div id="cfg-Ext.PagingToolbar-pageSize"></div>/**
116      * @cfg {Number} pageSize
117      * The number of records to display per page (defaults to <tt>20</tt>)
118      */
119     pageSize : 20,
120     <div id="cfg-Ext.PagingToolbar-prependButtons"></div>/**
121      * @cfg {Boolean} prependButtons
122      * <tt>true</tt> to insert any configured <tt>items</tt> <i>before</i> the paging buttons.
123      * Defaults to <tt>false</tt>.
124      */
125     <div id="cfg-Ext.PagingToolbar-displayMsg"></div>/**
126      * @cfg {String} displayMsg
127      * The paging status message to display (defaults to <tt>'Displaying {0} - {1} of {2}'</tt>).
128      * Note that this string is formatted using the braced numbers <tt>{0}-{2}</tt> as tokens
129      * that are replaced by the values for start, end and total respectively. These tokens should
130      * be preserved when overriding this string if showing those values is desired.
131      */
132     displayMsg : 'Displaying {0} - {1} of {2}',
133     <div id="cfg-Ext.PagingToolbar-emptyMsg"></div>/**
134      * @cfg {String} emptyMsg
135      * The message to display when no records are found (defaults to 'No data to display')
136      */
137     emptyMsg : 'No data to display',
138     <div id="cfg-Ext.PagingToolbar-beforePageText"></div>/**
139      * @cfg {String} beforePageText
140      * The text displayed before the input item (defaults to <tt>'Page'</tt>).
141      */
142     beforePageText : 'Page',
143     <div id="cfg-Ext.PagingToolbar-afterPageText"></div>/**
144      * @cfg {String} afterPageText
145      * Customizable piece of the default paging text (defaults to <tt>'of {0}'</tt>). Note that
146      * this string is formatted using <tt>{0}</tt> as a token that is replaced by the number of
147      * total pages. This token should be preserved when overriding this string if showing the
148      * total page count is desired.
149      */
150     afterPageText : 'of {0}',
151     <div id="cfg-Ext.PagingToolbar-firstText"></div>/**
152      * @cfg {String} firstText
153      * The quicktip text displayed for the first page button (defaults to <tt>'First Page'</tt>).
154      * <b>Note</b>: quick tips must be initialized for the quicktip to show.
155      */
156     firstText : 'First Page',
157     <div id="cfg-Ext.PagingToolbar-prevText"></div>/**
158      * @cfg {String} prevText
159      * The quicktip text displayed for the previous page button (defaults to <tt>'Previous Page'</tt>).
160      * <b>Note</b>: quick tips must be initialized for the quicktip to show.
161      */
162     prevText : 'Previous Page',
163     <div id="cfg-Ext.PagingToolbar-nextText"></div>/**
164      * @cfg {String} nextText
165      * The quicktip text displayed for the next page button (defaults to <tt>'Next Page'</tt>).
166      * <b>Note</b>: quick tips must be initialized for the quicktip to show.
167      */
168     nextText : 'Next Page',
169     <div id="cfg-Ext.PagingToolbar-lastText"></div>/**
170      * @cfg {String} lastText
171      * The quicktip text displayed for the last page button (defaults to <tt>'Last Page'</tt>).
172      * <b>Note</b>: quick tips must be initialized for the quicktip to show.
173      */
174     lastText : 'Last Page',
175     <div id="cfg-Ext.PagingToolbar-refreshText"></div>/**
176      * @cfg {String} refreshText
177      * The quicktip text displayed for the Refresh button (defaults to <tt>'Refresh'</tt>).
178      * <b>Note</b>: quick tips must be initialized for the quicktip to show.
179      */
180     refreshText : 'Refresh',
181
182     <div id="prop-Ext.PagingToolbar-paramNames"></div>/**
183      * <p><b>Deprecated</b>. <code>paramNames</code> should be set in the <b>data store</b>
184      * (see {@link Ext.data.Store#paramNames}).</p>
185      * <br><p>Object mapping of parameter names used for load calls, initially set to:</p>
186      * <pre>{start: 'start', limit: 'limit'}</pre>
187      * @type Object
188      * @property paramNames
189      * @deprecated
190      */
191
192     <div id="prop-Ext.PagingToolbar-pageSize"></div>/**
193      * The number of records to display per page.  See also <tt>{@link #cursor}</tt>.
194      * @type Number
195      * @property pageSize
196      */
197
198     <div id="prop-Ext.PagingToolbar-cursor"></div>/**
199      * Indicator for the record position.  This property might be used to get the active page
200      * number for example:<pre><code>
201      * // t is reference to the paging toolbar instance
202      * var activePage = Math.ceil((t.cursor + t.pageSize) / t.pageSize);
203      * </code></pre>
204      * @type Number
205      * @property cursor
206      */
207
208     initComponent : function(){
209         var pagingItems = [this.first = new T.Button({
210             tooltip: this.firstText,
211             overflowText: this.firstText,
212             iconCls: 'x-tbar-page-first',
213             disabled: true,
214             handler: this.moveFirst,
215             scope: this
216         }), this.prev = new T.Button({
217             tooltip: this.prevText,
218             overflowText: this.prevText,
219             iconCls: 'x-tbar-page-prev',
220             disabled: true,
221             handler: this.movePrevious,
222             scope: this
223         }), '-', this.beforePageText,
224         this.inputItem = new Ext.form.NumberField({
225             cls: 'x-tbar-page-number',
226             allowDecimals: false,
227             allowNegative: false,
228             enableKeyEvents: true,
229             selectOnFocus: true,
230             submitValue: false,
231             listeners: {
232                 scope: this,
233                 keydown: this.onPagingKeyDown,
234                 blur: this.onPagingBlur
235             }
236         }), this.afterTextItem = new T.TextItem({
237             text: String.format(this.afterPageText, 1)
238         }), '-', this.next = new T.Button({
239             tooltip: this.nextText,
240             overflowText: this.nextText,
241             iconCls: 'x-tbar-page-next',
242             disabled: true,
243             handler: this.moveNext,
244             scope: this
245         }), this.last = new T.Button({
246             tooltip: this.lastText,
247             overflowText: this.lastText,
248             iconCls: 'x-tbar-page-last',
249             disabled: true,
250             handler: this.moveLast,
251             scope: this
252         }), '-', this.refresh = new T.Button({
253             tooltip: this.refreshText,
254             overflowText: this.refreshText,
255             iconCls: 'x-tbar-loading',
256             handler: this.doRefresh,
257             scope: this
258         })];
259
260
261         var userItems = this.items || this.buttons || [];
262         if (this.prependButtons) {
263             this.items = userItems.concat(pagingItems);
264         }else{
265             this.items = pagingItems.concat(userItems);
266         }
267         delete this.buttons;
268         if(this.displayInfo){
269             this.items.push('->');
270             this.items.push(this.displayItem = new T.TextItem({}));
271         }
272         Ext.PagingToolbar.superclass.initComponent.call(this);
273         this.addEvents(
274             <div id="event-Ext.PagingToolbar-change"></div>/**
275              * @event change
276              * Fires after the active page has been changed.
277              * @param {Ext.PagingToolbar} this
278              * @param {Object} pageData An object that has these properties:<ul>
279              * <li><code>total</code> : Number <div class="sub-desc">The total number of records in the dataset as
280              * returned by the server</div></li>
281              * <li><code>activePage</code> : Number <div class="sub-desc">The current page number</div></li>
282              * <li><code>pages</code> : Number <div class="sub-desc">The total number of pages (calculated from
283              * the total number of records in the dataset as returned by the server and the current {@link #pageSize})</div></li>
284              * </ul>
285              */
286             'change',
287             <div id="event-Ext.PagingToolbar-beforechange"></div>/**
288              * @event beforechange
289              * Fires just before the active page is changed.
290              * Return false to prevent the active page from being changed.
291              * @param {Ext.PagingToolbar} this
292              * @param {Object} params An object hash of the parameters which the PagingToolbar will send when
293              * loading the required page. This will contain:<ul>
294              * <li><code>start</code> : Number <div class="sub-desc">The starting row number for the next page of records to
295              * be retrieved from the server</div></li>
296              * <li><code>limit</code> : Number <div class="sub-desc">The number of records to be retrieved from the server</div></li>
297              * </ul>
298              * <p>(note: the names of the <b>start</b> and <b>limit</b> properties are determined
299              * by the store's {@link Ext.data.Store#paramNames paramNames} property.)</p>
300              * <p>Parameters may be added as required in the event handler.</p>
301              */
302             'beforechange'
303         );
304         this.on('afterlayout', this.onFirstLayout, this, {single: true});
305         this.cursor = 0;
306         this.bindStore(this.store, true);
307     },
308
309     // private
310     onFirstLayout : function(){
311         if(this.dsLoaded){
312             this.onLoad.apply(this, this.dsLoaded);
313         }
314     },
315
316     // private
317     updateInfo : function(){
318         if(this.displayItem){
319             var count = this.store.getCount();
320             var msg = count == 0 ?
321                 this.emptyMsg :
322                 String.format(
323                     this.displayMsg,
324                     this.cursor+1, this.cursor+count, this.store.getTotalCount()
325                 );
326             this.displayItem.setText(msg);
327         }
328     },
329
330     // private
331     onLoad : function(store, r, o){
332         if(!this.rendered){
333             this.dsLoaded = [store, r, o];
334             return;
335         }
336         var p = this.getParams();
337         this.cursor = (o.params && o.params[p.start]) ? o.params[p.start] : 0;
338         var d = this.getPageData(), ap = d.activePage, ps = d.pages;
339
340         this.afterTextItem.setText(String.format(this.afterPageText, d.pages));
341         this.inputItem.setValue(ap);
342         this.first.setDisabled(ap == 1);
343         this.prev.setDisabled(ap == 1);
344         this.next.setDisabled(ap == ps);
345         this.last.setDisabled(ap == ps);
346         this.refresh.enable();
347         this.updateInfo();
348         this.fireEvent('change', this, d);
349     },
350
351     // private
352     getPageData : function(){
353         var total = this.store.getTotalCount();
354         return {
355             total : total,
356             activePage : Math.ceil((this.cursor+this.pageSize)/this.pageSize),
357             pages :  total < this.pageSize ? 1 : Math.ceil(total/this.pageSize)
358         };
359     },
360
361     <div id="method-Ext.PagingToolbar-changePage"></div>/**
362      * Change the active page
363      * @param {Integer} page The page to display
364      */
365     changePage : function(page){
366         this.doLoad(((page-1) * this.pageSize).constrain(0, this.store.getTotalCount()));
367     },
368
369     // private
370     onLoadError : function(){
371         if(!this.rendered){
372             return;
373         }
374         this.refresh.enable();
375     },
376
377     // private
378     readPage : function(d){
379         var v = this.inputItem.getValue(), pageNum;
380         if (!v || isNaN(pageNum = parseInt(v, 10))) {
381             this.inputItem.setValue(d.activePage);
382             return false;
383         }
384         return pageNum;
385     },
386
387     onPagingFocus : function(){
388         this.inputItem.select();
389     },
390
391     //private
392     onPagingBlur : function(e){
393         this.inputItem.setValue(this.getPageData().activePage);
394     },
395
396     // private
397     onPagingKeyDown : function(field, e){
398         var k = e.getKey(), d = this.getPageData(), pageNum;
399         if (k == e.RETURN) {
400             e.stopEvent();
401             pageNum = this.readPage(d);
402             if(pageNum !== false){
403                 pageNum = Math.min(Math.max(1, pageNum), d.pages) - 1;
404                 this.doLoad(pageNum * this.pageSize);
405             }
406         }else if (k == e.HOME || k == e.END){
407             e.stopEvent();
408             pageNum = k == e.HOME ? 1 : d.pages;
409             field.setValue(pageNum);
410         }else if (k == e.UP || k == e.PAGEUP || k == e.DOWN || k == e.PAGEDOWN){
411             e.stopEvent();
412             if((pageNum = this.readPage(d))){
413                 var increment = e.shiftKey ? 10 : 1;
414                 if(k == e.DOWN || k == e.PAGEDOWN){
415                     increment *= -1;
416                 }
417                 pageNum += increment;
418                 if(pageNum >= 1 & pageNum <= d.pages){
419                     field.setValue(pageNum);
420                 }
421             }
422         }
423     },
424
425     // private
426     getParams : function(){
427         //retain backwards compat, allow params on the toolbar itself, if they exist.
428         return this.paramNames || this.store.paramNames;
429     },
430
431     // private
432     beforeLoad : function(){
433         if(this.rendered && this.refresh){
434             this.refresh.disable();
435         }
436     },
437
438     // private
439     doLoad : function(start){
440         var o = {}, pn = this.getParams();
441         o[pn.start] = start;
442         o[pn.limit] = this.pageSize;
443         if(this.fireEvent('beforechange', this, o) !== false){
444             this.store.load({params:o});
445         }
446     },
447
448     <div id="method-Ext.PagingToolbar-moveFirst"></div>/**
449      * Move to the first page, has the same effect as clicking the 'first' button.
450      */
451     moveFirst : function(){
452         this.doLoad(0);
453     },
454
455     <div id="method-Ext.PagingToolbar-movePrevious"></div>/**
456      * Move to the previous page, has the same effect as clicking the 'previous' button.
457      */
458     movePrevious : function(){
459         this.doLoad(Math.max(0, this.cursor-this.pageSize));
460     },
461
462     <div id="method-Ext.PagingToolbar-moveNext"></div>/**
463      * Move to the next page, has the same effect as clicking the 'next' button.
464      */
465     moveNext : function(){
466         this.doLoad(this.cursor+this.pageSize);
467     },
468
469     <div id="method-Ext.PagingToolbar-moveLast"></div>/**
470      * Move to the last page, has the same effect as clicking the 'last' button.
471      */
472     moveLast : function(){
473         var total = this.store.getTotalCount(),
474             extra = total % this.pageSize;
475
476         this.doLoad(extra ? (total - extra) : total - this.pageSize);
477     },
478
479     <div id="method-Ext.PagingToolbar-doRefresh"></div>/**
480      * Refresh the current page, has the same effect as clicking the 'refresh' button.
481      */
482     doRefresh : function(){
483         this.doLoad(this.cursor);
484     },
485
486     <div id="method-Ext.PagingToolbar-bindStore"></div>/**
487      * Binds the paging toolbar to the specified {@link Ext.data.Store}
488      * @param {Store} store The store to bind to this toolbar
489      * @param {Boolean} initial (Optional) true to not remove listeners
490      */
491     bindStore : function(store, initial){
492         var doLoad;
493         if(!initial && this.store){
494             if(store !== this.store && this.store.autoDestroy){
495                 this.store.destroy();
496             }else{
497                 this.store.un('beforeload', this.beforeLoad, this);
498                 this.store.un('load', this.onLoad, this);
499                 this.store.un('exception', this.onLoadError, this);
500             }
501             if(!store){
502                 this.store = null;
503             }
504         }
505         if(store){
506             store = Ext.StoreMgr.lookup(store);
507             store.on({
508                 scope: this,
509                 beforeload: this.beforeLoad,
510                 load: this.onLoad,
511                 exception: this.onLoadError
512             });
513             doLoad = true;
514         }
515         this.store = store;
516         if(doLoad){
517             this.onLoad(store, null, {});
518         }
519     },
520
521     <div id="method-Ext.PagingToolbar-unbind"></div>/**
522      * Unbinds the paging toolbar from the specified {@link Ext.data.Store} <b>(deprecated)</b>
523      * @param {Ext.data.Store} store The data store to unbind
524      */
525     unbind : function(store){
526         this.bindStore(null);
527     },
528
529     <div id="method-Ext.PagingToolbar-bind"></div>/**
530      * Binds the paging toolbar to the specified {@link Ext.data.Store} <b>(deprecated)</b>
531      * @param {Ext.data.Store} store The data store to bind
532      */
533     bind : function(store){
534         this.bindStore(store);
535     },
536
537     // private
538     onDestroy : function(){
539         this.bindStore(null);
540         Ext.PagingToolbar.superclass.onDestroy.call(this);
541     }
542 });
543
544 })();
545 Ext.reg('paging', Ext.PagingToolbar);</pre>    
546 </body>
547 </html>