Translated using Weblate.
[phpmyadmin.git] / js / tbl_change.js
blobeaefe58801e9f72bc8e0e0efdcb0d4296c0bc0d2
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 form controls when the "NULL" checkbox is checked
13  *
14  * @param   theType     string   the MySQL field type
15  * @param   urlField    string   the urlencoded field name - OBSOLETE
16  * @param   md5Field    string   the md5 hashed field name
17  * @param   multi_edit  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     // "ENUM" field with more than 20 characters
30     if (theType == 1) {
31         rowForm.elements['fields' + multi_edit + '[' + md5Field +  ']'][1].selectedIndex = -1;
32     }
33     // Other "ENUM" field
34     else if (theType == 2) {
35         var elts     = rowForm.elements['fields' + multi_edit + '[' + md5Field + ']'];
36         // when there is just one option in ENUM:
37         if (elts.checked) {
38             elts.checked = false;
39         } else {
40             var elts_cnt = elts.length;
41             for (var i = 0; i < elts_cnt; i++ ) {
42                 elts[i].checked = false;
43             } // end for
45         } // end if
46     }
47     // "SET" field
48     else if (theType == 3) {
49         rowForm.elements['fields' + multi_edit + '[' + md5Field +  '][]'].selectedIndex = -1;
50     }
51     // Foreign key field (drop-down)
52     else if (theType == 4) {
53         rowForm.elements['fields' + multi_edit + '[' + md5Field +  ']'].selectedIndex = -1;
54     }
55     // foreign key field (with browsing icon for foreign values)
56     else if (theType == 6) {
57         rowForm.elements['fields' + multi_edit + '[' + md5Field + ']'].value = '';
58     }
59     // Other field types
60     else /*if (theType == 5)*/ {
61         rowForm.elements['fields' + multi_edit + '[' + md5Field + ']'].value = '';
62     } // end if... else if... else
64     return true;
65 } // end of the 'nullify()' function
68 /**
69  * javascript DateTime format validation.
70  * its used to prevent adding default (0000-00-00 00:00:00) to database when user enter wrong values
71  * Start of validation part
72  */
73 //function checks the number of days in febuary
74 function daysInFebruary (year)
76     return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
78 //function to convert single digit to double digit
79 function fractionReplace(num)
81     num = parseInt(num);
82     return num >= 1 && num <= 9 ? '0' + num : '00';
85 /* function to check the validity of date
86 * The following patterns are accepted in this validation (accepted in mysql as well)
87 * 1) 2001-12-23
88 * 2) 2001-1-2
89 * 3) 02-12-23
90 * 4) And instead of using '-' the following punctuations can be used (+,.,*,^,@,/) All these are accepted by mysql as well. Therefore no issues
92 function isDate(val,tmstmp)
94     val=val.replace(/[.|*|^|+|//|@]/g,'-');
95     var arrayVal=val.split("-");
96     for(var a=0;a<arrayVal.length;a++)
97     {
98         if(arrayVal[a].length==1)
99             arrayVal[a]=fractionReplace(arrayVal[a]);
100     }
101     val=arrayVal.join("-");
102     var pos=2;
103             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)))$/);
104         if(val.length==8)
105         {
106             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)))$/);
107             pos=0;
108         }
109         if(dtexp.test(val))
110         {
111             var month=parseInt(val.substring(pos+3,pos+5));
112             var day=parseInt(val.substring(pos+6,pos+8));
113             var year=parseInt(val.substring(0,pos+2));
114             if(month==2&&day>daysInFebruary(year))
115                 return false;
116             if(val.substring(0,pos+2).length==2)
117             {
118                 if(val.substring(0,pos+2).length==2)
119                     year=parseInt("20"+val.substring(0,pos+2));
120                 else
121                     year=parseInt("19"+val.substring(0,pos+2));
122             }
123             if(tmstmp==true)
124             {
125                 if(year<1978) return false;
126                 if(year>2038||(year>2037&&day>19&&month>=1)||(year>2037&&month>1)) return false;
127                 }
128         }
129         else
130             return false;
131         return true;
134 /* function to check the validity of time
135 * The following patterns are accepted in this validation (accepted in mysql as well)
136 * 1) 2:3:4
137 * 2) 2:23:43
139 function isTime(val)
141     var arrayVal=val.split(":");
142     for(var a=0;a<arrayVal.length;a++)
143     {
144         if(arrayVal[a].length==1)
145             arrayVal[a]=fractionReplace(arrayVal[a]);
146     }
147     val=arrayVal.join(":");
148     tmexp=new RegExp(/^(([0-1][0-9])|(2[0-3])):((0[0-9])|([1-5][0-9])):((0[0-9])|([1-5][0-9]))$/);
149         if(!tmexp.test(val))
150             return false;
151         return true;
154 function verificationsAfterFieldChange(urlField, multi_edit, theType)
156     var evt = window.event || arguments.callee.caller.arguments[0];
157     var target = evt.target || evt.srcElement;
159     // Unchecks the corresponding "NULL" control
160     $("input[name='fields_null[multi_edit][" + multi_edit + "][" + urlField + "]']").attr({'checked': false});
162     // Unchecks the Ignore checkbox for the current row
163     $("input[name='insert_ignore_" + multi_edit + "']").attr({'checked': false});
164     var $this_input = $("input[name='fields[multi_edit][" + multi_edit + "][" + urlField + "]']");
166     // Does this field come from datepicker?
167     if ($this_input.data('comes_from') == 'datepicker') {
168         // Yes, so do not validate because the final value is not yet in
169         // the field and hopefully the datepicker returns a valid date+time
170         $this_input.data('comes_from', '');
171         return true;
172     }
174     if(target.name.substring(0,6)=="fields") {
175         // validate for date time
176         if(theType=="datetime"||theType=="time"||theType=="date"||theType=="timestamp") {
177             $this_input.removeClass("invalid_value");
178             var dt_value = $this_input.val();
179             if(theType=="date"){
180                 if (! isDate(dt_value)) {
181                     $this_input.addClass("invalid_value");
182                     return false;
183                 }
184             } else if(theType=="time") {
185                 if (! isTime(dt_value)) {
186                     $this_input.addClass("invalid_value");
187                     return false;
188                 }
189             } else if(theType=="datetime"||theType=="timestamp") {
190                 tmstmp=false;
191                 if(dt_value == "CURRENT_TIMESTAMP") {
192                     return true;
193                 }
194                 if(theType=="timestamp") {
195                     tmstmp=true;
196                 }
197                 if(dt_value=="0000-00-00 00:00:00") {
198                     return true;
199                 }
200                 var dv=dt_value.indexOf(" ");
201                 if(dv==-1) {
202                     $this_input.addClass("invalid_value");
203                     return false;
204                 } else {
205                     if (! (isDate(dt_value.substring(0,dv),tmstmp) && isTime(dt_value.substring(dv+1)))) {
206                         $this_input.addClass("invalid_value");
207                         return false;
208                     }
209                 }
210             }
211         }
212         //validate for integer type
213         if(theType.substring(0,3) == "int"){
214             $this_input.removeClass("invalid_value");
215             if(isNaN($this_input.val())){
216                 $this_input.addClass("invalid_value");
217                 return false;
218             }
219         }
220     }
222  /* End of datetime validation*/
225  * Ajax handlers for Change Table page
227  * Actions Ajaxified here:
228  * Submit Data to be inserted into the table.
229  * Restart insertion with 'N' rows.
230  */
231 $(document).ready(function() {
233     $('.open_gis_editor').live('click', function(event) {
234         event.preventDefault();
236         var $span = $(this);
237         // Current value
238         var value = $span.parent('td').children("input[type='text']").val();
239         // Field name
240         var field = $span.parents('tr').children('td:first').find("input[type='hidden']").val();
241         // Column type
242         var type = $span.parents('tr').find('span.column_type').text();
243         // Names of input field and null checkbox
244         var input_name = $span.parent('td').children("input[type='text']").attr('name');
245         //Token
246         var token = $("input[name='token']").val();
248         openGISEditor();
249         if (!gisEditorLoaded) {
250             loadJSAndGISEditor(value, field, type, input_name, token);
251         } else {
252             loadGISEditor(value, field, type, input_name, token);
253         }
254     });
256     /**
257      * Uncheck the null checkbox as geometry data is placed on the input field
258      */
259     $("input[name='gis_data[save]']").live('click', function(event) {
260         var input_name = $('form#gis_data_editor_form').find("input[name='input_name']").val();   
261         var $null_checkbox = $("input[name='" + input_name + "']").parents('tr').find('.checkbox_null');
262         $null_checkbox.attr('checked', false);
263     });
265     // these were hidden via the "hide" class
266     $('.foreign_values_anchor').show();
268     /**
269      * Handles all current checkboxes for Null; this only takes care of the
270      * checkboxes on currently displayed rows as the rows generated by
271      * "Continue insertion" are handled in the "Continue insertion" code
272      *
273      */
274     $('.checkbox_null').bind('click', function(e) {
275             nullify(
276                 // use hidden fields populated by tbl_change.php
277                 $(this).siblings('.nullify_code').val(),
278                 $(this).closest('tr').find('input:hidden').first().val(),
279                 $(this).siblings('.hashed_field').val(),
280                 $(this).siblings('.multi_edit').val()
281             );
282     });
284     /**
285      * Submission of data to be inserted or updated
286      *
287      * @uses    PMA_ajaxShowMessage()
288      *
289      * This section has been deactivated. Here are the problems that I've
290      * noticed:
291      *
292      * 1. If the form contains a file upload field, the data does not reach
293      *    tbl_replace.php. This is because AJAX does not support file upload.
294      *    As a workaround I tried jquery.form.js version 2.49. The file
295      *    upload worked but afterwards the browser presented a tbl_replace.php
296      *    file and a choice to open or save.
297      *
298      * 2. This code can be called if we are editing or inserting. If editing,
299      *    the "and then" action can be "go back to this page" or "edit next
300      *    row", in which cases it makes sense to use AJAX. But the "go back
301      *    to previous page" and "insert another new row" actions, using AJAX
302      *    has no obvious advantage. If inserting, the "go back to previous"
303      *    action needs a page refresh anyway.
304      */
305     $("#insertFormDEACTIVATED").live('submit', function(event) {
307         /**
308          * @var the_form    Object referring to the insertion form
309          */
310         var $form = $(this);
311         event.preventDefault();
313         PMA_ajaxShowMessage();
314         PMA_prepareForAjaxRequest($form);
316         $.post($form.attr('action'), $form.serialize(), function(data) {
317             if (typeof data.success != 'undefined') {
318                 if(data.success == true) {
319                     PMA_ajaxShowMessage(data.message);
321                     $("#floating_menubar")
322                     .next('div')
323                     .remove()
324                     .end()
325                     .after(data.sql_query);
327                     //Remove the empty notice div generated due to a NULL query passed to PMA_showMessage()
328                     var $notice_class = $("#floating_menubar").next("div").find('.notice');
329                     if ($notice_class.text() == '') {
330                         $notice_class.remove();
331                     }
333                     var submit_type = $form.find("select[name='submit_type']").val();
334                     if ('insert' == submit_type || 'insertignore' == submit_type) {
335                         //Clear the data in the forms
336                         $form.find('input:reset').trigger('click');
337                     }
338                 } else {
339                     PMA_ajaxShowMessage(PMA_messages['strErrorProcessingRequest'] + " : " + data.error, false);
340                 }
341             } else {
342                 //happens for example when no change was done while editing
343                 $('#insertForm').remove();
344                 $('#floating_menubar').after('<div id="sqlqueryresults"></div>');
345                 $('#sqlqueryresults').html(data);
346             }
347         })
348     }) // end submission of data to be inserted into table
350     /**
351      * Continue Insertion form
352      */
353     $("#insert_rows").live('change', function(event) {
354         event.preventDefault();
356         /**
357          * @var curr_rows   Number of current insert rows already on page
358          */
359         var curr_rows = $(".insertRowTable").length;
360         /**
361          * @var target_rows Number of rows the user wants
362          */
363         var target_rows = $("#insert_rows").val();
365         // remove all datepickers
366         $('.datefield,.datetimefield').each(function(){
367             $(this).datepicker('destroy');
368         });
370         if(curr_rows < target_rows ) {
371             while( curr_rows < target_rows ) {
373                 /**
374                  * @var $last_row    Object referring to the last row
375                  */
376                 var $last_row = $("#insertForm").find(".insertRowTable:last");
378                 // need to access this at more than one level
379                 // (also needs improvement because it should be calculated
380                 //  just once per cloned row, not once per column)
381                 var new_row_index = 0;
383                 //Clone the insert tables
384                 $last_row
385                 .clone()
386                 .insertBefore("#actions_panel")
387                 .find('input[name*=multi_edit],select[name*=multi_edit],textarea[name*=multi_edit]')
388                 .each(function() {
390                     var $this_element = $(this);
391                     /**
392                      * Extract the index from the name attribute for all input/select fields and increment it
393                      * name is of format funcs[multi_edit][10][<long random string of alphanum chars>]
394                      */
396                     /**
397                      * @var this_name   String containing name of the input/select elements
398                      */
399                     var this_name = $this_element.attr('name');
400                     /** split {@link this_name} at [10], so we have the parts that can be concatenated later */
401                     var name_parts = this_name.split(/\[\d+\]/);
402                     /** extract the [10] from  {@link name_parts} */
403                     var old_row_index_string = this_name.match(/\[\d+\]/)[0];
404                     /** extract 10 - had to split into two steps to accomodate double digits */
405                     var old_row_index = parseInt(old_row_index_string.match(/\d+/)[0]);
407                     /** calculate next index i.e. 11 */
408                     new_row_index = old_row_index + 1;
409                     /** generate the new name i.e. funcs[multi_edit][11][foobarbaz] */
410                     var new_name = name_parts[0] + '[' + new_row_index + ']' + name_parts[1];
412                     var hashed_field = name_parts[1].match(/\[(.+)\]/)[1];
413                     $this_element.attr('name', new_name);
415                     if ($this_element.is('.textfield')) {
416                         // do not remove the 'value' attribute for ENUM columns
417                         if ($this_element.closest('tr').find('span.column_type').html() != 'enum') {
418                             $this_element.attr('value', $this_element.closest('tr').find('span.default_value').html());
419                         }
420                         $this_element
421                         .unbind('change')
422                         // Remove onchange attribute that was placed
423                         // by tbl_change.php; it refers to the wrong row index
424                         .attr('onchange', null)
425                         // Keep these values to be used when the element
426                         // will change
427                         .data('hashed_field', hashed_field)
428                         .data('new_row_index', new_row_index)
429                         .bind('change', function(e) {
430                             var $changed_element = $(this);
431                             verificationsAfterFieldChange(
432                                 $changed_element.data('hashed_field'),
433                                 $changed_element.data('new_row_index'),
434                                 $changed_element.closest('tr').find('span.column_type').html()
435                                 );
436                         });
437                     }
439                     if ($this_element.is('.checkbox_null')) {
440                         $this_element
441                         // this event was bound earlier by jQuery but
442                         // to the original row, not the cloned one, so unbind()
443                         .unbind('click')
444                         // Keep these values to be used when the element
445                         // will be clicked
446                         .data('hashed_field', hashed_field)
447                         .data('new_row_index', new_row_index)
448                         .bind('click', function(e) {
449                                 var $changed_element = $(this);
450                                 nullify(
451                                     $changed_element.siblings('.nullify_code').val(),
452                                     $this_element.closest('tr').find('input:hidden').first().val(),
453                                     $changed_element.data('hashed_field'),
454                                     '[multi_edit][' + $changed_element.data('new_row_index') + ']'
455                                     );
456                         });
457                     }
458                 }) // end each
459                 .end()
460                 .find('.foreign_values_anchor')
461                 .each(function() {
462                         $anchor = $(this);
463                         var new_value = 'rownumber=' + new_row_index;
464                         // needs improvement in case something else inside
465                         // the href contains this pattern
466                         var new_href = $anchor.attr('href').replace(/rownumber=\d+/, new_value);
467                         $anchor.attr('href', new_href );
468                     });
470                 //Insert/Clone the ignore checkboxes
471                 if(curr_rows == 1 ) {
472                     $('<input id="insert_ignore_1" type="checkbox" name="insert_ignore_1" checked="checked" />')
473                     .insertBefore(".insertRowTable:last")
474                     .after('<label for="insert_ignore_1">' + PMA_messages['strIgnore'] + '</label>');
475                 }
476                 else {
478                     /**
479                      * @var last_checkbox   Object reference to the last checkbox in #insertForm
480                      */
481                     var last_checkbox = $("#insertForm").children('input:checkbox:last');
483                     /** name of {@link last_checkbox} */
484                     var last_checkbox_name = $(last_checkbox).attr('name');
485                     /** index of {@link last_checkbox} */
486                     var last_checkbox_index = parseInt(last_checkbox_name.match(/\d+/));
487                     /** name of new {@link last_checkbox} */
488                     var new_name = last_checkbox_name.replace(/\d+/,last_checkbox_index+1);
490                     $(last_checkbox)
491                     .clone()
492                     .attr({'id':new_name, 'name': new_name, 'checked': true})
493                     .add('label[for^=insert_ignore]:last')
494                     .clone()
495                     .attr('for', new_name)
496                     .before('<br />')
497                     .insertBefore(".insertRowTable:last");
498                 }
499                 curr_rows++;
500             }
501         // recompute tabindex for text fields and other controls at footer;
502         // IMO it's not really important to handle the tabindex for
503         // function and Null
504         var tabindex = 0;
505         $('.textfield')
506         .each(function() {
507                 tabindex++;
508                 $(this).attr('tabindex', tabindex);
509                 // update the IDs of textfields to ensure that they are unique
510                 $(this).attr('id', "field_" + tabindex + "_3");
511             });
512         $('.control_at_footer')
513         .each(function() {
514                 tabindex++;
515                 $(this).attr('tabindex', tabindex);
516             });
517         // Add all the required datepickers back
518         $('.datefield,.datetimefield').each(function(){
519             PMA_addDatepicker($(this));
520             });
521         }
522         else if( curr_rows > target_rows) {
523             while(curr_rows > target_rows) {
524                 $("input[id^=insert_ignore]:last")
525                 .nextUntil("fieldset")
526                 .andSelf()
527                 .remove();
528                 curr_rows--;
529             }
530         }
531     })
532 }, 'top.frame_content'); //end $(document).ready()