Upgrade to ExtJS 3.0.3 - Released 10/11/2009
[extjs.git] / src / widgets / PagingToolbar.js
1 /*!
2  * Ext JS Library 3.0.3
3  * Copyright(c) 2006-2009 Ext JS, LLC
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             listeners: {
223                 scope: this,
224                 keydown: this.onPagingKeyDown,
225                 blur: this.onPagingBlur
226             }
227         }), this.afterTextItem = new T.TextItem({
228             text: String.format(this.afterPageText, 1)
229         }), '-', this.next = new T.Button({
230             tooltip: this.nextText,
231             overflowText: this.nextText,
232             iconCls: 'x-tbar-page-next',
233             disabled: true,
234             handler: this.moveNext,
235             scope: this
236         }), this.last = new T.Button({
237             tooltip: this.lastText,
238             overflowText: this.lastText,
239             iconCls: 'x-tbar-page-last',
240             disabled: true,
241             handler: this.moveLast,
242             scope: this
243         }), '-', this.refresh = new T.Button({
244             tooltip: this.refreshText,
245             overflowText: this.refreshText,
246             iconCls: 'x-tbar-loading',
247             handler: this.doRefresh,
248             scope: this
249         })];
250
251
252         var userItems = this.items || this.buttons || [];
253         if (this.prependButtons) {
254             this.items = userItems.concat(pagingItems);
255         }else{
256             this.items = pagingItems.concat(userItems);
257         }
258         delete this.buttons;
259         if(this.displayInfo){
260             this.items.push('->');
261             this.items.push(this.displayItem = new T.TextItem({}));
262         }
263         Ext.PagingToolbar.superclass.initComponent.call(this);
264         this.addEvents(
265             /**
266              * @event change
267              * Fires after the active page has been changed.
268              * @param {Ext.PagingToolbar} this
269              * @param {Object} pageData An object that has these properties:<ul>
270              * <li><code>total</code> : Number <div class="sub-desc">The total number of records in the dataset as
271              * returned by the server</div></li>
272              * <li><code>activePage</code> : Number <div class="sub-desc">The current page number</div></li>
273              * <li><code>pages</code> : Number <div class="sub-desc">The total number of pages (calculated from
274              * the total number of records in the dataset as returned by the server and the current {@link #pageSize})</div></li>
275              * </ul>
276              */
277             'change',
278             /**
279              * @event beforechange
280              * Fires just before the active page is changed.
281              * Return false to prevent the active page from being changed.
282              * @param {Ext.PagingToolbar} this
283              * @param {Object} params An object hash of the parameters which the PagingToolbar will send when
284              * loading the required page. This will contain:<ul>
285              * <li><code>start</code> : Number <div class="sub-desc">The starting row number for the next page of records to
286              * be retrieved from the server</div></li>
287              * <li><code>limit</code> : Number <div class="sub-desc">The number of records to be retrieved from the server</div></li>
288              * </ul>
289              * <p>(note: the names of the <b>start</b> and <b>limit</b> properties are determined
290              * by the store's {@link Ext.data.Store#paramNames paramNames} property.)</p>
291              * <p>Parameters may be added as required in the event handler.</p>
292              */
293             'beforechange'
294         );
295         this.on('afterlayout', this.onFirstLayout, this, {single: true});
296         this.cursor = 0;
297         this.bindStore(this.store, true);
298     },
299
300     // private
301     onFirstLayout : function(){
302         if(this.dsLoaded){
303             this.onLoad.apply(this, this.dsLoaded);
304         }
305     },
306
307     // private
308     updateInfo : function(){
309         if(this.displayItem){
310             var count = this.store.getCount();
311             var msg = count == 0 ?
312                 this.emptyMsg :
313                 String.format(
314                     this.displayMsg,
315                     this.cursor+1, this.cursor+count, this.store.getTotalCount()
316                 );
317             this.displayItem.setText(msg);
318         }
319     },
320
321     // private
322     onLoad : function(store, r, o){
323         if(!this.rendered){
324             this.dsLoaded = [store, r, o];
325             return;
326         }
327         var p = this.getParams();
328         this.cursor = (o.params && o.params[p.start]) ? o.params[p.start] : 0;
329         var d = this.getPageData(), ap = d.activePage, ps = d.pages;
330
331         this.afterTextItem.setText(String.format(this.afterPageText, d.pages));
332         this.inputItem.setValue(ap);
333         this.first.setDisabled(ap == 1);
334         this.prev.setDisabled(ap == 1);
335         this.next.setDisabled(ap == ps);
336         this.last.setDisabled(ap == ps);
337         this.refresh.enable();
338         this.updateInfo();
339         this.fireEvent('change', this, d);
340     },
341
342     // private
343     getPageData : function(){
344         var total = this.store.getTotalCount();
345         return {
346             total : total,
347             activePage : Math.ceil((this.cursor+this.pageSize)/this.pageSize),
348             pages :  total < this.pageSize ? 1 : Math.ceil(total/this.pageSize)
349         };
350     },
351
352     /**
353      * Change the active page
354      * @param {Integer} page The page to display
355      */
356     changePage : function(page){
357         this.doLoad(((page-1) * this.pageSize).constrain(0, this.store.getTotalCount()));
358     },
359
360     // private
361     onLoadError : function(){
362         if(!this.rendered){
363             return;
364         }
365         this.refresh.enable();
366     },
367
368     // private
369     readPage : function(d){
370         var v = this.inputItem.getValue(), pageNum;
371         if (!v || isNaN(pageNum = parseInt(v, 10))) {
372             this.inputItem.setValue(d.activePage);
373             return false;
374         }
375         return pageNum;
376     },
377
378     onPagingFocus : function(){
379         this.inputItem.select();
380     },
381
382     //private
383     onPagingBlur : function(e){
384         this.inputItem.setValue(this.getPageData().activePage);
385     },
386
387     // private
388     onPagingKeyDown : function(field, e){
389         var k = e.getKey(), d = this.getPageData(), pageNum;
390         if (k == e.RETURN) {
391             e.stopEvent();
392             pageNum = this.readPage(d);
393             if(pageNum !== false){
394                 pageNum = Math.min(Math.max(1, pageNum), d.pages) - 1;
395                 this.doLoad(pageNum * this.pageSize);
396             }
397         }else if (k == e.HOME || k == e.END){
398             e.stopEvent();
399             pageNum = k == e.HOME ? 1 : d.pages;
400             field.setValue(pageNum);
401         }else if (k == e.UP || k == e.PAGEUP || k == e.DOWN || k == e.PAGEDOWN){
402             e.stopEvent();
403             if((pageNum = this.readPage(d))){
404                 var increment = e.shiftKey ? 10 : 1;
405                 if(k == e.DOWN || k == e.PAGEDOWN){
406                     increment *= -1;
407                 }
408                 pageNum += increment;
409                 if(pageNum >= 1 & pageNum <= d.pages){
410                     field.setValue(pageNum);
411                 }
412             }
413         }
414     },
415
416     // private
417     getParams : function(){
418         //retain backwards compat, allow params on the toolbar itself, if they exist.
419         return this.paramNames || this.store.paramNames;
420     },
421
422     // private
423     getParams : function(){
424         //retain backwards compat, allow params on the toolbar itself, if they exist.
425         return this.paramNames || this.store.paramNames;
426     },
427
428     // private
429     beforeLoad : function(){
430         if(this.rendered && this.refresh){
431             this.refresh.disable();
432         }
433     },
434
435     // private
436     doLoad : function(start){
437         var o = {}, pn = this.getParams();
438         o[pn.start] = start;
439         o[pn.limit] = this.pageSize;
440         if(this.fireEvent('beforechange', this, o) !== false){
441             this.store.load({params:o});
442         }
443     },
444
445     /**
446      * Move to the first page, has the same effect as clicking the 'first' button.
447      */
448     moveFirst : function(){
449         this.doLoad(0);
450     },
451
452     /**
453      * Move to the previous page, has the same effect as clicking the 'previous' button.
454      */
455     movePrevious : function(){
456         this.doLoad(Math.max(0, this.cursor-this.pageSize));
457     },
458
459     /**
460      * Move to the next page, has the same effect as clicking the 'next' button.
461      */
462     moveNext : function(){
463         this.doLoad(this.cursor+this.pageSize);
464     },
465
466     /**
467      * Move to the last page, has the same effect as clicking the 'last' button.
468      */
469     moveLast : function(){
470         var total = this.store.getTotalCount(),
471             extra = total % this.pageSize;
472
473         this.doLoad(extra ? (total - extra) : total - this.pageSize);
474     },
475
476     /**
477      * Refresh the current page, has the same effect as clicking the 'refresh' button.
478      */
479     doRefresh : function(){
480         this.doLoad(this.cursor);
481     },
482
483     /**
484      * Binds the paging toolbar to the specified {@link Ext.data.Store}
485      * @param {Store} store The store to bind to this toolbar
486      * @param {Boolean} initial (Optional) true to not remove listeners
487      */
488     bindStore : function(store, initial){
489         var doLoad;
490         if(!initial && this.store){
491             if(store !== this.store && this.store.autoDestroy){
492                 this.store.destroy();
493             }else{
494                 this.store.un('beforeload', this.beforeLoad, this);
495                 this.store.un('load', this.onLoad, this);
496                 this.store.un('exception', this.onLoadError, this);
497             }
498             if(!store){
499                 this.store = null;
500             }
501         }
502         if(store){
503             store = Ext.StoreMgr.lookup(store);
504             store.on({
505                 scope: this,
506                 beforeload: this.beforeLoad,
507                 load: this.onLoad,
508                 exception: this.onLoadError
509             });
510             doLoad = true;
511         }
512         this.store = store;
513         if(doLoad){
514             this.onLoad(store, null, {});
515         }
516     },
517
518     /**
519      * Unbinds the paging toolbar from the specified {@link Ext.data.Store} <b>(deprecated)</b>
520      * @param {Ext.data.Store} store The data store to unbind
521      */
522     unbind : function(store){
523         this.bindStore(null);
524     },
525
526     /**
527      * Binds the paging toolbar to the specified {@link Ext.data.Store} <b>(deprecated)</b>
528      * @param {Ext.data.Store} store The data store to bind
529      */
530     bind : function(store){
531         this.bindStore(store);
532     },
533
534     // private
535     onDestroy : function(){
536         this.bindStore(null);
537         Ext.PagingToolbar.superclass.onDestroy.call(this);
538     }
539 });
540
541 })();
542 Ext.reg('paging', Ext.PagingToolbar);