functions, procedures and events are missing from the export
[phpmyadmin/dkf.git] / js / tbl_change.js
blobf9c2d432cf00c0583e14e47deb5475f04b1fcea1
1 /* vim: set expandtab sw=4 ts=4 sts=4: */
2 /**
3  * @fileoverview    function used in table data manipulation pages
4  *
5  * @requires    jQuery
6  * @requires    jQueryUI
7  * @requires    js/functions.js
8  *
9  */
11 /**
12  * Modify from controls when the "NULL" checkbox is selected
13  *
14  * @param   string   the MySQL field type
15  * @param   string   the urlencoded field name - OBSOLETE
16  * @param   string   the md5 hashed field name
17  * @param   string   the multi_edit row sequence number
18  *
19  * @return  boolean  always true
20  */
21 function nullify(theType, urlField, md5Field, multi_edit)
23     var rowForm = document.forms['insertForm'];
25     if (typeof(rowForm.elements['funcs' + multi_edit + '[' + md5Field + ']']) != 'undefined') {
26         rowForm.elements['funcs' + multi_edit + '[' + md5Field + ']'].selectedIndex = -1;
27     }
29     // "SET" field , "ENUM" field with more than 20 characters
30     // or foreign key field (drop-down)
31     if (theType == 1 || theType == 3 || theType == 4) {
32         rowForm.elements['field_' + md5Field + multi_edit + '[]'].selectedIndex = -1;
33     }
34     // Other "ENUM" field
35     else if (theType == 2) {
36         var elts     = rowForm.elements['field_' + md5Field + multi_edit + '[]'];
37         // when there is just one option in ENUM:
38         if (elts.checked) {
39             elts.checked = false;
40         } else {
41             var elts_cnt = elts.length;
42             for (var i = 0; i < elts_cnt; i++ ) {
43                 elts[i].checked = false;
44             } // end for
46         } // end if
47     }
48     // foreign key field (with browsing icon for foreign values)
49     else if (theType == 6) {
50         rowForm.elements['field_' + md5Field + multi_edit + '[]'].value = '';
51     }
52     // Other field types
53     else /*if (theType == 5)*/ {
54         rowForm.elements['fields' + multi_edit + '[' + md5Field + ']'].value = '';
55     } // end if... else if... else
57     return true;
58 } // end of the 'nullify()' function
61 /**
62  * javascript DateTime format validation.
63  * its used to prevent adding default (0000-00-00 00:00:00) to database when user enter wrong values
64  * Start of validation part
65  */
66 //function checks the number of days in febuary
67 function daysInFebruary (year){
68     return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
70 //function to convert single digit to double digit
71 function fractionReplace(num)
73     num=parseInt(num);
74     var res="00";
75     switch(num)
76     {
77         case 1:res= "01";break;
78         case 2:res= "02";break;
79         case 3:res= "03";break;
80         case 4:res= "04";break;
81         case 5:res= "05";break;
82         case 6:res= "06";break;
83         case 7:res= "07";break;
84         case 8:res= "08";break;
85         case 9:res= "09";break;
86         }
87     return res;
90 /* function to check the validity of date
91 * The following patterns are accepted in this validation (accepted in mysql as well)
92 * 1) 2001-12-23
93 * 2) 2001-1-2
94 * 3) 02-12-23
95 * 4) And instead of using '-' the following punctuations can be used (+,.,*,^,@,/) All these are accepted by mysql as well. Therefore no issues
97 function isDate(val,tmstmp)
99     val=val.replace(/[.|*|^|+|//|@]/g,'-');
100     var arrayVal=val.split("-");
101     for(var a=0;a<arrayVal.length;a++)
102     {
103         if(arrayVal[a].length==1)
104             arrayVal[a]=fractionReplace(arrayVal[a]);
105     }
106     val=arrayVal.join("-");
107     var pos=2;
108             dtexp=new RegExp(/^([0-9]{4})-(((01|03|05|07|08|10|12)-((0[0-9])|([1-2][0-9])|(3[0-1])))|((02|04|06|09|11)-((0[0-9])|([1-2][0-9])|30)))$/);
109         if(val.length==8)
110         {
111             dtexp=new RegExp(/^([0-9]{2})-(((01|03|05|07|08|10|12)-((0[0-9])|([1-2][0-9])|(3[0-1])))|((02|04|06|09|11)-((0[0-9])|([1-2][0-9])|30)))$/);
112             pos=0;
113         }
114         if(dtexp.test(val))
115         {
116             var month=parseInt(val.substring(pos+3,pos+5));
117             var day=parseInt(val.substring(pos+6,pos+8));
118             var year=parseInt(val.substring(0,pos+2));
119             if(month==2&&day>daysInFebruary(year))
120                 return false;
121             if(val.substring(0,pos+2).length==2)
122             {
123                 if(val.substring(0,pos+2).length==2)
124                     year=parseInt("20"+val.substring(0,pos+2));
125                 else
126                     year=parseInt("19"+val.substring(0,pos+2));
127             }
128             if(tmstmp==true)
129             {
130                 if(year<1978) return false;
131                 if(year>2038||(year>2037&&day>19&&month>=1)||(year>2037&&month>1)) return false;
132                 }
133         }
134         else
135             return false;
136         return true;
139 /* function to check the validity of time
140 * The following patterns are accepted in this validation (accepted in mysql as well)
141 * 1) 2:3:4
142 * 2) 2:23:43
144 function isTime(val)
146     var arrayVal=val.split(":");
147     for(var a=0;a<arrayVal.length;a++)
148     {
149         if(arrayVal[a].length==1)
150             arrayVal[a]=fractionReplace(arrayVal[a]);
151     }
152     val=arrayVal.join(":");
153     tmexp=new RegExp(/^(([0-1][0-9])|(2[0-3])):((0[0-9])|([1-5][0-9])):((0[0-9])|([1-5][0-9]))$/);
154         if(!tmexp.test(val))
155             return false;
156         return true;
158 //validate the datetime and integer
159 function Validator(urlField, multi_edit,theType){
160     var rowForm = document.forms['insertForm'];
161     var evt = window.event || arguments.callee.caller.arguments[0];
162     var target = evt.target || evt.srcElement;
163     unNullify(urlField, multi_edit);
165     if(target.name.substring(0,6)=="fields")
166     {
167         var dt=rowForm.elements['fields[multi_edit][' + multi_edit + '][' + urlField + ']'];
168         // validate for date time
169         if(theType=="datetime"||theType=="time"||theType=="date"||theType=="timestamp")
170         {
171             if(theType=="date"){
172                 if(!isDate(dt.value))
173                     {
174                         dt.className="invalid_value";
175                         return false;
176                     }
177             }
178             else if(theType=="time")
179             {
180                 if(!isTime(dt.value))
181                 {
182                     dt.className="invalid_value";
183                     return false;
184                 }
185             }
186             else if(theType=="datetime"||theType=="timestamp")
187             {
188                 tmstmp=false;
189                 if(dt.value=="CURRENT_TIMESTAMP")
190                 {
191                     dt.className="";
192                     return true;
193                 }
194                 if(theType=="timestamp")
195                 {
196                     tmstmp=true;
197                 }
198                 if(dt.value=="0000-00-00 00:00:00")
199                     return true;
200                 var dv=dt.value.indexOf(" ");
201                 if(dv==-1)
202                 {
203                     dt.className="invalid_value";
204                     return false;
205                 }
206                 else
207                 {
208                     if(!(isDate(dt.value.substring(0,dv),tmstmp)&&isTime(dt.value.substring(dv+1))))
209                     {
210                         dt.className="invalid_value";
211                         return false;
212                     }
213                 }
214             }
215         }
216         //validate for integer type
217         if(theType.substring(0,3)=="int"){
219             if(isNaN(dt.value)){
220                     dt.className="invalid_value";
221                     return false;
222             }
223         }
224     }
226  /* End of datetime validation*/
229  * Unchecks the "NULL" control when a function has been selected or a value
230  * entered
232  * @param   string   the urlencoded field name
233  * @param   string   the multi_edit row sequence number
235  * @return  boolean  always true
236  */
237 function unNullify(urlField, multi_edit)
239     var rowForm = document.forms['insertForm'];
241     if (typeof(rowForm.elements['fields_null[multi_edit][' + multi_edit + '][' + urlField + ']']) != 'undefined') {
242         rowForm.elements['fields_null[multi_edit][' + multi_edit + '][' + urlField + ']'].checked = false
243     } // end if
245     if (typeof(rowForm.elements['insert_ignore_' + multi_edit]) != 'undefined') {
246         rowForm.elements['insert_ignore_' + multi_edit].checked = false
247     } // end if
249     return true;
250 } // end of the 'unNullify()' function
253  * Ajax handlers for Change Table page
255  * Actions Ajaxified here:
256  * Submit Data to be inserted into the table
257  * Restart insertion with 'N' rows.
258  */
259 $(document).ready(function() {
261     /**
262      * Handles all current checkboxes for Null 
263      * 
264      */
265     $('.checkbox_null').bind('click', function(e) {
266             nullify(
267                 // use hidden fields populated by tbl_change.php
268                 $(this).siblings('.nullify_code').val(),
269                 $(this).closest('tr').find('input:hidden').first().val(), 
270                 $(this).siblings('.hashed_field').val(),
271                 $(this).siblings('.multi_edit').val()
272             );
273     });
275     /**
276      * Submission of data to be inserted into table
277      * 
278      * @uses    PMA_ajaxShowMessage()
279      */
280     $("#insertForm").live('submit', function(event) {
282         /**
283          * @var the_form    Object referring to the insertion form
284          */
285         var the_form = $(this);
286         event.preventDefault();
288         PMA_ajaxShowMessage();
289         $(the_form).append('<input type="hidden" name="ajax_request" value="true" />');
291         $.post($(the_form).attr('action'), $(the_form).serialize(), function(data) {
292             if(data.success == true) {
293                 PMA_ajaxShowMessage(data.message);
295                 $("#topmenucontainer")
296                 .next('div')
297                 .remove()
298                 .end()
299                 .after(data.sql_query);
301                 //Remove the empty notice div generated due to a NULL query passed to PMA_showMessage()
302                 var notice_class = $("#topmenucontainer").next("div").find('.notice');
303                 if($(notice_class).text() == '') {
304                     $(notice_class).remove();
305                 }
307                 //Clear the data in the forms
308                 $(the_form).find('input:reset').trigger('click');
309             }
310             else {
311                 PMA_ajaxShowMessage(PMA_messages['strErrorProcessingRequest'] + " : "+data.error, "7000");
312             }
313         })
314     }) // end submission of data to be inserted into table
316     /**
317      * Continue Insertion form
318      */
319     $("#insert_rows").live('change', function(event) {
320         event.preventDefault();
322         /**
323          * @var curr_rows   Number of current insert rows already on page
324          */
325         var curr_rows = $(".insertRowTable").length;
326         /**
327          * @var target_rows Number of rows the user wants
328          */
329         var target_rows = $("#insert_rows").val();
331         if(curr_rows < target_rows ) {
332             while( curr_rows < target_rows ) {
334                 /**
335                  * @var last_row    Object referring to the last row
336                  */
337                 var last_row = $("#insertForm").find(".insertRowTable:last");
339                 //Clone the insert tables
340                 $(last_row)
341                 .clone()
342                 .insertBefore("#insertForm > fieldset")
343                 .find('input[name*=multi_edit],select[name*=multi_edit]')
344                 .each(function() {
346                     /**
347                      * Extract the index from the name attribute for all input/select fields and increment it
348                      * name is of format funcs[multi_edit][10][<long random string of alphanum chars>]
349                      */
351                     /**
352                      * @var this_name   String containing name of the input/select elements
353                      */
354                     var this_name = $(this).attr('name');
355                     /** split {@link this_name} at [10], so we have the parts that can be concatenated later */
356                     var name_parts = this_name.split(/\[\d+\]/);
357                     /** extract the [10] from  {@link name_parts} */
358                     var old_row_index_string = this_name.match(/\[\d+\]/)[0];
359                     /** extract 10 - had to split into two steps to accomodate double digits */
360                     var old_row_index = parseInt(old_row_index_string.match(/\d+/)[0]);
362                     /** calculate next index i.e. 11 */
363                     var new_row_index = old_row_index + 1;
364                     /** generate the new name i.e. funcs[multi_edit][11][foobarbaz] */
365                     var new_name = name_parts[0] + '[' + new_row_index + ']' + name_parts[1];
367                     var hashed_field = name_parts[1].match(/\[(.+)\]/)[1];
368                     $(this).attr('name', new_name);
370                     $(this).filter('.textfield')
371                         .attr('value', '')
372                         .unbind('change')
373                         .attr('onchange', null)
374                         .bind('change', function(e) {
375                             Validator(
376                                 hashed_field, 
377                                 new_row_index, 
378                                 $(this).closest('tr').find('span.column_type').html()
379                                 );
380                         })
381                         .end();
383                     $(this).filter('.checkbox_null')
384                         .bind('click', function(e) {
385                                 nullify(
386                                     $(this).siblings('.nullify_code').val(),
387                                     $(this).closest('tr').find('input:hidden').first().val(), 
388                                     hashed_field, 
389                                     '[multi_edit][' + new_row_index + ']'
390                                     );
391                         }) 
392                         .end();
394                 });
396                 //Insert/Clone the ignore checkboxes
397                 if(curr_rows == 1 ) {
398                     $('<input id="insert_ignore_1" type="checkbox" name="insert_ignore_1" checked="checked" />')
399                     .insertBefore(".insertRowTable:last")
400                     .after('<label for="insert_ignore_1">' + PMA_messages['strIgnore'] + '</label>');
401                 }
402                 else {
404                     /**
405                      * @var last_checkbox   Object reference to the last checkbox in #insertForm
406                      */
407                     var last_checkbox = $("#insertForm").children('input:checkbox:last');
409                     /** name of {@link last_checkbox} */
410                     var last_checkbox_name = $(last_checkbox).attr('name');
411                     /** index of {@link last_checkbox} */
412                     var last_checkbox_index = parseInt(last_checkbox_name.match(/\d+/));
413                     /** name of new {@link last_checkbox} */
414                     var new_name = last_checkbox_name.replace(/\d+/,last_checkbox_index+1);
416                     $(last_checkbox)
417                     .clone()
418                     .attr({'id':new_name, 'name': new_name, 'checked': true})
419                     .add('label[for^=insert_ignore]:last')
420                     .clone()
421                     .attr('for', new_name)
422                     .before('<br />')
423                     .insertBefore(".insertRowTable:last");
424                 }
425                 curr_rows++;
426             }
427         // recompute tabindex for text fields and other controls at footer;
428         // IMO it's not really important to handle the tabindex for
429         // function and Null
430         var tabindex = 0;
431         $('.textfield') 
432         .each(function() {
433                 tabindex++;
434                 $(this).attr('tabindex', tabindex);
435             });
436         $('.control_at_footer')
437         .each(function() {
438                 tabindex++;
439                 $(this).attr('tabindex', tabindex);
440             });
441         }
442         else if( curr_rows > target_rows) {
443             while(curr_rows > target_rows) {
444                 $("input[id^=insert_ignore]:last")
445                 .nextUntil("fieldset")
446                 .andSelf()
447                 .remove();
448                 curr_rows--;
449             }
450         }
451     })
452 }, 'top.frame_content'); //end $(document).ready()