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 from controls when the "NULL" checkbox is selected
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 // "SET" field , "ENUM" field with more than 20 characters
30 // or foreign key field (drop-down)
31 if (theType == 1 || theType == 3 || theType == 4) {
32 rowForm.elements['field_' + md5Field + multi_edit + '[]'].selectedIndex = -1;
35 else if (theType == 2) {
36 var elts = rowForm.elements['field_' + md5Field + multi_edit + '[]'];
37 // when there is just one option in ENUM:
41 var elts_cnt = elts.length;
42 for (var i = 0; i < elts_cnt; i++ ) {
43 elts[i].checked = false;
48 // foreign key field (with browsing icon for foreign values)
49 else if (theType == 6) {
50 rowForm.elements['field_' + md5Field + multi_edit + '[]'].value = '';
53 else /*if (theType == 5)*/ {
54 rowForm.elements['fields' + multi_edit + '[' + md5Field + ']'].value = '';
55 } // end if... else if... else
58 } // end of the 'nullify()' function
62 * javascript DateTime format validation.
63 * its used to prevent adding default (0000-00-00 00:00:00) to database when user enter wrong values
64 * Start of validation part
66 //function checks the number of days in febuary
67 function daysInFebruary (year){
68 return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
70 //function to convert single digit to double digit
71 function fractionReplace(num)
77 case 1:res= "01";break;
78 case 2:res= "02";break;
79 case 3:res= "03";break;
80 case 4:res= "04";break;
81 case 5:res= "05";break;
82 case 6:res= "06";break;
83 case 7:res= "07";break;
84 case 8:res= "08";break;
85 case 9:res= "09";break;
90 /* function to check the validity of date
91 * The following patterns are accepted in this validation (accepted in mysql as well)
95 * 4) And instead of using '-' the following punctuations can be used (+,.,*,^,@,/) All these are accepted by mysql as well. Therefore no issues
97 function isDate(val,tmstmp)
99 val=val.replace(/[.|*|^|+|//|@]/g,'-');
100 var arrayVal=val.split("-");
101 for(var a=0;a<arrayVal.length;a++)
103 if(arrayVal[a].length==1)
104 arrayVal[a]=fractionReplace(arrayVal[a]);
106 val=arrayVal.join("-");
108 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)))$/);
111 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)))$/);
116 var month=parseInt(val.substring(pos+3,pos+5));
117 var day=parseInt(val.substring(pos+6,pos+8));
118 var year=parseInt(val.substring(0,pos+2));
119 if(month==2&&day>daysInFebruary(year))
121 if(val.substring(0,pos+2).length==2)
123 if(val.substring(0,pos+2).length==2)
124 year=parseInt("20"+val.substring(0,pos+2));
126 year=parseInt("19"+val.substring(0,pos+2));
130 if(year<1978) return false;
131 if(year>2038||(year>2037&&day>19&&month>=1)||(year>2037&&month>1)) return false;
139 /* function to check the validity of time
140 * The following patterns are accepted in this validation (accepted in mysql as well)
146 var arrayVal=val.split(":");
147 for(var a=0;a<arrayVal.length;a++)
149 if(arrayVal[a].length==1)
150 arrayVal[a]=fractionReplace(arrayVal[a]);
152 val=arrayVal.join(":");
153 tmexp=new RegExp(/^(([0-1][0-9])|(2[0-3])):((0[0-9])|([1-5][0-9])):((0[0-9])|([1-5][0-9]))$/);
158 //validate the datetime and integer
159 function Validator(urlField, multi_edit,theType){
160 var rowForm = document.forms['insertForm'];
161 var evt = window.event || arguments.callee.caller.arguments[0];
162 var target = evt.target || evt.srcElement;
163 unNullify(urlField, multi_edit);
165 if(target.name.substring(0,6)=="fields")
167 var dt=rowForm.elements['fields[multi_edit][' + multi_edit + '][' + urlField + ']'];
168 // validate for date time
169 if(theType=="datetime"||theType=="time"||theType=="date"||theType=="timestamp")
172 if(!isDate(dt.value))
174 dt.className="invalid_value";
178 else if(theType=="time")
180 if(!isTime(dt.value))
182 dt.className="invalid_value";
186 else if(theType=="datetime"||theType=="timestamp")
189 if(dt.value=="CURRENT_TIMESTAMP")
194 if(theType=="timestamp")
198 if(dt.value=="0000-00-00 00:00:00")
200 var dv=dt.value.indexOf(" ");
203 dt.className="invalid_value";
208 if(!(isDate(dt.value.substring(0,dv),tmstmp)&&isTime(dt.value.substring(dv+1))))
210 dt.className="invalid_value";
216 //validate for integer type
217 if(theType.substring(0,3)=="int"){
220 dt.className="invalid_value";
226 /* End of datetime validation*/
229 * Unchecks the "NULL" control when a function has been selected or a value
232 * @param string the urlencoded field name
233 * @param string the multi_edit row sequence number
235 * @return boolean always true
237 function unNullify(urlField, multi_edit)
239 var rowForm = document.forms['insertForm'];
241 if (typeof(rowForm.elements['fields_null[multi_edit][' + multi_edit + '][' + urlField + ']']) != 'undefined') {
242 rowForm.elements['fields_null[multi_edit][' + multi_edit + '][' + urlField + ']'].checked = false
245 if (typeof(rowForm.elements['insert_ignore_' + multi_edit]) != 'undefined') {
246 rowForm.elements['insert_ignore_' + multi_edit].checked = false
250 } // end of the 'unNullify()' function
253 * Ajax handlers for Change Table page
255 * Actions Ajaxified here:
256 * Submit Data to be inserted into the table
257 * Restart insertion with 'N' rows.
259 $(document).ready(function() {
261 // these were hidden via the "hide" class
262 $('.foreign_values_anchor').show();
265 * Handles all current checkboxes for Null
268 $('.checkbox_null').bind('click', function(e) {
270 // use hidden fields populated by tbl_change.php
271 $(this).siblings('.nullify_code').val(),
272 $(this).closest('tr').find('input:hidden').first().val(),
273 $(this).siblings('.hashed_field').val(),
274 $(this).siblings('.multi_edit').val()
279 * Submission of data to be inserted or updated
281 * @uses PMA_ajaxShowMessage()
283 * This section has been deactivated. Here are the problems that I've
286 * 1. If the form contains a file upload field, the data does not reach
287 * tbl_replace.php. This is because AJAX does not support file upload.
288 * As a workaround I tried jquery.form.js version 2.49. The file
289 * upload worked but afterwards the browser presented a tbl_replace.php
290 * file and a choice to open or save.
292 * 2. This code can be called if we are editing or inserting. If editing,
293 * the "and then" action can be "go back to this page" or "edit next
294 * row", in which cases it makes sense to use AJAX. But the "go back
295 * to previous page" and "insert another new row" actions, using AJAX
296 * has no obvious advantage. If inserting, the "go back to previous"
297 * action needs a page refresh anyway.
299 $("#insertFormDEACTIVATED").live('submit', function(event) {
302 * @var the_form Object referring to the insertion form
305 event.preventDefault();
307 PMA_ajaxShowMessage();
308 if (! $form.find('input:hidden').is('#ajax_request_hidden')) {
309 $form.append('<input type="hidden" id="ajax_request_hidden" name="ajax_request" value="true" />');
312 $.post($form.attr('action'), $form.serialize(), function(data) {
313 if (typeof data.success != 'undefined') {
314 if(data.success == true) {
315 PMA_ajaxShowMessage(data.message);
317 $("#topmenucontainer")
321 .after(data.sql_query);
323 //Remove the empty notice div generated due to a NULL query passed to PMA_showMessage()
324 var $notice_class = $("#topmenucontainer").next("div").find('.notice');
325 if ($notice_class.text() == '') {
326 $notice_class.remove();
329 var submit_type = $form.find("select[name='submit_type']").val();
330 if ('insert' == submit_type || 'insertignore' == submit_type) {
331 //Clear the data in the forms
332 $form.find('input:reset').trigger('click');
335 PMA_ajaxShowMessage(PMA_messages['strErrorProcessingRequest'] + " : "+data.error, "7000");
338 //happens for example when no change was done while editing
339 $('#insertForm').remove();
340 $('#topmenucontainer').after('<div id="sqlqueryresults"></div>');
341 $('#sqlqueryresults').html(data);
344 }) // end submission of data to be inserted into table
347 * Continue Insertion form
349 $("#insert_rows").live('change', function(event) {
350 event.preventDefault();
353 * @var curr_rows Number of current insert rows already on page
355 var curr_rows = $(".insertRowTable").length;
357 * @var target_rows Number of rows the user wants
359 var target_rows = $("#insert_rows").val();
361 if(curr_rows < target_rows ) {
362 while( curr_rows < target_rows ) {
365 * @var $last_row Object referring to the last row
367 var $last_row = $("#insertForm").find(".insertRowTable:last");
369 // need to access this at more than one level
370 // (also needs improvement because it should be calculated
371 // just once per cloned row, not once per column)
372 var new_row_index = 0;
374 //Clone the insert tables
377 .insertBefore("#actions_panel")
378 .find('input[name*=multi_edit],select[name*=multi_edit]')
381 var $this_element = $(this);
383 * Extract the index from the name attribute for all input/select fields and increment it
384 * name is of format funcs[multi_edit][10][<long random string of alphanum chars>]
388 * @var this_name String containing name of the input/select elements
390 var this_name = $this_element.attr('name');
391 /** split {@link this_name} at [10], so we have the parts that can be concatenated later */
392 var name_parts = this_name.split(/\[\d+\]/);
393 /** extract the [10] from {@link name_parts} */
394 var old_row_index_string = this_name.match(/\[\d+\]/)[0];
395 /** extract 10 - had to split into two steps to accomodate double digits */
396 var old_row_index = parseInt(old_row_index_string.match(/\d+/)[0]);
398 /** calculate next index i.e. 11 */
399 new_row_index = old_row_index + 1;
400 /** generate the new name i.e. funcs[multi_edit][11][foobarbaz] */
401 var new_name = name_parts[0] + '[' + new_row_index + ']' + name_parts[1];
403 var hashed_field = name_parts[1].match(/\[(.+)\]/)[1];
404 $this_element.attr('name', new_name);
406 if ($this_element.is('.textfield')) {
410 // Keep these values to be used when the element
412 .data('hashed_field', hashed_field)
413 .data('new_row_index', new_row_index)
414 .bind('change', function(e) {
415 var $changed_element = $(this);
417 $changed_element.data('hashed_field'),
418 $changed_element.data('new_row_index'),
419 $changed_element.closest('tr').find('span.column_type').html()
424 if ($this_element.is('.checkbox_null')) {
426 .bind('click', function(e) {
428 $this_element.siblings('.nullify_code').val(),
429 $this_element.closest('tr').find('input:hidden').first().val(),
431 '[multi_edit][' + new_row_index + ']'
437 .find('.foreign_values_anchor')
440 var new_value = 'rownumber=' + new_row_index;
441 // needs improvement in case something else inside
442 // the href contains this pattern
443 var new_href = $anchor.attr('href').replace(/rownumber=\d+/, new_value);
444 $anchor.attr('href', new_href );
447 //Insert/Clone the ignore checkboxes
448 if(curr_rows == 1 ) {
449 $('<input id="insert_ignore_1" type="checkbox" name="insert_ignore_1" checked="checked" />')
450 .insertBefore(".insertRowTable:last")
451 .after('<label for="insert_ignore_1">' + PMA_messages['strIgnore'] + '</label>');
456 * @var last_checkbox Object reference to the last checkbox in #insertForm
458 var last_checkbox = $("#insertForm").children('input:checkbox:last');
460 /** name of {@link last_checkbox} */
461 var last_checkbox_name = $(last_checkbox).attr('name');
462 /** index of {@link last_checkbox} */
463 var last_checkbox_index = parseInt(last_checkbox_name.match(/\d+/));
464 /** name of new {@link last_checkbox} */
465 var new_name = last_checkbox_name.replace(/\d+/,last_checkbox_index+1);
469 .attr({'id':new_name, 'name': new_name, 'checked': true})
470 .add('label[for^=insert_ignore]:last')
472 .attr('for', new_name)
474 .insertBefore(".insertRowTable:last");
478 // recompute tabindex for text fields and other controls at footer;
479 // IMO it's not really important to handle the tabindex for
485 $(this).attr('tabindex', tabindex);
487 $('.control_at_footer')
490 $(this).attr('tabindex', tabindex);
493 else if( curr_rows > target_rows) {
494 while(curr_rows > target_rows) {
495 $("input[id^=insert_ignore]:last")
496 .nextUntil("fieldset")
503 }, 'top.frame_content'); //end $(document).ready()