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()
285 * Submission of data to be inserted or updated
287 * @uses PMA_ajaxShowMessage()
289 * This section has been deactivated. Here are the problems that I've
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.
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.
305 $("#insertFormDEACTIVATED").live('submit', function(event) {
308 * @var the_form Object referring to the insertion form
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")
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();
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');
339 PMA_ajaxShowMessage(PMA_messages['strErrorProcessingRequest'] + " : " + data.error, false);
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);
348 }) // end submission of data to be inserted into table
351 * Continue Insertion form
353 $("#insert_rows").live('change', function(event) {
354 event.preventDefault();
357 * @var curr_rows Number of current insert rows already on page
359 var curr_rows = $(".insertRowTable").length;
361 * @var target_rows Number of rows the user wants
363 var target_rows = $("#insert_rows").val();
365 // remove all datepickers
366 $('.datefield,.datetimefield').each(function(){
367 $(this).datepicker('destroy');
370 if(curr_rows < target_rows ) {
371 while( curr_rows < target_rows ) {
374 * @var $last_row Object referring to the last row
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
386 .insertBefore("#actions_panel")
387 .find('input[name*=multi_edit],select[name*=multi_edit],textarea[name*=multi_edit]')
390 var $this_element = $(this);
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>]
397 * @var this_name String containing name of the input/select elements
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());
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
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()
439 if ($this_element.is('.checkbox_null')) {
441 // this event was bound earlier by jQuery but
442 // to the original row, not the cloned one, so unbind()
444 // Keep these values to be used when the element
446 .data('hashed_field', hashed_field)
447 .data('new_row_index', new_row_index)
448 .bind('click', function(e) {
449 var $changed_element = $(this);
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') + ']'
460 .find('.foreign_values_anchor')
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 );
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>');
479 * @var last_checkbox Object reference to the last checkbox in #insertForm
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);
492 .attr({'id':new_name, 'name': new_name, 'checked': true})
493 .add('label[for^=insert_ignore]:last')
495 .attr('for', new_name)
497 .insertBefore(".insertRowTable:last");
501 // recompute tabindex for text fields and other controls at footer;
502 // IMO it's not really important to handle the tabindex for
508 $(this).attr('tabindex', tabindex);
509 // update the IDs of textfields to ensure that they are unique
510 $(this).attr('id', "field_" + tabindex + "_3");
512 $('.control_at_footer')
515 $(this).attr('tabindex', tabindex);
517 // Add all the required datepickers back
518 $('.datefield,.datetimefield').each(function(){
519 PMA_addDatepicker($(this));
522 else if( curr_rows > target_rows) {
523 while(curr_rows > target_rows) {
524 $("input[id^=insert_ignore]:last")
525 .nextUntil("fieldset")
532 }, 'top.frame_content'); //end $(document).ready()