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     
134     uploadProgress : function()
135     {
136         var dlg = this;
137         if (!dlg.haveProgress) {
138            Roo.MessageBox.progress("Uploading", "Uploading");
139         }
140         if (dlg.uploadComplete) {
141            Roo.MessageBox.hide();
142            return;
143         }
144         dlg.haveProgress = true;
145    
146         var uid = this.form.findField('UPLOAD_IDENTIFIER').getValue();
147         Pman.request({
148            url : this.form.progressUrl,
149            params: {
150                id : uid
151            },
152            method: 'GET',
153            success : function(data){
154                //console.log(data);
155                if (dlg.uploadComplete) {
156                    Roo.MessageBox.hide();
157                    return;
158                }
159                    
160                if (data){
161                    Roo.MessageBox.updateProgress(data.bytes_uploaded/data.bytes_total,
162                        Math.floor((data.bytes_total - data.bytes_uploaded)/1000) + 'k remaining'
163                    );
164                }
165                dlg.uploadProgress.defer(2000,dlg);
166            },
167            failure: function(data) {
168              //  console.log('fail');
169             //   console.log(data);
170            }
171        })
172            
173     },
174     
175     
176     run : function()
177     {
178         // run get Values on the form, so it syncs any secondary forms.
179         this.form.getValues();
180         
181         var o = this.options;
182         var method = this.getMethod();
183         var isPost = method == 'POST';
184         if(o.clientValidation === false || this.form.isValid()){
185             if (this.form.progressUrl && this.form.findField( 'UPLOAD_IDENTIFIER')) {
186                 // use upload progress bar..
187                 this.findField('UPLOAD_IDENTIFIER').setValue(
188                     (new Date() * 1) + '' + Math.random());
189                     
190                     
191             }
192             
193             
194             
195             Roo.Ajax.request(Roo.apply(this.createCallback(), {
196                 form:this.form.el.dom,
197                 url:this.getUrl(!isPost),
198                 method: method,
199                 params:isPost ? this.getParams() : null,
200                 isUpload: this.form.fileUpload
201             }));
202
203         }else if (o.clientValidation !== false){ // client validation failed
204             this.failureType = Roo.form.Action.CLIENT_INVALID;
205             this.form.afterAction(this, false);
206         }
207     },
208
209     success : function(response){
210         var result = this.processResponse(response);
211         if(result === true || result.success){
212             this.form.afterAction(this, true);
213             return;
214         }
215         if(result.errors){
216             this.form.markInvalid(result.errors);
217             this.failureType = Roo.form.Action.SERVER_INVALID;
218         }
219         this.form.afterAction(this, false);
220     },
221
222     handleResponse : function(response){
223         if(this.form.errorReader){
224             var rs = this.form.errorReader.read(response);
225             var errors = [];
226             if(rs.records){
227                 for(var i = 0, len = rs.records.length; i < len; i++) {
228                     var r = rs.records[i];
229                     errors[i] = r.data;
230                 }
231             }
232             if(errors.length < 1){
233                 errors = null;
234             }
235             return {
236                 success : rs.success,
237                 errors : errors
238             };
239         }
240         var ret = false;
241         try {
242             ret = Roo.decode(response.responseText);
243         } catch (e) {
244             ret = {
245                 success: false,
246                 errorMsg: "Failed to read server message: " + (response ? response.responseText : ' - no message'),
247                 errors : []
248             };
249         }
250         return ret;
251         
252     }
253 });
254
255
256 Roo.form.Action.Load = function(form, options){
257     Roo.form.Action.Load.superclass.constructor.call(this, form, options);
258     this.reader = this.form.reader;
259 };
260
261 Roo.extend(Roo.form.Action.Load, Roo.form.Action, {
262     type : 'load',
263
264     run : function(){
265         Roo.Ajax.request(Roo.apply(
266                 this.createCallback(), {
267                     method:this.getMethod(),
268                     url:this.getUrl(false),
269                     params:this.getParams()
270         }));
271     },
272
273     success : function(response){
274         var result = this.processResponse(response);
275         if(result === true || !result.success || !result.data){
276             this.failureType = Roo.form.Action.LOAD_FAILURE;
277             this.form.afterAction(this, false);
278             return;
279         }
280         this.form.clearInvalid();
281         this.form.setValues(result.data);
282         this.form.afterAction(this, true);
283     },
284
285     handleResponse : function(response){
286         if(this.form.reader){
287             var rs = this.form.reader.read(response);
288             var data = rs.records && rs.records[0] ? rs.records[0].data : null;
289             return {
290                 success : rs.success,
291                 data : data
292             };
293         }
294         return Roo.decode(response.responseText);
295     }
296 });
297
298 Roo.form.Action.ACTION_TYPES = {
299     'load' : Roo.form.Action.Load,
300     'submit' : Roo.form.Action.Submit
301 };