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)
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)
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)
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++)
98 if(arrayVal[a].length==1)
99 arrayVal[a]=fractionReplace(arrayVal[a]);
101 val=arrayVal.join("-");
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)))$/);
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)))$/);
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))
116 if(val.substring(0,pos+2).length==2)
118 if(val.substring(0,pos+2).length==2)
119 year=parseInt("20"+val.substring(0,pos+2));
121 year=parseInt("19"+val.substring(0,pos+2));
125 if(year<1978) return false;
126 if(year>2038||(year>2037&&day>19&&month>=1)||(year>2037&&month>1)) return false;
134 /* function to check the validity of time
135 * The following patterns are accepted in this validation (accepted in mysql as well)
141 var arrayVal=val.split(":");
142 for(var a=0;a<arrayVal.length;a++)
144 if(arrayVal[a].length==1)
145 arrayVal[a]=fractionReplace(arrayVal[a]);
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]))$/);
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', '');
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();
180 if (! isDate(dt_value)) {
181 $this_input.addClass("invalid_value");
184 } else if(theType=="time") {
185 if (! isTime(dt_value)) {
186 $this_input.addClass("invalid_value");
189 } else if(theType=="datetime"||theType=="timestamp") {
191 if(dt_value == "CURRENT_TIMESTAMP") {
194 if(theType=="timestamp") {
197 if(dt_value=="0000-00-00 00:00:00") {
200 var dv=dt_value.indexOf(" ");
202 $this_input.addClass("invalid_value");
205 if (! (isDate(dt_value.substring(0,dv),tmstmp) && isTime(dt_value.substring(dv+1)))) {
206 $this_input.addClass("invalid_value");
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");
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.
231 $(document).ready(function() {
233 $('.open_gis_editor').live('click', function(event) {
234 event.preventDefault();
238 var value = $span.parent('td').children("input[type='text']").val();
240 var field = $span.parents('tr').children('td:first').find("input[type='hidden']").val();
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');
246 var token = $("input[name='token']").val();
249 if (!gisEditorLoaded) {
250 loadJSAndGISEditor(value, field, type, input_name, token);
252 loadGISEditor(value, field, type, input_name, token);
257 * Uncheck the null checkbox as geometry data is placed on the input field
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);
265 // these were hidden via the "hide" class
266 $('.foreign_values_anchor').show();
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
274 $('.checkbox_null').bind('click', function(e) {
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()
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
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);
302 $(value_field).val(previous_value);
311 * Submission of data to be inserted or updated
313 * @uses PMA_ajaxShowMessage()
315 * This section has been deactivated. Here are the problems that I've
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.
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.
331 $("#insertFormDEACTIVATED").live('submit', function(event) {
334 * @var the_form Object referring to the insertion form
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")
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();
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');
365 PMA_ajaxShowMessage(PMA_messages['strErrorProcessingRequest'] + " : " + data.error, false);
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);
374 }) // end submission of data to be inserted into table
377 * Continue Insertion form
379 $("#insert_rows").live('change', function(event) {
380 event.preventDefault();
383 * @var curr_rows Number of current insert rows already on page
385 var curr_rows = $(".insertRowTable").length;
387 * @var target_rows Number of rows the user wants
389 var target_rows = $("#insert_rows").val();
391 // remove all datepickers
392 $('.datefield,.datetimefield').each(function(){
393 $(this).datepicker('destroy');
396 if(curr_rows < target_rows ) {
397 while( curr_rows < target_rows ) {
400 * @var $last_row Object referring to the last row
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
412 .insertBefore("#actions_panel")
413 .find('input[name*=multi_edit],select[name*=multi_edit],textarea[name*=multi_edit]')
416 var $this_element = $(this);
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>]
423 * @var this_name String containing name of the input/select elements
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());
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
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()
465 if ($this_element.is('.checkbox_null')) {
467 // this event was bound earlier by jQuery but
468 // to the original row, not the cloned one, so unbind()
470 // Keep these values to be used when the element
472 .data('hashed_field', hashed_field)
473 .data('new_row_index', new_row_index)
474 .bind('click', function(e) {
475 var $changed_element = $(this);
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') + ']'
486 .find('.foreign_values_anchor')
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 );
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>');
505 * @var last_checkbox Object reference to the last checkbox in #insertForm
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);
518 .attr({'id':new_name, 'name': new_name, 'checked': true})
519 .add('label[for^=insert_ignore]:last')
521 .attr('for', new_name)
523 .insertBefore(".insertRowTable:last");
527 // recompute tabindex for text fields and other controls at footer;
528 // IMO it's not really important to handle the tabindex for
534 $(this).attr('tabindex', tabindex);
535 // update the IDs of textfields to ensure that they are unique
536 $(this).attr('id', "field_" + tabindex + "_3");
538 $('.control_at_footer')
541 $(this).attr('tabindex', tabindex);
543 // Add all the required datepickers back
544 $('.datefield,.datetimefield').each(function(){
545 PMA_addDatepicker($(this));
548 else if( curr_rows > target_rows) {
549 while(curr_rows > target_rows) {
550 $("input[id^=insert_ignore]:last")
551 .nextUntil("fieldset")
558 }, 'top.frame_content'); //end $(document).ready()