bug #3398788 [session] No feedback when result is empty (signon auth_type)
[phpmyadmin.git] / js / tbl_change.js
blob234e4e19764b239d5b9c887c009650809e0dc66d
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){
75     return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
77 //function to convert single digit to double digit
78 function fractionReplace(num)
80     num=parseInt(num);
81     var res="00";
82     switch(num)
83     {
84         case 1:res= "01";break;
85         case 2:res= "02";break;
86         case 3:res= "03";break;
87         case 4:res= "04";break;
88         case 5:res= "05";break;
89         case 6:res= "06";break;
90         case 7:res= "07";break;
91         case 8:res= "08";break;
92         case 9:res= "09";break;
93         }
94     return res;
97 /* function to check the validity of date
98 * The following patterns are accepted in this validation (accepted in mysql as well)
99 * 1) 2001-12-23
100 * 2) 2001-1-2
101 * 3) 02-12-23
102 * 4) And instead of using '-' the following punctuations can be used (+,.,*,^,@,/) All these are accepted by mysql as well. Therefore no issues
104 function isDate(val,tmstmp)
106     val=val.replace(/[.|*|^|+|//|@]/g,'-');
107     var arrayVal=val.split("-");
108     for(var a=0;a<arrayVal.length;a++)
109     {
110         if(arrayVal[a].length==1)
111             arrayVal[a]=fractionReplace(arrayVal[a]);
112     }
113     val=arrayVal.join("-");
114     var pos=2;
115             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)))$/);
116         if(val.length==8)
117         {
118             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)))$/);
119             pos=0;
120         }
121         if(dtexp.test(val))
122         {
123             var month=parseInt(val.substring(pos+3,pos+5));
124             var day=parseInt(val.substring(pos+6,pos+8));
125             var year=parseInt(val.substring(0,pos+2));
126             if(month==2&&day>daysInFebruary(year))
127                 return false;
128             if(val.substring(0,pos+2).length==2)
129             {
130                 if(val.substring(0,pos+2).length==2)
131                     year=parseInt("20"+val.substring(0,pos+2));
132                 else
133                     year=parseInt("19"+val.substring(0,pos+2));
134             }
135             if(tmstmp==true)
136             {
137                 if(year<1978) return false;
138                 if(year>2038||(year>2037&&day>19&&month>=1)||(year>2037&&month>1)) return false;
139                 }
140         }
141         else
142             return false;
143         return true;
146 /* function to check the validity of time
147 * The following patterns are accepted in this validation (accepted in mysql as well)
148 * 1) 2:3:4
149 * 2) 2:23:43
151 function isTime(val)
153     var arrayVal=val.split(":");
154     for(var a=0;a<arrayVal.length;a++)
155     {
156         if(arrayVal[a].length==1)
157             arrayVal[a]=fractionReplace(arrayVal[a]);
158     }
159     val=arrayVal.join(":");
160     tmexp=new RegExp(/^(([0-1][0-9])|(2[0-3])):((0[0-9])|([1-5][0-9])):((0[0-9])|([1-5][0-9]))$/);
161         if(!tmexp.test(val))
162             return false;
163         return true;
166 function verificationsAfterFieldChange(urlField, multi_edit, theType){
167     var evt = window.event || arguments.callee.caller.arguments[0];
168     var target = evt.target || evt.srcElement;
170     // Unchecks the corresponding "NULL" control
171     $("input[name='fields_null[multi_edit][" + multi_edit + "][" + urlField + "]']").attr({'checked': false});
173     // Unchecks the Ignore checkbox for the current row
174     $("input[name='insert_ignore_" + multi_edit + "']").attr({'checked': false});
175     var $this_input = $("input[name='fields[multi_edit][" + multi_edit + "][" + urlField + "]']");
177     // Does this field come from datepicker?
178     if ($this_input.data('comes_from') == 'datepicker') {
179         // Yes, so do not validate because the final value is not yet in
180         // the field and hopefully the datepicker returns a valid date+time
181         $this_input.data('comes_from', '');
182         return true;
183     }
185     if(target.name.substring(0,6)=="fields") {
186         // validate for date time
187         if(theType=="datetime"||theType=="time"||theType=="date"||theType=="timestamp") {
188             $this_input.removeClass("invalid_value");
189             var dt_value = $this_input.val();
190             if(theType=="date"){
191                 if (! isDate(dt_value)) {
192                     $this_input.addClass("invalid_value");
193                     return false;
194                 }
195             } else if(theType=="time") {
196                 if (! isTime(dt_value)) {
197                     $this_input.addClass("invalid_value");
198                     return false;
199                 }
200             } else if(theType=="datetime"||theType=="timestamp") {
201                 tmstmp=false;
202                 if(dt_value == "CURRENT_TIMESTAMP") {
203                     return true;
204                 }
205                 if(theType=="timestamp") {
206                     tmstmp=true;
207                 }
208                 if(dt_value=="0000-00-00 00:00:00") {
209                     return true;
210                 }
211                 var dv=dt_value.indexOf(" ");
212                 if(dv==-1) {
213                     $this_input.addClass("invalid_value");
214                     return false;
215                 } else {
216                     if (! (isDate(dt_value.substring(0,dv),tmstmp) && isTime(dt_value.substring(dv+1)))) {
217                         $this_input.addClass("invalid_value");
218                         return false;
219                     }
220                 }
221             }
222         }
223         //validate for integer type
224         if(theType.substring(0,3) == "int"){
225             $this_input.removeClass("invalid_value");
226             if(isNaN($this_input.val())){
227                 $this_input.addClass("invalid_value");
228                 return false;
229             }
230         }
231     }
233  /* End of datetime validation*/
236  * Ajax handlers for Change Table page
238  * Actions Ajaxified here:
239  * Submit Data to be inserted into the table
240  * Restart insertion with 'N' rows.
241  */
242 $(document).ready(function() {
244     // these were hidden via the "hide" class
245     $('.foreign_values_anchor').show();
247     /**
248      * Handles all current checkboxes for Null; this only takes care of the
249      * checkboxes on currently displayed rows as the rows generated by 
250      * "Continue insertion" are handled in the "Continue insertion" code 
251      * 
252      */
253     $('.checkbox_null').bind('click', function(e) {
254             nullify(
255                 // use hidden fields populated by tbl_change.php
256                 $(this).siblings('.nullify_code').val(),
257                 $(this).closest('tr').find('input:hidden').first().val(), 
258                 $(this).siblings('.hashed_field').val(),
259                 $(this).siblings('.multi_edit').val()
260             );
261     });
263     /**
264      * Submission of data to be inserted or updated 
265      * 
266      * @uses    PMA_ajaxShowMessage()
267      *
268      * This section has been deactivated. Here are the problems that I've
269      * noticed:
270      *
271      * 1. If the form contains a file upload field, the data does not reach
272      *    tbl_replace.php. This is because AJAX does not support file upload.
273      *    As a workaround I tried jquery.form.js version 2.49. The file
274      *    upload worked but afterwards the browser presented a tbl_replace.php
275      *    file and a choice to open or save.
276      *
277      * 2. This code can be called if we are editing or inserting. If editing,
278      *    the "and then" action can be "go back to this page" or "edit next
279      *    row", in which cases it makes sense to use AJAX. But the "go back
280      *    to previous page" and "insert another new row" actions, using AJAX 
281      *    has no obvious advantage. If inserting, the "go back to previous"
282      *    action needs a page refresh anyway. 
283      */
284     $("#insertFormDEACTIVATED").live('submit', function(event) {
286         /**
287          * @var the_form    Object referring to the insertion form
288          */
289         var $form = $(this);
290         event.preventDefault();
292         PMA_ajaxShowMessage();
293         PMA_prepareForAjaxRequest($form);
295         $.post($form.attr('action'), $form.serialize(), function(data) {
296             if (typeof data.success != 'undefined') {
297                 if(data.success == true) {
298                     PMA_ajaxShowMessage(data.message);
300                     $("#topmenucontainer")
301                     .next('div')
302                     .remove()
303                     .end()
304                     .after(data.sql_query);
306                     //Remove the empty notice div generated due to a NULL query passed to PMA_showMessage()
307                     var $notice_class = $("#topmenucontainer").next("div").find('.notice');
308                     if ($notice_class.text() == '') {
309                         $notice_class.remove();
310                     }
312                     var submit_type = $form.find("select[name='submit_type']").val();
313                     if ('insert' == submit_type || 'insertignore' == submit_type) {
314                         //Clear the data in the forms
315                         $form.find('input:reset').trigger('click');
316                     }
317                 } else {
318                     PMA_ajaxShowMessage(PMA_messages['strErrorProcessingRequest'] + " : "+data.error, "7000");
319                 }
320             } else {
321                 //happens for example when no change was done while editing
322                 $('#insertForm').remove();
323                 $('#topmenucontainer').after('<div id="sqlqueryresults"></div>');
324                 $('#sqlqueryresults').html(data);
325             }
326         })
327     }) // end submission of data to be inserted into table
329     /**
330      * Continue Insertion form
331      */
332     $("#insert_rows").live('change', function(event) {
333         event.preventDefault();
335         /**
336          * @var curr_rows   Number of current insert rows already on page
337          */
338         var curr_rows = $(".insertRowTable").length;
339         /**
340          * @var target_rows Number of rows the user wants
341          */
342         var target_rows = $("#insert_rows").val();
344         // remove all datepickers
345         $('.datefield,.datetimefield').each(function(){
346             $(this).datepicker('destroy');
347         });
349         if(curr_rows < target_rows ) {
350             while( curr_rows < target_rows ) {
352                 /**
353                  * @var $last_row    Object referring to the last row
354                  */
355                 var $last_row = $("#insertForm").find(".insertRowTable:last");
357                 // need to access this at more than one level
358                 // (also needs improvement because it should be calculated
359                 //  just once per cloned row, not once per column)
360                 var new_row_index = 0;
362                 //Clone the insert tables
363                 $last_row
364                 .clone()
365                 .insertBefore("#actions_panel")
366                 .find('input[name*=multi_edit],select[name*=multi_edit],textarea[name*=multi_edit]')
367                 .each(function() {
369                     var $this_element = $(this);
370                     /**
371                      * Extract the index from the name attribute for all input/select fields and increment it
372                      * name is of format funcs[multi_edit][10][<long random string of alphanum chars>]
373                      */
375                     /**
376                      * @var this_name   String containing name of the input/select elements
377                      */
378                     var this_name = $this_element.attr('name');
379                     /** split {@link this_name} at [10], so we have the parts that can be concatenated later */
380                     var name_parts = this_name.split(/\[\d+\]/);
381                     /** extract the [10] from  {@link name_parts} */
382                     var old_row_index_string = this_name.match(/\[\d+\]/)[0];
383                     /** extract 10 - had to split into two steps to accomodate double digits */
384                     var old_row_index = parseInt(old_row_index_string.match(/\d+/)[0]);
386                     /** calculate next index i.e. 11 */
387                     new_row_index = old_row_index + 1;
388                     /** generate the new name i.e. funcs[multi_edit][11][foobarbaz] */
389                     var new_name = name_parts[0] + '[' + new_row_index + ']' + name_parts[1];
391                     var hashed_field = name_parts[1].match(/\[(.+)\]/)[1];
392                     $this_element.attr('name', new_name);
394                     if ($this_element.is('.textfield')) {
395                         // do not remove the 'value' attribute for ENUM columns
396                         if ($this_element.closest('tr').find('span.column_type').html() != 'enum') {
397                             $this_element.attr('value', $this_element.closest('tr').find('span.default_value').html());
398                         }
399                         $this_element
400                         .unbind('change')
401                         // Remove onchange attribute that was placed
402                         // by tbl_change.php; it refers to the wrong row index
403                         .attr('onchange', null)
404                         // Keep these values to be used when the element
405                         // will change
406                         .data('hashed_field', hashed_field)
407                         .data('new_row_index', new_row_index)
408                         .bind('change', function(e) {
409                             var $changed_element = $(this);
410                             verificationsAfterFieldChange(
411                                 $changed_element.data('hashed_field'), 
412                                 $changed_element.data('new_row_index'), 
413                                 $changed_element.closest('tr').find('span.column_type').html()
414                                 );
415                         });
416                     }
418                     if ($this_element.is('.checkbox_null')) {
419                         $this_element
420                         // this event was bound earlier by jQuery but
421                         // to the original row, not the cloned one, so unbind()
422                         .unbind('click')
423                         // Keep these values to be used when the element
424                         // will be clicked 
425                         .data('hashed_field', hashed_field)
426                         .data('new_row_index', new_row_index)
427                         .bind('click', function(e) {
428                                 var $changed_element = $(this);
429                                 nullify(
430                                     $changed_element.siblings('.nullify_code').val(),
431                                     $this_element.closest('tr').find('input:hidden').first().val(), 
432                                     $changed_element.data('hashed_field'), 
433                                     '[multi_edit][' + $changed_element.data('new_row_index') + ']'
434                                     );
435                         });
436                     }
437                 }) // end each
438                 .end()
439                 .find('.foreign_values_anchor')
440                 .each(function() {
441                         $anchor = $(this);
442                         var new_value = 'rownumber=' + new_row_index;
443                         // needs improvement in case something else inside
444                         // the href contains this pattern
445                         var new_href = $anchor.attr('href').replace(/rownumber=\d+/, new_value);
446                         $anchor.attr('href', new_href );
447                     });
449                 //Insert/Clone the ignore checkboxes
450                 if(curr_rows == 1 ) {
451                     $('<input id="insert_ignore_1" type="checkbox" name="insert_ignore_1" checked="checked" />')
452                     .insertBefore(".insertRowTable:last")
453                     .after('<label for="insert_ignore_1">' + PMA_messages['strIgnore'] + '</label>');
454                 }
455                 else {
457                     /**
458                      * @var last_checkbox   Object reference to the last checkbox in #insertForm
459                      */
460                     var last_checkbox = $("#insertForm").children('input:checkbox:last');
462                     /** name of {@link last_checkbox} */
463                     var last_checkbox_name = $(last_checkbox).attr('name');
464                     /** index of {@link last_checkbox} */
465                     var last_checkbox_index = parseInt(last_checkbox_name.match(/\d+/));
466                     /** name of new {@link last_checkbox} */
467                     var new_name = last_checkbox_name.replace(/\d+/,last_checkbox_index+1);
469                     $(last_checkbox)
470                     .clone()
471                     .attr({'id':new_name, 'name': new_name, 'checked': true})
472                     .add('label[for^=insert_ignore]:last')
473                     .clone()
474                     .attr('for', new_name)
475                     .before('<br />')
476                     .insertBefore(".insertRowTable:last");
477                 }
478                 curr_rows++;
479             }
480         // recompute tabindex for text fields and other controls at footer;
481         // IMO it's not really important to handle the tabindex for
482         // function and Null
483         var tabindex = 0;
484         $('.textfield') 
485         .each(function() {
486                 tabindex++;
487                 $(this).attr('tabindex', tabindex);
488                 // update the IDs of textfields to ensure that they are unique
489                 $(this).attr('id', "field_" + tabindex + "_3");
490             });
491         $('.control_at_footer')
492         .each(function() {
493                 tabindex++;
494                 $(this).attr('tabindex', tabindex);
495             });
496         // Add all the required datepickers back
497         $('.datefield,.datetimefield').each(function(){
498             PMA_addDatepicker($(this));
499             });
500         }
501         else if( curr_rows > target_rows) {
502             while(curr_rows > target_rows) {
503                 $("input[id^=insert_ignore]:last")
504                 .nextUntil("fieldset")
505                 .andSelf()
506                 .remove();
507                 curr_rows--;
508             }
509         }
510     })
511 }, 'top.frame_content'); //end $(document).ready()