handle exception on store load if paging toolbar is used
[roojs1] / Roo / bootstrap / PagingToolbar.js
1 /*
2  * Based on:
3  * Ext JS Library 1.1.1
4  * Copyright(c) 2006-2007, Ext JS, LLC.
5  *
6  * Originally Released Under LGPL - original licence link has changed is not relivant.
7  *
8  * Fork - LGPL
9  * <script type="text/javascript">
10  */
11  
12 /**
13  * @class Roo.bootstrap.PagingToolbar
14  * @extends Roo.bootstrap.nav.Simplebar
15  * A specialized toolbar that is bound to a {@link Roo.data.Store} and provides automatic paging controls.
16  * @constructor
17  * Create a new PagingToolbar
18  * @param {Object} config The config object
19  * @param {Roo.data.Store} store
20  */
21 Roo.bootstrap.PagingToolbar = function(config)
22 {
23     // old args format still supported... - xtype is prefered..
24         // created from xtype...
25     
26     this.ds = config.dataSource;
27     
28     if (config.store && !this.ds) {
29         this.store= Roo.factory(config.store, Roo.data);
30         this.ds = this.store;
31         this.ds.xmodule = this.xmodule || false;
32     }
33     
34     this.toolbarItems = [];
35     if (config.items) {
36         this.toolbarItems = config.items;
37     }
38     
39     Roo.bootstrap.PagingToolbar.superclass.constructor.call(this, config);
40     
41     this.cursor = 0;
42     
43     if (this.ds) { 
44         this.bind(this.ds);
45     }
46     
47     if (Roo.bootstrap.version == 4) {
48         this.navgroup = new Roo.bootstrap.ButtonGroup({ cls: 'pagination' });
49     } else {
50         this.navgroup = new Roo.bootstrap.nav.Group({ cls: 'pagination' });
51     }
52     
53 };
54
55 Roo.extend(Roo.bootstrap.PagingToolbar, Roo.bootstrap.nav.Simplebar, {
56     /**
57      * @cfg {Roo.bootstrap.Button} buttons[]
58      * Buttons for the toolbar
59      */
60      /**
61      * @cfg {Roo.data.Store} store
62      * The underlying data store providing the paged data
63      */
64     /**
65      * @cfg {String/HTMLElement/Element} container
66      * container The id or element that will contain the toolbar
67      */
68     /**
69      * @cfg {Boolean} displayInfo
70      * True to display the displayMsg (defaults to false)
71      */
72     /**
73      * @cfg {Number} pageSize
74      * The number of records to display per page (defaults to 20)
75      */
76     pageSize: 20,
77     /**
78      * @cfg {String} displayMsg
79      * The paging status message to display (defaults to "Displaying {start} - {end} of {total}")
80      */
81     displayMsg : 'Displaying {0} - {1} of {2}',
82     /**
83      * @cfg {String} emptyMsg
84      * The message to display when no records are found (defaults to "No data to display")
85      */
86     emptyMsg : 'No data to display',
87     /**
88      * Customizable piece of the default paging text (defaults to "Page")
89      * @type String
90      */
91     beforePageText : "Page",
92     /**
93      * Customizable piece of the default paging text (defaults to "of %0")
94      * @type String
95      */
96     afterPageText : "of {0}",
97     /**
98      * Customizable piece of the default paging text (defaults to "First Page")
99      * @type String
100      */
101     firstText : "First Page",
102     /**
103      * Customizable piece of the default paging text (defaults to "Previous Page")
104      * @type String
105      */
106     prevText : "Previous Page",
107     /**
108      * Customizable piece of the default paging text (defaults to "Next Page")
109      * @type String
110      */
111     nextText : "Next Page",
112     /**
113      * Customizable piece of the default paging text (defaults to "Last Page")
114      * @type String
115      */
116     lastText : "Last Page",
117     /**
118      * Customizable piece of the default paging text (defaults to "Refresh")
119      * @type String
120      */
121     refreshText : "Refresh",
122
123     buttons : false,
124     // private
125     onRender : function(ct, position) 
126     {
127         Roo.bootstrap.PagingToolbar.superclass.onRender.call(this, ct, position);
128         this.navgroup.parentId = this.id;
129         this.navgroup.onRender(this.el, null);
130         // add the buttons to the navgroup
131         
132         if(this.displayInfo){
133             this.el.select('ul.navbar-nav',true).first().createChild({cls:'x-paging-info'});
134             this.displayEl = this.el.select('.x-paging-info', true).first();
135 //            var navel = this.navgroup.addItem( { tagtype : 'span', html : '', cls : 'x-paging-info', preventDefault : true } );
136 //            this.displayEl = navel.el.select('span',true).first();
137         }
138         
139         var _this = this;
140         
141         if(this.buttons){
142             Roo.each(_this.buttons, function(e){ // this might need to use render????
143                Roo.factory(e).render(_this.el);
144             });
145         }
146             
147         Roo.each(_this.toolbarItems, function(e) {
148             _this.navgroup.addItem(e);
149         });
150         
151         
152         this.first = this.navgroup.addItem({
153             tooltip: this.firstText,
154             cls: "prev btn-outline-secondary",
155             html : ' <i class="fa fa-step-backward"></i>',
156             disabled: true,
157             preventDefault: true,
158             listeners : { click : this.onClick.createDelegate(this, ["first"]) }
159         });
160         
161         this.prev =  this.navgroup.addItem({
162             tooltip: this.prevText,
163             cls: "prev btn-outline-secondary",
164             html : ' <i class="fa fa-backward"></i>',
165             disabled: true,
166             preventDefault: true,
167             listeners : { click :  this.onClick.createDelegate(this, ["prev"]) }
168         });
169     //this.addSeparator();
170         
171         
172         var field = this.navgroup.addItem( {
173             tagtype : 'span',
174             cls : 'x-paging-position  btn-outline-secondary',
175              disabled: true,
176             html : this.beforePageText  +
177                 '<input type="text" size="3" value="1" class="x-grid-page-number">' +
178                 '<span class="x-paging-after">' +  String.format(this.afterPageText, 1) + '</span>'
179          } ); //?? escaped?
180         
181         this.field = field.el.select('input', true).first();
182         this.field.on("keydown", this.onPagingKeydown, this);
183         this.field.on("focus", function(){this.dom.select();});
184     
185     
186         this.afterTextEl =  field.el.select('.x-paging-after',true).first();
187         //this.field.setHeight(18);
188         //this.addSeparator();
189         this.next = this.navgroup.addItem({
190             tooltip: this.nextText,
191             cls: "next btn-outline-secondary",
192             html : ' <i class="fa fa-forward"></i>',
193             disabled: true,
194             preventDefault: true,
195             listeners : { click :  this.onClick.createDelegate(this, ["next"]) }
196         });
197         this.last = this.navgroup.addItem({
198             tooltip: this.lastText,
199             html : ' <i class="fa fa-step-forward"></i>',
200             cls: "next btn-outline-secondary",
201             disabled: true,
202             preventDefault: true,
203             listeners : { click :  this.onClick.createDelegate(this, ["last"]) }
204         });
205     //this.addSeparator();
206         this.loading = this.navgroup.addItem({
207             tooltip: this.refreshText,
208             cls: "btn-outline-secondary",
209             html : ' <i class="fa fa-refresh"></i>',
210             preventDefault: true,
211             listeners : { click : this.onClick.createDelegate(this, ["refresh"]) }
212         });
213         
214     },
215
216     // private
217     updateInfo : function(){
218         if(this.displayEl){
219             var count = (typeof(this.getCount) == 'undefined') ? this.ds.getCount() : this.getCount();
220             var msg = count == 0 ?
221                 this.emptyMsg :
222                 String.format(
223                     this.displayMsg,
224                     this.cursor+1, this.cursor+count, this.ds.getTotalCount()    
225                 );
226             this.displayEl.update(msg);
227         }
228     },
229
230     // private
231     onLoad : function(ds, r, o)
232     {
233         this.cursor = o.params && o.params.start ? o.params.start : 0;
234         
235         var d = this.getPageData(),
236             ap = d.activePage,
237             ps = d.pages;
238         
239         
240         this.afterTextEl.dom.innerHTML = String.format(this.afterPageText, d.pages);
241         this.field.dom.value = ap;
242         this.first.setDisabled(ap == 1);
243         this.prev.setDisabled(ap == 1);
244         this.next.setDisabled(ap == ps);
245         this.last.setDisabled(ap == ps);
246         this.loading.enable();
247         this.updateInfo();
248     },
249
250     // private
251     getPageData : function(){
252         var total = this.ds.getTotalCount();
253         return {
254             total : total,
255             activePage : Math.ceil((this.cursor+this.pageSize)/this.pageSize),
256             pages :  total < this.pageSize ? 1 : Math.ceil(total/this.pageSize)
257         };
258     },
259
260     // private
261     onLoadError : function(o){
262         this.loading.enable();
263         if (this.ds.events.loadexception.listeners.length  < 2) {
264             // nothing has been assigned to loadexception except this...
265             // so 
266             Roo.MessageBox.alert("Error loading",o.raw.errorMsg);
267
268         }
269     },
270
271     // private
272     onPagingKeydown : function(e){
273         var k = e.getKey();
274         var d = this.getPageData();
275         if(k == e.RETURN){
276             var v = this.field.dom.value, pageNum;
277             if(!v || isNaN(pageNum = parseInt(v, 10))){
278                 this.field.dom.value = d.activePage;
279                 return;
280             }
281             pageNum = Math.min(Math.max(1, pageNum), d.pages) - 1;
282             this.ds.load({params:{start: pageNum * this.pageSize, limit: this.pageSize}});
283             e.stopEvent();
284         }
285         else if(k == e.HOME || (k == e.UP && e.ctrlKey) || (k == e.PAGEUP && e.ctrlKey) || (k == e.RIGHT && e.ctrlKey) || k == e.END || (k == e.DOWN && e.ctrlKey) || (k == e.LEFT && e.ctrlKey) || (k == e.PAGEDOWN && e.ctrlKey))
286         {
287           var pageNum = (k == e.HOME || (k == e.DOWN && e.ctrlKey) || (k == e.LEFT && e.ctrlKey) || (k == e.PAGEDOWN && e.ctrlKey)) ? 1 : d.pages;
288           this.field.dom.value = pageNum;
289           this.ds.load({params:{start: (pageNum - 1) * this.pageSize, limit: this.pageSize}});
290           e.stopEvent();
291         }
292         else if(k == e.UP || k == e.RIGHT || k == e.PAGEUP || k == e.DOWN || k == e.LEFT || k == e.PAGEDOWN)
293         {
294           var v = this.field.dom.value, pageNum; 
295           var increment = (e.shiftKey) ? 10 : 1;
296           if(k == e.DOWN || k == e.LEFT || k == e.PAGEDOWN) {
297                 increment *= -1;
298           }
299           if(!v || isNaN(pageNum = parseInt(v, 10))) {
300             this.field.dom.value = d.activePage;
301             return;
302           }
303           else if(parseInt(v, 10) + increment >= 1 & parseInt(v, 10) + increment <= d.pages)
304           {
305             this.field.dom.value = parseInt(v, 10) + increment;
306             pageNum = Math.min(Math.max(1, pageNum + increment), d.pages) - 1;
307             this.ds.load({params:{start: pageNum * this.pageSize, limit: this.pageSize}});
308           }
309           e.stopEvent();
310         }
311     },
312
313     // private
314     beforeLoad : function(){
315         if(this.loading){
316             this.loading.disable();
317         }
318     },
319
320     // private
321     onClick : function(which){
322         
323         var ds = this.ds;
324         if (!ds) {
325             return;
326         }
327         
328         switch(which){
329             case "first":
330                 ds.load({params:{start: 0, limit: this.pageSize}});
331             break;
332             case "prev":
333                 ds.load({params:{start: Math.max(0, this.cursor-this.pageSize), limit: this.pageSize}});
334             break;
335             case "next":
336                 ds.load({params:{start: this.cursor+this.pageSize, limit: this.pageSize}});
337             break;
338             case "last":
339                 var total = ds.getTotalCount();
340                 var extra = total % this.pageSize;
341                 var lastStart = extra ? (total - extra) : total-this.pageSize;
342                 ds.load({params:{start: lastStart, limit: this.pageSize}});
343             break;
344             case "refresh":
345                 ds.load({params:{start: this.cursor, limit: this.pageSize}});
346             break;
347         }
348     },
349
350     /**
351      * Unbinds the paging toolbar from the specified {@link Roo.data.Store}
352      * @param {Roo.data.Store} store The data store to unbind
353      */
354     unbind : function(ds){
355         ds.un("beforeload", this.beforeLoad, this);
356         ds.un("load", this.onLoad, this);
357         ds.un("loadexception", this.onLoadError, this);
358         ds.un("remove", this.updateInfo, this);
359         ds.un("add", this.updateInfo, this);
360         this.ds = undefined;
361     },
362
363     /**
364      * Binds the paging toolbar to the specified {@link Roo.data.Store}
365      * @param {Roo.data.Store} store The data store to bind
366      */
367     bind : function(ds){
368         ds.on("beforeload", this.beforeLoad, this);
369         ds.on("load", this.onLoad, this);
370         ds.on("loadexception", this.onLoadError, this);
371         ds.on("remove", this.updateInfo, this);
372         ds.on("add", this.updateInfo, this);
373         this.ds = ds;
374     }
375 });