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