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