Translated using Weblate.
[phpmyadmin.git] / js / tbl_change.js
blobcaa71f06fa8ef4ecb437b6c5e8d546f8a83a71b4
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     });
285     /**
286      * Reset the auto_increment column to 0 when selecting any of the
287      * insert options in submit_type-dropdown. Only perform the reset 
288      * when we are in edit-mode, and not in insert-mode(no previous value
289      * available).
290      */
291     $('select[name="submit_type"]').bind('change', function (e) {
292         var auto_increment_column = $('.insertRowTable').find('input[name^="auto_increment"]').attr('name');
293         var prev_value_field = $('.insertRowTable').find('input[name="' + auto_increment_column.replace('auto_increment', 'fields_prev') + '"]');
294         var value_field = $('.insertRowTable').find('input[name="' + auto_increment_column.replace('auto_increment', 'fields') + '"]');
296         if (auto_increment_column) {
297             var previous_value = $(prev_value_field).val();
298             if (previous_value !== undefined) {
299                 if ($(this).val() == 'insert' || $(this).val() == 'insertignore' || $(this).val() == 'showinsert' ) {
300                     $(value_field).val(0);
301                 } else {
302                     $(value_field).val(previous_value);
303                 }
304             }
305         }
307     });
310     /**
311      * Submission of data to be inserted or updated
312      *
313      * @uses    PMA_ajaxShowMessage()
314      *
315      * This section has been deactivated. Here are the problems that I've
316      * noticed:
317      *
318      * 1. If the form contains a file upload field, the data does not reach
319      *    tbl_replace.php. This is because AJAX does not support file upload.
320      *    As a workaround I tried jquery.form.js version 2.49. The file
321      *    upload worked but afterwards the browser presented a tbl_replace.php
322      *    file and a choice to open or save.
323      *
324      * 2. This code can be called if we are editing or inserting. If editing,
325      *    the "and then" action can be "go back to this page" or "edit next
326      *    row", in which cases it makes sense to use AJAX. But the "go back
327      *    to previous page" and "insert another new row" actions, using AJAX
328      *    has no obvious advantage. If inserting, the "go back to previous"
329      *    action needs a page refresh anyway.
330      */
331     $("#insertFormDEACTIVATED").live('submit', function(event) {
333         /**
334          * @var the_form    Object referring to the insertion form
335          */
336         var $form = $(this);
337         event.preventDefault();
339         PMA_ajaxShowMessage();
340         PMA_prepareForAjaxRequest($form);
342         $.post($form.attr('action'), $form.serialize(), function(data) {
343             if (typeof data.success != 'undefined') {
344                 if(data.success == true) {
345                     PMA_ajaxShowMessage(data.message);
347                     $("#floating_menubar")
348                     .next('div')
349                     .remove()
350                     .end()
351                     .after(data.sql_query);
353                     //Remove the empty notice div generated due to a NULL query passed to PMA_showMessage()
354                     var $notice_class = $("#floating_menubar").next("div").find('.notice');
355                     if ($notice_class.text() == '') {
356                         $notice_class.remove();
357                     }
359                     var submit_type = $form.find("select[name='submit_type']").val();
360                     if ('insert' == submit_type || 'insertignore' == submit_type) {
361                         //Clear the data in the forms
362                         $form.find('input:reset').trigger('click');
363                     }
364                 } else {
365                     PMA_ajaxShowMessage(PMA_messages['strErrorProcessingRequest'] + " : " + data.error, false);
366                 }
367             } else {
368                 //happens for example when no change was done while editing
369                 $('#insertForm').remove();
370                 $('#floating_menubar').after('<div id="sqlqueryresults"></div>');
371                 $('#sqlqueryresults').html(data);
372             }
373         })
374     }) // end submission of data to be inserted into table
376     /**
377      * Continue Insertion form
378      */
379     $("#insert_rows").live('change', function(event) {
380         event.preventDefault();
382         /**
383          * @var curr_rows   Number of current insert rows already on page
384          */
385         var curr_rows = $(".insertRowTable").length;
386         /**
387          * @var target_rows Number of rows the user wants
388          */
389         var target_rows = $("#insert_rows").val();
391         // remove all datepickers
392         $('.datefield,.datetimefield').each(function(){
393             $(this).datepicker('destroy');
394         });
396         if(curr_rows < target_rows ) {
397             while( curr_rows < target_rows ) {
399                 /**
400                  * @var $last_row    Object referring to the last row
401                  */
402                 var $last_row = $("#insertForm").find(".insertRowTable:last");
404                 // need to access this at more than one level
405                 // (also needs improvement because it should be calculated
406                 //  just once per cloned row, not once per column)
407                 var new_row_index = 0;
409                 //Clone the insert tables
410                 $last_row
411                 .clone()
412                 .insertBefore("#actions_panel")
413                 .find('input[name*=multi_edit],select[name*=multi_edit],textarea[name*=multi_edit]')
414                 .each(function() {
416                     var $this_element = $(this);
417                     /**
418                      * Extract the index from the name attribute for all input/select fields and increment it
419                      * name is of format funcs[multi_edit][10][<long random string of alphanum chars>]
420                      */
422                     /**
423                      * @var this_name   String containing name of the input/select elements
424                      */
425                     var this_name = $this_element.attr('name');
426                     /** split {@link this_name} at [10], so we have the parts that can be concatenated later */
427                     var name_parts = this_name.split(/\[\d+\]/);
428                     /** extract the [10] from  {@link name_parts} */
429                     var old_row_index_string = this_name.match(/\[\d+\]/)[0];
430                     /** extract 10 - had to split into two steps to accomodate double digits */
431                     var old_row_index = parseInt(old_row_index_string.match(/\d+/)[0]);
433                     /** calculate next index i.e. 11 */
434                     new_row_index = old_row_index + 1;
435                     /** generate the new name i.e. funcs[multi_edit][11][foobarbaz] */
436                     var new_name = name_parts[0] + '[' + new_row_index + ']' + name_parts[1];
438                     var hashed_field = name_parts[1].match(/\[(.+)\]/)[1];
439                     $this_element.attr('name', new_name);
441                     if ($this_element.is('.textfield')) {
442                         // do not remove the 'value' attribute for ENUM columns
443                         if ($this_element.closest('tr').find('span.column_type').html() != 'enum') {
444                             $this_element.attr('value', $this_element.closest('tr').find('span.default_value').html());
445                         }
446                         $this_element
447                         .unbind('change')
448                         // Remove onchange attribute that was placed
449                         // by tbl_change.php; it refers to the wrong row index
450                         .attr('onchange', null)
451                         // Keep these values to be used when the element
452                         // will change
453                         .data('hashed_field', hashed_field)
454                         .data('new_row_index', new_row_index)
455                         .bind('change', function(e) {
456                             var $changed_element = $(this);
457                             verificationsAfterFieldChange(
458                                 $changed_element.data('hashed_field'),
459                                 $changed_element.data('new_row_index'),
460                                 $changed_element.closest('tr').find('span.column_type').html()
461                                 );
462                         });
463                     }
465                     if ($this_element.is('.checkbox_null')) {
466                         $this_element
467                         // this event was bound earlier by jQuery but
468                         // to the original row, not the cloned one, so unbind()
469                         .unbind('click')
470                         // Keep these values to be used when the element
471                         // will be clicked
472                         .data('hashed_field', hashed_field)
473                         .data('new_row_index', new_row_index)
474                         .bind('click', function(e) {
475                                 var $changed_element = $(this);
476                                 nullify(
477                                     $changed_element.siblings('.nullify_code').val(),
478                                     $this_element.closest('tr').find('input:hidden').first().val(),
479                                     $changed_element.data('hashed_field'),
480                                     '[multi_edit][' + $changed_element.data('new_row_index') + ']'
481                                     );
482                         });
483                     }
484                 }) // end each
485                 .end()
486                 .find('.foreign_values_anchor')
487                 .each(function() {
488                         $anchor = $(this);
489                         var new_value = 'rownumber=' + new_row_index;
490                         // needs improvement in case something else inside
491                         // the href contains this pattern
492                         var new_href = $anchor.attr('href').replace(/rownumber=\d+/, new_value);
493                         $anchor.attr('href', new_href );
494                     });
496                 //Insert/Clone the ignore checkboxes
497                 if(curr_rows == 1 ) {
498                     $('<input id="insert_ignore_1" type="checkbox" name="insert_ignore_1" checked="checked" />')
499                     .insertBefore(".insertRowTable:last")
500                     .after('<label for="insert_ignore_1">' + PMA_messages['strIgnore'] + '</label>');
501                 }
502                 else {
504                     /**
505                      * @var last_checkbox   Object reference to the last checkbox in #insertForm
506                      */
507                     var last_checkbox = $("#insertForm").children('input:checkbox:last');
509                     /** name of {@link last_checkbox} */
510                     var last_checkbox_name = $(last_checkbox).attr('name');
511                     /** index of {@link last_checkbox} */
512                     var last_checkbox_index = parseInt(last_checkbox_name.match(/\d+/));
513                     /** name of new {@link last_checkbox} */
514                     var new_name = last_checkbox_name.replace(/\d+/,last_checkbox_index+1);
516                     $(last_checkbox)
517                     .clone()
518                     .attr({'id':new_name, 'name': new_name, 'checked': true})
519                     .add('label[for^=insert_ignore]:last')
520                     .clone()
521                     .attr('for', new_name)
522                     .before('<br />')
523                     .insertBefore(".insertRowTable:last");
524                 }
525                 curr_rows++;
526             }
527         // recompute tabindex for text fields and other controls at footer;
528         // IMO it's not really important to handle the tabindex for
529         // function and Null
530         var tabindex = 0;
531         $('.textfield')
532         .each(function() {
533                 tabindex++;
534                 $(this).attr('tabindex', tabindex);
535                 // update the IDs of textfields to ensure that they are unique
536                 $(this).attr('id', "field_" + tabindex + "_3");
537             });
538         $('.control_at_footer')
539         .each(function() {
540                 tabindex++;
541                 $(this).attr('tabindex', tabindex);
542             });
543         // Add all the required datepickers back
544         $('.datefield,.datetimefield').each(function(){
545             PMA_addDatepicker($(this));
546             });
547         }
548         else if( curr_rows > target_rows) {
549             while(curr_rows > target_rows) {
550                 $("input[id^=insert_ignore]:last")
551                 .nextUntil("fieldset")
552                 .andSelf()
553                 .remove();
554                 curr_rows--;
555             }
556         }
557     })
558 }, 'top.frame_content'); //end $(document).ready()