Roo/form/Action.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         this.response = response;
71         this.failureType = Roo.form.Action.CONNECT_FAILURE;
72         this.form.afterAction(this, false);
73     },
74
75     processResponse : function(response){
76         this.response = response;
77         if(!response.responseText){
78             return true;
79         }
80         this.result = this.handleResponse(response);
81         return this.result;
82     },
83
84     // utility functions used internally
85     getUrl : function(appendParams){
86         var url = this.options.url || this.form.url || this.form.el.dom.action;
87         if(appendParams){
88             var p = this.getParams();
89             if(p){
90                 url += (url.indexOf('?') != -1 ? '&' : '?') + p;
91             }
92         }
93         return url;
94     },
95
96     getMethod : function(){
97         return (this.options.method || this.form.method || this.form.el.dom.method || 'POST').toUpperCase();
98     },
99
100     getParams : function(){
101         var bp = this.form.baseParams;
102         var p = this.options.params;
103         if(p){
104             if(typeof p == "object"){
105                 p = Roo.urlEncode(Roo.applyIf(p, bp));
106             }else if(typeof p == 'string' && bp){
107                 p += '&' + Roo.urlEncode(bp);
108             }
109         }else if(bp){
110             p = Roo.urlEncode(bp);
111         }
112         return p;
113     },
114
115     createCallback : function(){
116         return {
117             success: this.success,
118             failure: this.failure,
119             scope: this,
120             timeout: (this.form.timeout*1000),
121             upload: this.form.fileUpload ? this.success : undefined
122         };
123     }
124 };
125
126 Roo.form.Action.Submit = function(form, options){
127     Roo.form.Action.Submit.superclass.constructor.call(this, form, options);
128 };
129
130 Roo.extend(Roo.form.Action.Submit, Roo.form.Action, {
131     type : 'submit',
132
133     haveProgress : false,
134     uploadComplete : false,
135     
136     // uploadPrograss indicator.
137     uploadProgress : function()
138     {
139         
140         if (!this.haveProgress) {
141             Roo.MessageBox.progress("Uploading", "Uploading");
142         }
143         if (this.uploadComplete) {
144            Roo.MessageBox.hide();
145            return;
146         }
147         
148         this.haveProgress = true;
149    
150         var uid = this.form.findField('UPLOAD_IDENTIFIER').getValue();
151         
152         var c = new Roo.data.Connection();
153         c.request({
154             url : this.form.progressUrl,
155             params: {
156                 id : uid
157             },
158             method: 'GET',
159             success : function(data){
160                //console.log(data);
161                 if (this.uploadComplete) {
162                    Roo.MessageBox.hide();
163                    return;
164                 }
165                    
166                 if (data){
167                     Roo.MessageBox.updateProgress(data.bytes_uploaded/data.bytes_total,
168                        Math.floor((data.bytes_total - data.bytes_uploaded)/1000) + 'k remaining'
169                     );
170                 }
171                 this.uploadProgress.defer(2000,this);
172             },
173             scope : this,
174            failure: function(data) {
175                 Roo.log('progress url failed ');
176                 Roo.log(data);
177            }
178         });
179            
180     },
181     
182     
183     run : function()
184     {
185         // run get Values on the form, so it syncs any secondary forms.
186         this.form.getValues();
187         
188         var o = this.options;
189         var method = this.getMethod();
190         var isPost = method == 'POST';
191         if(o.clientValidation === false || this.form.isValid()){
192             if (this.form.progressUrl) {
193                 
194                 
195                 // use upload progress bar..
196                 this.findField('UPLOAD_IDENTIFIER').setValue(
197                     (new Date() * 1) + '' + Math.random());
198                     
199                     
200             }
201             
202             
203             
204             Roo.Ajax.request(Roo.apply(this.createCallback(), {
205                 form:this.form.el.dom,
206                 url:this.getUrl(!isPost),
207                 method: method,
208                 params:isPost ? this.getParams() : null,
209                 isUpload: this.form.fileUpload
210             }));
211
212         }else if (o.clientValidation !== false){ // client validation failed
213             this.failureType = Roo.form.Action.CLIENT_INVALID;
214             this.form.afterAction(this, false);
215         }
216     },
217
218     success : function(response)
219     {
220         this.uploadComplete= true;
221         if (this.haveProgress) {
222             Roo.MessageBox.hide();
223         }
224         
225         var result = this.processResponse(response);
226         if(result === true || result.success){
227             this.form.afterAction(this, true);
228             return;
229         }
230         if(result.errors){
231             this.form.markInvalid(result.errors);
232             this.failureType = Roo.form.Action.SERVER_INVALID;
233         }
234         this.form.afterAction(this, false);
235     },
236     failure : function(response)
237     {
238         this.uploadComplete= true;
239         if (this.haveProgress) {
240             Roo.MessageBox.hide();
241         }
242         
243         this.response = response;
244         this.failureType = Roo.form.Action.CONNECT_FAILURE;
245         this.form.afterAction(this, false);
246     },
247     
248     handleResponse : function(response){
249         if(this.form.errorReader){
250             var rs = this.form.errorReader.read(response);
251             var errors = [];
252             if(rs.records){
253                 for(var i = 0, len = rs.records.length; i < len; i++) {
254                     var r = rs.records[i];
255                     errors[i] = r.data;
256                 }
257             }
258             if(errors.length < 1){
259                 errors = null;
260             }
261             return {
262                 success : rs.success,
263                 errors : errors
264             };
265         }
266         var ret = false;
267         try {
268             ret = Roo.decode(response.responseText);
269         } catch (e) {
270             ret = {
271                 success: false,
272                 errorMsg: "Failed to read server message: " + (response ? response.responseText : ' - no message'),
273                 errors : []
274             };
275         }
276         return ret;
277         
278     }
279 });
280
281
282 Roo.form.Action.Load = function(form, options){
283     Roo.form.Action.Load.superclass.constructor.call(this, form, options);
284     this.reader = this.form.reader;
285 };
286
287 Roo.extend(Roo.form.Action.Load, Roo.form.Action, {
288     type : 'load',
289
290     run : function(){
291         Roo.Ajax.request(Roo.apply(
292                 this.createCallback(), {
293                     method:this.getMethod(),
294                     url:this.getUrl(false),
295                     params:this.getParams()
296         }));
297     },
298
299     success : function(response){
300         var result = this.processResponse(response);
301         if(result === true || !result.success || !result.data){
302             this.failureType = Roo.form.Action.LOAD_FAILURE;
303             this.form.afterAction(this, false);
304             return;
305         }
306         this.form.clearInvalid();
307         this.form.setValues(result.data);
308         this.form.afterAction(this, true);
309     },
310
311     handleResponse : function(response){
312         if(this.form.reader){
313             var rs = this.form.reader.read(response);
314             var data = rs.records && rs.records[0] ? rs.records[0].data : null;
315             return {
316                 success : rs.success,
317                 data : data
318             };
319         }
320         return Roo.decode(response.responseText);
321     }
322 });
323
324 Roo.form.Action.ACTION_TYPES = {
325     'load' : Roo.form.Action.Load,
326     'submit' : Roo.form.Action.Submit
327 };