roojs-ui.js
[roojs1] / Roo / form / Action.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.form.Action
14  * Internal Class used to handle form actions
15  * @constructor
16  * @param {Roo.form.BasicForm} el The form element or its id
17  * @param {Object} config Configuration options
18  */
19  
20  
21 // define the action interface
22 Roo.form.Action = function(form, options){
23     this.form = form;
24     this.options = options || {};
25 };
26 /**
27  * Client Validation Failed
28  * @const 
29  */
30 Roo.form.Action.CLIENT_INVALID = 'client';
31 /**
32  * Server Validation Failed
33  * @const 
34  */
35  Roo.form.Action.SERVER_INVALID = 'server';
36  /**
37  * Connect to Server Failed
38  * @const 
39  */
40 Roo.form.Action.CONNECT_FAILURE = 'connect';
41 /**
42  * Reading Data from Server Failed
43  * @const 
44  */
45 Roo.form.Action.LOAD_FAILURE = 'load';
46
47 Roo.form.Action.prototype = {
48     type : 'default',
49     failureType : undefined,
50     response : undefined,
51     result : undefined,
52
53     // interface method
54     run : function(options){
55
56     },
57
58     // interface method
59     success : function(response){
60
61     },
62
63     // interface method
64     handleResponse : function(response){
65
66     },
67
68     // default connection failure
69     failure : function(response){
70         
71         this.response = response;
72         this.failureType = Roo.form.Action.CONNECT_FAILURE;
73         this.form.afterAction(this, false);
74     },
75
76     processResponse : function(response){
77         this.response = response;
78         if(!response.responseText){
79             return true;
80         }
81         this.result = this.handleResponse(response);
82         return this.result;
83     },
84
85     // utility functions used internally
86     getUrl : function(appendParams){
87         var url = this.options.url || this.form.url || this.form.el.dom.action;
88         if(appendParams){
89             var p = this.getParams();
90             if(p){
91                 url += (url.indexOf('?') != -1 ? '&' : '?') + p;
92             }
93         }
94         return url;
95     },
96
97     getMethod : function(){
98         return (this.options.method || this.form.method || this.form.el.dom.method || 'POST').toUpperCase();
99     },
100
101     getParams : function(){
102         var bp = this.form.baseParams;
103         var p = this.options.params;
104         if(p){
105             if(typeof p == "object"){
106                 p = Roo.urlEncode(Roo.applyIf(p, bp));
107             }else if(typeof p == 'string' && bp){
108                 p += '&' + Roo.urlEncode(bp);
109             }
110         }else if(bp){
111             p = Roo.urlEncode(bp);
112         }
113         return p;
114     },
115
116     createCallback : function(){
117         return {
118             success: this.success,
119             failure: this.failure,
120             scope: this,
121             timeout: (this.form.timeout*1000),
122             upload: this.form.fileUpload ? this.success : undefined
123         };
124     }
125 };
126
127 Roo.form.Action.Submit = function(form, options){
128     Roo.form.Action.Submit.superclass.constructor.call(this, form, options);
129 };
130
131 Roo.extend(Roo.form.Action.Submit, Roo.form.Action, {
132     type : 'submit',
133
134     haveProgress : false,
135     uploadComplete : false,
136     
137     // uploadProgress indicator.
138     uploadProgress : function()
139     {
140         if (!this.form.progressUrl) {
141             return;
142         }
143         
144         if (!this.haveProgress) {
145             Roo.MessageBox.progress("Uploading", "Uploading");
146         }
147         if (this.uploadComplete) {
148            Roo.MessageBox.hide();
149            return;
150         }
151         
152         this.haveProgress = true;
153    
154         var uid = this.form.findField('UPLOAD_IDENTIFIER').getValue();
155         
156         var c = new Roo.data.Connection();
157         c.request({
158             url : this.form.progressUrl,
159             params: {
160                 id : uid
161             },
162             method: 'GET',
163             success : function(req){
164                //console.log(data);
165                 var rdata = false;
166                 var edata;
167                 try  {
168                    rdata = Roo.decode(req.responseText)
169                 } catch (e) {
170                     Roo.log("Invalid data from server..");
171                     Roo.log(edata);
172                     return;
173                 }
174                 if (!rdata || !rdata.success) {
175                     Roo.log(rdata);
176                     return;
177                 }
178                 var data = rdata.data;
179                 
180                 if (this.uploadComplete) {
181                    Roo.MessageBox.hide();
182                    return;
183                 }
184                    
185                 if (data){
186                     Roo.MessageBox.updateProgress(data.bytes_uploaded/data.bytes_total,
187                        Math.floor((data.bytes_total - data.bytes_uploaded)/1000) + 'k remaining'
188                     );
189                 }
190                 this.uploadProgress.defer(2000,this);
191             },
192        
193             failure: function(data) {
194                 Roo.log('progress url failed ');
195                 Roo.log(data);
196             },
197             scope : this
198         });
199            
200     },
201     
202     
203     run : function()
204     {
205         // run get Values on the form, so it syncs any secondary forms.
206         this.form.getValues();
207         
208         var o = this.options;
209         var method = this.getMethod();
210         var isPost = method == 'POST';
211         if(o.clientValidation === false || this.form.isValid()){
212             
213             if (this.form.progressUrl) {
214                 this.form.findField('UPLOAD_IDENTIFIER').setValue(
215                     (new Date() * 1) + '' + Math.random());
216                     
217             } 
218             
219             
220             Roo.Ajax.request(Roo.apply(this.createCallback(), {
221                 form:this.form.el.dom,
222                 url:this.getUrl(!isPost),
223                 method: method,
224                 params:isPost ? this.getParams() : null,
225                 isUpload: this.form.fileUpload
226             }));
227             
228             this.uploadProgress();
229
230         }else if (o.clientValidation !== false){ // client validation failed
231             this.failureType = Roo.form.Action.CLIENT_INVALID;
232             this.form.afterAction(this, false);
233         }
234     },
235
236     success : function(response)
237     {
238         this.uploadComplete= true;
239         if (this.haveProgress) {
240             Roo.MessageBox.hide();
241         }
242         
243         
244         var result = this.processResponse(response);
245         if(result === true || result.success){
246             this.form.afterAction(this, true);
247             return;
248         }
249         if(result.errors){
250             this.form.markInvalid(result.errors);
251             this.failureType = Roo.form.Action.SERVER_INVALID;
252         }
253         this.form.afterAction(this, false);
254     },
255     failure : function(response)
256     {
257         this.uploadComplete= true;
258         if (this.haveProgress) {
259             Roo.MessageBox.hide();
260         }
261         
262         this.response = response;
263         this.failureType = Roo.form.Action.CONNECT_FAILURE;
264         this.form.afterAction(this, false);
265     },
266     
267     handleResponse : function(response){
268         if(this.form.errorReader){
269             var rs = this.form.errorReader.read(response);
270             var errors = [];
271             if(rs.records){
272                 for(var i = 0, len = rs.records.length; i < len; i++) {
273                     var r = rs.records[i];
274                     errors[i] = r.data;
275                 }
276             }
277             if(errors.length < 1){
278                 errors = null;
279             }
280             return {
281                 success : rs.success,
282                 errors : errors
283             };
284         }
285         var ret = false;
286         try {
287             ret = Roo.decode(response.responseText);
288         } catch (e) {
289             ret = {
290                 success: false,
291                 errorMsg: "Failed to read server message: " + (response ? response.responseText : ' - no message'),
292                 errors : []
293             };
294         }
295         return ret;
296         
297     }
298 });
299
300
301 Roo.form.Action.Load = function(form, options){
302     Roo.form.Action.Load.superclass.constructor.call(this, form, options);
303     this.reader = this.form.reader;
304 };
305
306 Roo.extend(Roo.form.Action.Load, Roo.form.Action, {
307     type : 'load',
308
309     run : function(){
310         
311         Roo.Ajax.request(Roo.apply(
312                 this.createCallback(), {
313                     method:this.getMethod(),
314                     url:this.getUrl(false),
315                     params:this.getParams()
316         }));
317     },
318
319     success : function(response){
320         
321         var result = this.processResponse(response);
322         if(result === true || !result.success || !result.data){
323             this.failureType = Roo.form.Action.LOAD_FAILURE;
324             this.form.afterAction(this, false);
325             return;
326         }
327         this.form.clearInvalid();
328         this.form.setValues(result.data);
329         this.form.afterAction(this, true);
330     },
331
332     handleResponse : function(response){
333         if(this.form.reader){
334             var rs = this.form.reader.read(response);
335             var data = rs.records && rs.records[0] ? rs.records[0].data : null;
336             return {
337                 success : rs.success,
338                 data : data
339             };
340         }
341         return Roo.decode(response.responseText);
342     }
343 });
344
345 Roo.form.Action.ACTION_TYPES = {
346     'load' : Roo.form.Action.Load,
347     'submit' : Roo.form.Action.Submit
348 };