1 /* vim: set expandtab sw=4 ts=4 sts=4: */
3 * @fileoverview function used in table data manipulation pages
7 * @requires js/functions.js
12 * Modify form controls when the "NULL" checkbox is checked
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
19 * @return boolean always true
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;
29 // "ENUM" field with more than 20 characters
31 rowForm.elements['fields' + multi_edit + '[' + md5Field + ']'][1].selectedIndex = -1;
34 else if (theType == 2) {
35 var elts = rowForm.elements['fields' + multi_edit + '[' + md5Field + ']'];
36 // when there is just one option in ENUM:
40 var elts_cnt = elts.length;
41 for (var i = 0; i < elts_cnt; i++ ) {
42 elts[i].checked = false;
48 else if (theType == 3) {
49 rowForm.elements['fields' + multi_edit + '[' + md5Field + '][]'].selectedIndex = -1;
51 // Foreign key field (drop-down)
52 else if (theType == 4) {
53 rowForm.elements['fields' + multi_edit + '[' + md5Field + ']'].selectedIndex = -1;
55 // foreign key field (with browsing icon for foreign values)
56 else if (theType == 6) {
57 rowForm.elements['fields' + multi_edit + '[' + md5Field + ']'].value = '';
60 else /*if (theType == 5)*/ {
61 rowForm.elements['fields' + multi_edit + '[' + md5Field + ']'].value = '';
62 } // end if... else if... else
65 } // end of the 'nullify()' function
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
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)
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;
97 /* function to check the validity of date
98 * The following patterns are accepted in this validation (accepted in mysql as well)
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++)
110 if(arrayVal[a].length==1)
111 arrayVal[a]=fractionReplace(arrayVal[a]);
113 val=arrayVal.join("-");
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)))$/);
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)))$/);
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))
128 if(val.substring(0,pos+2).length==2)
130 if(val.substring(0,pos+2).length==2)
131 year=parseInt("20"+val.substring(0,pos+2));
133 year=parseInt("19"+val.substring(0,pos+2));
137 if(year<1978) return false;
138 if(year>2038||(year>2037&&day>19&&month>=1)||(year>2037&&month>1)) return false;
146 /* function to check the validity of time
147 * The following patterns are accepted in this validation (accepted in mysql as well)
153 var arrayVal=val.split(":");
154 for(var a=0;a<arrayVal.length;a++)
156 if(arrayVal[a].length==1)
157 arrayVal[a]=fractionReplace(arrayVal[a]);
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]))$/);
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', '');
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();
191 if (! isDate(dt_value)) {
192 $this_input.addClass("invalid_value");
195 } else if(theType=="time") {
196 if (! isTime(dt_value)) {
197 $this_input.addClass("invalid_value");
200 } else if(theType=="datetime"||theType=="timestamp") {
202 if(dt_value == "CURRENT_TIMESTAMP") {
205 if(theType=="timestamp") {
208 if(dt_value=="0000-00-00 00:00:00") {
211 var dv=dt_value.indexOf(" ");
213 $this_input.addClass("invalid_value");
216 if (! (isDate(dt_value.substring(0,dv),tmstmp) && isTime(dt_value.substring(dv+1)))) {
217 $this_input.addClass("invalid_value");
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");
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.
242 $(document).ready(function() {
244 // these were hidden via the "hide" class
245 $('.foreign_values_anchor').show();
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
253 $('.checkbox_null').bind('click', function(e) {
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()
264 * Submission of data to be inserted or updated
266 * @uses PMA_ajaxShowMessage()
268 * This section has been deactivated. Here are the problems that I've
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.
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.
284 $("#insertFormDEACTIVATED").live('submit', function(event) {
287 * @var the_form Object referring to the insertion form
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")
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();
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');
318 PMA_ajaxShowMessage(PMA_messages['strErrorProcessingRequest'] + " : "+data.error, "7000");
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);
327 }) // end submission of data to be inserted into table
330 * Continue Insertion form
332 $("#insert_rows").live('change', function(event) {
333 event.preventDefault();
336 * @var curr_rows Number of current insert rows already on page
338 var curr_rows = $(".insertRowTable").length;
340 * @var target_rows Number of rows the user wants
342 var target_rows = $("#insert_rows").val();
344 // remove all datepickers
345 $('.datefield,.datetimefield').each(function(){
346 $(this).datepicker('destroy');
349 if(curr_rows < target_rows ) {
350 while( curr_rows < target_rows ) {
353 * @var $last_row Object referring to the last row
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
365 .insertBefore("#actions_panel")
366 .find('input[name*=multi_edit],select[name*=multi_edit],textarea[name*=multi_edit]')
369 var $this_element = $(this);
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>]
376 * @var this_name String containing name of the input/select elements
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());
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
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()
418 if ($this_element.is('.checkbox_null')) {
420 // this event was bound earlier by jQuery but
421 // to the original row, not the cloned one, so unbind()
423 // Keep these values to be used when the element
425 .data('hashed_field', hashed_field)
426 .data('new_row_index', new_row_index)
427 .bind('click', function(e) {
428 var $changed_element = $(this);
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') + ']'
439 .find('.foreign_values_anchor')
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 );
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>');
458 * @var last_checkbox Object reference to the last checkbox in #insertForm
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);
471 .attr({'id':new_name, 'name': new_name, 'checked': true})
472 .add('label[for^=insert_ignore]:last')
474 .attr('for', new_name)
476 .insertBefore(".insertRowTable:last");
480 // recompute tabindex for text fields and other controls at footer;
481 // IMO it's not really important to handle the tabindex for
487 $(this).attr('tabindex', tabindex);
488 // update the IDs of textfields to ensure that they are unique
489 $(this).attr('id', "field_" + tabindex + "_3");
491 $('.control_at_footer')
494 $(this).attr('tabindex', tabindex);
496 // Add all the required datepickers back
497 $('.datefield,.datetimefield').each(function(){
498 PMA_addDatepicker($(this));
501 else if( curr_rows > target_rows) {
502 while(curr_rows > target_rows) {
503 $("input[id^=insert_ignore]:last")
504 .nextUntil("fieldset")
511 }, 'top.frame_content'); //end $(document).ready()