1 /* vim: set expandtab sw=4 ts=4 sts=4: */
3 * Create advanced table (resize, reorder, and show/hide columns; and also grid editing).
4 * This function is designed mainly for table DOM generated from browsing a table in the database.
5 * For using this function in other table DOM, you may need to:
6 * - add "draggable" class in the table header <th>, in order to make it resizable, sortable or hidable
7 * - have at least one non-"draggable" header in the table DOM for placing column visibility drop-down arrow
8 * - pass the value "false" for the parameter "enableGridEdit"
9 * - adjust other parameter value, to select which features that will be enabled
11 * @param t the table DOM element
12 * @param enableResize Optional, if false, column resizing feature will be disabled
13 * @param enableReorder Optional, if false, column reordering feature will be disabled
14 * @param enableVisib Optional, if false, show/hide column feature will be disabled
15 * @param enableGridEdit Optional, if false, grid editing feature will be disabled
17 function PMA_makegrid(t, enableResize, enableReorder, enableVisib, enableGridEdit) {
26 * Variables, assigned with default value, changed later
28 actionSpan: 5, // number of colspan in Actions header in a table
29 tableCreateTime: null, // table creation time, used for saving column order and visibility to server, only available in "Browse tab"
31 // Column reordering variables
32 colOrder: [], // array of column order
34 // Column visibility variables
35 colVisib: [], // array of column visibility
36 showAllColText: '', // string, text for "show all" button under column visibility list
37 visibleHeadersCount: 0, // number of visible data headers
39 // Table hint variables
40 reorderHint: '', // string, hint for column reordering
41 sortHint: '', // string, hint for column sorting
42 markHint: '', // string, hint for column marking
43 copyHint: '', // string, hint for copy column name
44 showReorderHint: false,
49 isCellEditActive: false, // true if current focus is in edit cell
50 isEditCellTextEditable: false, // true if current edit cell is editable in the text input box (not textarea)
51 currentEditCell: null, // reference to <td> that currently being edited
52 cellEditHint: '', // hint shown when doing grid edit
53 gotoLinkText: '', // "Go to link" text
54 wasEditedCellNull: false, // true if last value of the edited cell was NULL
55 maxTruncatedLen: 0, // number of characters that can be displayed in a cell
56 saveCellsAtOnce: false, // $cfg[saveCellsAtOnce]
57 isCellEdited: false, // true if at least one cell has been edited
58 saveCellWarning: '', // string, warning text when user want to leave a page with unsaved edited data
59 lastXHR : null, // last XHR object used in AJAX request
60 isSaving: false, // true when currently saving edited data, used to handle double posting caused by pressing ENTER in grid edit text box in Chrome browser
61 alertNonUnique: '', // string, alert shown when saving edited nonunique table
63 // Common hidden inputs
75 * Start to resize column. Called when clicking on column separator.
78 * @param obj dragged div object
80 dragStartRsz: function (e, obj) {
81 var n = $(g.cRsz).find('div').index(obj); // get the index of separator (i.e., column index)
82 $(obj).addClass('colborder_active');
87 objLeft: $(obj).position().left,
88 objWidth: $(g.t).find('th.draggable:visible:eq(' + n + ') span').outerWidth()
90 $(document.body).css('cursor', 'col-resize').noSelect();
91 if (g.isCellEditActive) {
97 * Start to reorder column. Called when clicking on table header.
100 * @param obj table header object
102 dragStartReorder: function (e, obj) {
103 // prepare the cCpy (column copy) and cPointer (column pointer) from the dragged column
104 $(g.cCpy).text($(obj).text());
105 var objPos = $(obj).position();
107 top: objPos.top + 20,
109 height: $(obj).height(),
110 width: $(obj).width()
116 // get the column index, zero-based
117 var n = g.getHeaderIdx(obj);
129 $(document.body).css('cursor', 'move').noSelect();
130 if (g.isCellEditActive) {
136 * Handle mousemove event when dragging.
140 dragMove: function (e) {
142 var dx = e.pageX - g.colRsz.x0;
143 if (g.colRsz.objWidth + dx > g.minColWidth) {
144 $(g.colRsz.obj).css('left', g.colRsz.objLeft + dx + 'px');
146 } else if (g.colReorder) {
147 // dragged column animation
148 var dx = e.pageX - g.colReorder.x0;
150 .css('left', g.colReorder.objLeft + dx)
154 var hoveredCol = g.getHoveredCol(e);
156 var newn = g.getHeaderIdx(hoveredCol);
157 g.colReorder.newn = newn;
158 if (newn != g.colReorder.n) {
159 // show the column pointer in the right place
160 var colPos = $(hoveredCol).position();
161 var newleft = newn < g.colReorder.n ?
163 colPos.left + $(hoveredCol).outerWidth();
167 visibility: 'visible'
170 // no movement to other column, hide the column pointer
171 $(g.cPointer).css('visibility', 'hidden');
178 * Stop the dragging action.
182 dragEnd: function (e) {
184 var dx = e.pageX - g.colRsz.x0;
185 var nw = g.colRsz.objWidth + dx;
186 if (nw < g.minColWidth) {
196 $(g.cRsz).find('div').removeClass('colborder_active');
197 rearrangeStickyColumns($(t).prev('.sticky_columns'), $(t));
198 } else if (g.colReorder) {
200 if (g.colReorder.newn != g.colReorder.n) {
201 g.shiftCol(g.colReorder.n, g.colReorder.newn);
202 // assign new position
203 var objPos = $(g.colReorder.obj).position();
204 g.colReorder.objTop = objPos.top;
205 g.colReorder.objLeft = objPos.left;
206 g.colReorder.n = g.colReorder.newn;
207 // send request to server to remember the column order
208 if (g.tableCreateTime) {
211 g.refreshRestoreButton();
214 // animate new column position
215 $(g.cCpy).stop(true, true)
217 top: g.colReorder.objTop,
218 left: g.colReorder.objLeft
221 $(g.cPointer).css('visibility', 'hidden');
223 g.colReorder = false;
224 rearrangeStickyColumns($(t).prev('.sticky_columns'), $(t));
226 $(document.body).css('cursor', 'inherit').noSelect(false);
230 * Resize column n to new width "nw"
232 * @param n zero-based column index
233 * @param nw new width of the column in pixel
235 resize: function (n, nw) {
236 $(g.t).find('tr').each(function () {
237 $(this).find('th.draggable:visible:eq(' + n + ') span,' +
238 'td:visible:eq(' + (g.actionSpan + n) + ') span')
244 * Reposition column resize bars.
246 reposRsz: function () {
247 $(g.cRsz).find('div').hide();
248 var $firstRowCols = $(g.t).find('tr:first th.draggable:visible');
249 var $resizeHandles = $(g.cRsz).find('div').removeClass('condition');
250 $(g.t).find('table.pma_table').find('thead th:first').removeClass('before-condition');
251 for (var n = 0, l = $firstRowCols.length; n < l; n++) {
252 var $col = $($firstRowCols[n]);
254 if (navigator.userAgent.toLowerCase().indexOf("safari") != -1) {
255 colWidth = $col.outerWidth();
257 colWidth = $col.outerWidth(true);
259 $($resizeHandles[n]).css('left', $col.position().left + colWidth)
261 if ($col.hasClass('condition')) {
262 $($resizeHandles[n]).addClass('condition');
264 $($resizeHandles[n - 1]).addClass('condition');
268 if ($($resizeHandles[0]).hasClass('condition')) {
269 $(g.t).find('thead th:first').addClass('before-condition');
271 $(g.cRsz).css('height', $(g.t).height());
275 * Shift column from index oldn to newn.
277 * @param oldn old zero-based column index
278 * @param newn new zero-based column index
280 shiftCol: function (oldn, newn) {
281 $(g.t).find('tr').each(function () {
283 $(this).find('th.draggable:eq(' + newn + '),' +
284 'td:eq(' + (g.actionSpan + newn) + ')')
285 .before($(this).find('th.draggable:eq(' + oldn + '),' +
286 'td:eq(' + (g.actionSpan + oldn) + ')'));
288 $(this).find('th.draggable:eq(' + newn + '),' +
289 'td:eq(' + (g.actionSpan + newn) + ')')
290 .after($(this).find('th.draggable:eq(' + oldn + '),' +
291 'td:eq(' + (g.actionSpan + oldn) + ')'));
294 // reposition the column resize bars
297 // adjust the column visibility list
299 $(g.cList).find('.lDiv div:eq(' + newn + ')')
300 .before($(g.cList).find('.lDiv div:eq(' + oldn + ')'));
302 $(g.cList).find('.lDiv div:eq(' + newn + ')')
303 .after($(g.cList).find('.lDiv div:eq(' + oldn + ')'));
305 // adjust the colOrder
306 var tmp = g.colOrder[oldn];
307 g.colOrder.splice(oldn, 1);
308 g.colOrder.splice(newn, 0, tmp);
309 // adjust the colVisib
310 if (g.colVisib.length > 0) {
311 tmp = g.colVisib[oldn];
312 g.colVisib.splice(oldn, 1);
313 g.colVisib.splice(newn, 0, tmp);
318 * Find currently hovered table column's header (excluding actions column).
321 * @return the hovered column's th object or undefined if no hovered column found.
323 getHoveredCol: function (e) {
325 $headers = $(g.t).find('th.draggable:visible');
326 $headers.each(function () {
327 var left = $(this).offset().left;
328 var right = left + $(this).outerWidth();
329 if (left <= e.pageX && e.pageX <= right) {
337 * Get a zero-based index from a <th class="draggable"> tag in a table.
339 * @param obj table header <th> object
340 * @return zero-based index of the specified table header in the set of table headers (visible or not)
342 getHeaderIdx: function (obj) {
343 return $(obj).parents('tr').find('th.draggable').index(obj);
347 * Reposition the columns back to normal order.
349 restoreColOrder: function () {
350 // use insertion sort, since we already have shiftCol function
351 for (var i = 1; i < g.colOrder.length; i++) {
352 var x = g.colOrder[i];
354 while (j >= 0 && x < g.colOrder[j]) {
358 g.shiftCol(i, j + 1);
361 if (g.tableCreateTime) {
362 // send request to server to remember the column order
365 g.refreshRestoreButton();
369 * Send column preferences (column order and visibility) to the server.
371 sendColPrefs: function () {
372 if ($(g.t).is('.ajax')) { // only send preferences if ajax class
380 table_create_time: g.tableCreateTime
382 if (g.colOrder.length > 0) {
383 $.extend(post_params, {col_order: g.colOrder.toString()});
385 if (g.colVisib.length > 0) {
386 $.extend(post_params, {col_visib: g.colVisib.toString()});
388 $.post('sql.php', post_params, function (data) {
389 if (data.success !== true) {
390 var $temp_div = $(document.createElement('div'));
391 $temp_div.html(data.error);
392 $temp_div.addClass("error");
393 PMA_ajaxShowMessage($temp_div, false);
400 * Refresh restore button state.
401 * Make restore button disabled if the table is similar with initial state.
403 refreshRestoreButton: function () {
404 // check if table state is as initial state
405 var isInitial = true;
406 for (var i = 0; i < g.colOrder.length; i++) {
407 if (g.colOrder[i] != i) {
412 // check if only one visible column left
413 var isOneColumn = g.visibleHeadersCount == 1;
414 // enable or disable restore button
415 if (isInitial || isOneColumn) {
416 $(g.o).find('div.restore_column').hide();
418 $(g.o).find('div.restore_column').show();
423 * Update current hint using the boolean values (showReorderHint, showSortHint, etc.).
426 updateHint: function () {
428 if (!g.colRsz && !g.colReorder) { // if not resizing or dragging
429 if (g.visibleHeadersCount > 1) {
430 g.showReorderHint = true;
432 if ($(t).find('th.marker').length > 0) {
433 g.showMarkHint = true;
435 if (g.showSortHint && g.sortHint) {
436 text += text.length > 0 ? '<br />' : '';
437 text += '- ' + g.sortHint;
439 if (g.showMultiSortHint && g.strMultiSortHint) {
440 text += text.length > 0 ? '<br />' : '';
441 text += '- ' + g.strMultiSortHint;
443 if (g.showMarkHint &&
445 ! g.showSortHint && // we do not show mark hint, when sort hint is shown
449 text += text.length > 0 ? '<br />' : '';
450 text += '- ' + g.reorderHint;
451 text += text.length > 0 ? '<br />' : '';
452 text += '- ' + g.markHint;
453 text += text.length > 0 ? '<br />' : '';
454 text += '- ' + g.copyHint;
461 * Toggle column's visibility.
462 * After calling this function and it returns true, afterToggleCol() must be called.
464 * @return boolean True if the column is toggled successfully.
466 toggleCol: function (n) {
468 // can hide if more than one column is visible
469 if (g.visibleHeadersCount > 1) {
470 $(g.t).find('tr').each(function () {
471 $(this).find('th.draggable:eq(' + n + '),' +
472 'td:eq(' + (g.actionSpan + n) + ')')
476 $(g.cList).find('.lDiv div:eq(' + n + ') input').prop('checked', false);
478 // cannot hide, force the checkbox to stay checked
479 $(g.cList).find('.lDiv div:eq(' + n + ') input').prop('checked', true);
482 } else { // column n is not visible
483 $(g.t).find('tr').each(function () {
484 $(this).find('th.draggable:eq(' + n + '),' +
485 'td:eq(' + (g.actionSpan + n) + ')')
489 $(g.cList).find('.lDiv div:eq(' + n + ') input').prop('checked', true);
495 * This must be called if toggleCol() returns is true.
497 * This function is separated from toggleCol because, sometimes, we want to toggle
498 * some columns together at one time and do just one adjustment after it, e.g. in showAllColumns().
500 afterToggleCol: function () {
501 // some adjustments after hiding column
506 // check visible first row headers count
507 g.visibleHeadersCount = $(g.t).find('tr:first th.draggable:visible').length;
508 g.refreshRestoreButton();
512 * Show columns' visibility list.
514 * @param obj The drop down arrow of column visibility list
516 showColList: function (obj) {
517 // only show when not resizing or reordering
518 if (!g.colRsz && !g.colReorder) {
519 var pos = $(obj).position();
520 // check if the list position is too right
521 if (pos.left + $(g.cList).outerWidth(true) > $(document).width()) {
522 pos.left = $(document).width() - $(g.cList).outerWidth(true);
526 top: pos.top + $(obj).outerHeight(true)
529 $(obj).addClass('coldrop-hover');
534 * Hide columns' visibility list.
536 hideColList: function () {
538 $(g.cDrop).find('.coldrop-hover').removeClass('coldrop-hover');
542 * Reposition the column visibility drop-down arrow.
544 reposDrop: function () {
545 var $th = $(t).find('th:not(.draggable)');
546 for (var i = 0; i < $th.length; i++) {
547 var $cd = $(g.cDrop).find('div:eq(' + i + ')'); // column drop-down arrow
548 var pos = $($th[i]).position();
550 left: pos.left + $($th[i]).width() - $cd.width(),
557 * Show all hidden columns.
559 showAllColumns: function () {
560 for (var i = 0; i < g.colVisib.length; i++) {
561 if (!g.colVisib[i]) {
569 * Show edit cell, if it can be shown
571 * @param cell <td> element to be edited
573 showEditCell: function (cell) {
574 if ($(cell).is('.grid_edit') &&
575 !g.colRsz && !g.colReorder)
577 if (!g.isCellEditActive) {
580 if ('string' === $cell.attr('data-type') ||
581 'blob' === $cell.attr('data-type')
583 g.cEdit = g.cEditTextarea;
585 g.cEdit = g.cEditStd;
588 // remove all edit area and hide it
589 $(g.cEdit).find('.edit_area').empty().hide();
590 // reposition the cEdit element
592 top: $cell.position().top,
593 left: $cell.position().left
598 width: $cell.outerWidth(),
599 height: $cell.outerHeight()
601 // fill the cell edit with text from <td>
602 var value = PMA_getCellValue(cell);
603 $(g.cEdit).find('.edit_box').val(value);
605 g.currentEditCell = cell;
606 $(g.cEdit).find('.edit_box').focus();
607 moveCursorToEnd($(g.cEdit).find('.edit_box'));
608 $(g.cEdit).find('*').removeProp('disabled');
612 function moveCursorToEnd(input) {
613 var originalValue = input.val();
614 var originallength = originalValue.length;
616 input.blur().focus().val(originalValue);
617 input[0].setSelectionRange(originallength, originallength);
622 * Remove edit cell and the edit area, if it is shown.
624 * @param force Optional, force to hide edit cell without saving edited field.
625 * @param data Optional, data from the POST AJAX request to save the edited field
626 * or just specify "true", if we want to replace the edited field with the new value.
627 * @param field Optional, the edited <td>. If not specified, the function will
628 * use currently edited <td> from g.currentEditCell.
629 * @param field Optional, this object contains a boolean named move (true, if called from move* functions)
630 * and a <td> to which the grid_edit should move
632 hideEditCell: function (force, data, field, options) {
633 if (g.isCellEditActive && !force) {
634 // cell is being edited, save or post the edited data
635 if (options !== undefined) {
636 g.saveOrPostEditedCell(options);
638 g.saveOrPostEditedCell();
643 // cancel any previous request
644 if (g.lastXHR !== null) {
650 if (g.currentEditCell) { // save value of currently edited cell
651 // replace current edited field with the new value
652 var $this_field = $(g.currentEditCell);
653 var is_null = $this_field.data('value') === null;
655 $this_field.find('span').html('NULL');
656 $this_field.addClass('null');
658 $this_field.removeClass('null');
659 var value = data.isNeedToRecheck
660 ? data.truncatableFieldValue
661 : $this_field.data('value');
663 // Truncates the text.
664 $this_field.removeClass('truncated');
665 if (PMA_commonParams.get('pftext') === 'P' && value.length > g.maxTruncatedLen) {
666 $this_field.addClass('truncated');
667 value = value.substring(0, g.maxTruncatedLen) + '...';
670 //Add <br> before carriage return.
671 new_html = escapeHtml(value);
672 new_html = new_html.replace(/\n/g, '<br>\n');
674 //remove decimal places if column type not supported
675 if (($this_field.attr('data-decimals') == 0) && ( $this_field.attr('data-type').indexOf('time') != -1)) {
676 new_html = new_html.substring(0, new_html.indexOf('.'));
679 //remove addtional decimal places
680 if (($this_field.attr('data-decimals') > 0) && ( $this_field.attr('data-type').indexOf('time') != -1)){
681 new_html = new_html.substring(0, new_html.length - (6 - $this_field.attr('data-decimals')));
684 var selector = 'span';
685 if ($this_field.hasClass('hex') && $this_field.find('a').length) {
689 // Updates the code keeping highlighting (if any).
690 var $target = $this_field.find(selector);
691 if (!PMA_updateCode($target, new_html, value)) {
692 $target.html(new_html);
695 if ($this_field.is('.bit')) {
696 $this_field.find('span').text($this_field.data('value'));
699 if (data.transformations !== undefined) {
700 $.each(data.transformations, function (cell_index, value) {
701 var $this_field = $(g.t).find('.to_be_saved:eq(' + cell_index + ')');
702 $this_field.find('span').html(value);
705 if (data.relations !== undefined) {
706 $.each(data.relations, function (cell_index, value) {
707 var $this_field = $(g.t).find('.to_be_saved:eq(' + cell_index + ')');
708 $this_field.find('span').html(value);
717 // hide the cell editing area
719 $(g.cEdit).find('.edit_box').blur();
720 g.isCellEditActive = false;
721 g.currentEditCell = null;
722 // destroy datepicker in edit area, if exist
723 var $dp = $(g.cEdit).find('.hasDatepicker');
724 if ($dp.length > 0) {
725 $(document).bind('mousedown', $.datepicker._checkExternalClick);
726 $dp.datepicker('destroy');
727 // change the cursor in edit box back to normal
728 // (the cursor become a hand pointer when we add datepicker)
729 $(g.cEdit).find('.edit_box').css('cursor', 'inherit');
734 * Show drop-down edit area when edit cell is focused.
736 showEditArea: function () {
737 if (!g.isCellEditActive) { // make sure the edit area has not been shown
738 g.isCellEditActive = true;
739 g.isEditCellTextEditable = false;
741 * @var $td current edited cell
743 var $td = $(g.currentEditCell);
745 * @var $editArea the editing area
747 var $editArea = $(g.cEdit).find('.edit_area');
749 * @var where_clause WHERE clause for the edited cell
751 var where_clause = $td.parent('tr').find('.where_clause').val();
753 * @var field_name String containing the name of this field.
754 * @see getFieldName()
756 var field_name = getFieldName($(t), $td);
758 * @var relation_curr_value String current value of the field (for fields that are foreign keyed).
760 var relation_curr_value = $td.text();
762 * @var relation_key_or_display_column String relational key if in 'Relational display column' mode,
763 * relational display column if in 'Relational key' mode (for fields that are foreign keyed).
765 var relation_key_or_display_column = $td.find('a').attr('title');
767 * @var curr_value String current value of the field (for fields that are of type enum or set).
769 var curr_value = $td.find('span').text();
771 // empty all edit area, then rebuild it based on $td classes
774 // remember this instead of testing more than once
775 var is_null = $td.is('.null');
777 // add goto link, if this cell contains a link
778 if ($td.find('a').length > 0) {
779 var gotoLink = document.createElement('div');
780 gotoLink.className = 'goto_link';
781 $(gotoLink).append(g.gotoLinkText + ' ').append($td.find('a').clone());
782 $editArea.append(gotoLink);
785 g.wasEditedCellNull = false;
786 if ($td.is(':not(.not_null)')) {
787 // append a null checkbox
788 $editArea.append('<div class="null_div">Null:<input type="checkbox"></div>');
790 var $checkbox = $editArea.find('.null_div input');
791 // check if current <td> is NULL
793 $checkbox.prop('checked', true);
794 g.wasEditedCellNull = true;
797 // if the select/editor is changed un-check the 'checkbox_null_<field_name>_<row_index>'.
798 if ($td.is('.enum, .set')) {
799 $editArea.on('change', 'select', function (e) {
800 $checkbox.prop('checked', false);
802 } else if ($td.is('.relation')) {
803 $editArea.on('change', 'select', function (e) {
804 $checkbox.prop('checked', false);
806 $editArea.on('click', '.browse_foreign', function (e) {
807 $checkbox.prop('checked', false);
810 $(g.cEdit).on('keypress change paste', '.edit_box', function (e) {
811 $checkbox.prop('checked', false);
813 // Capture ctrl+v (on IE and Chrome)
814 $(g.cEdit).on('keydown', '.edit_box', function (e) {
815 if (e.ctrlKey && e.which == 86) {
816 $checkbox.prop('checked', false);
819 $editArea.on('keydown', 'textarea', function (e) {
820 $checkbox.prop('checked', false);
824 // if null checkbox is clicked empty the corresponding select/editor.
825 $checkbox.click(function (e) {
826 if ($td.is('.enum')) {
827 $editArea.find('select').val('');
828 } else if ($td.is('.set')) {
829 $editArea.find('select').find('option').each(function () {
830 var $option = $(this);
831 $option.prop('selected', false);
833 } else if ($td.is('.relation')) {
834 // if the dropdown is there to select the foreign value
835 if ($editArea.find('select').length > 0) {
836 $editArea.find('select').val('');
839 $editArea.find('textarea').val('');
841 $(g.cEdit).find('.edit_box').val('');
845 //reset the position of the edit_area div after closing datetime picker
846 $(g.cEdit).find('.edit_area').css({'top' :'0','position':''});
848 if ($td.is('.relation')) {
850 $editArea.addClass('edit_area_loading');
852 // initialize the original data
853 $td.data('original_data', null);
856 * @var post_params Object containing parameters for the POST request
859 'ajax_request' : true,
860 'get_relational_values' : true,
864 'column' : field_name,
866 'curr_value' : relation_curr_value,
867 'relation_key_or_display_column' : relation_key_or_display_column
870 g.lastXHR = $.post('sql.php', post_params, function (data) {
872 $editArea.removeClass('edit_area_loading');
873 if ($(data.dropdown).is('select')) {
874 // save original_data
875 var value = $(data.dropdown).val();
876 $td.data('original_data', value);
877 // update the text input field, in case where the "Relational display column" is checked
878 $(g.cEdit).find('.edit_box').val(value);
881 $editArea.append(data.dropdown);
882 $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
884 // for 'Browse foreign values' options,
885 // hide the value next to 'Browse foreign values' link
886 $editArea.find('span.curr_value').hide();
887 // handle update for new values selected from new window
888 $editArea.find('span.curr_value').change(function () {
889 $(g.cEdit).find('.edit_box').val($(this).text());
894 $editArea.on('change', 'select', function (e) {
895 $(g.cEdit).find('.edit_box').val($(this).val());
897 g.isEditCellTextEditable = true;
899 else if ($td.is('.enum')) {
901 $editArea.addClass('edit_area_loading');
904 * @var post_params Object containing parameters for the POST request
907 'ajax_request' : true,
908 'get_enum_values' : true,
912 'column' : field_name,
914 'curr_value' : curr_value
916 g.lastXHR = $.post('sql.php', post_params, function (data) {
918 $editArea.removeClass('edit_area_loading');
919 $editArea.append(data.dropdown);
920 $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
924 $editArea.on('change', 'select', function (e) {
925 $(g.cEdit).find('.edit_box').val($(this).val());
928 else if ($td.is('.set')) {
930 $editArea.addClass('edit_area_loading');
933 * @var post_params Object containing parameters for the POST request
936 'ajax_request' : true,
937 'get_set_values' : true,
941 'column' : field_name,
943 'curr_value' : curr_value
946 // if the data is truncated, get the full data
947 if ($td.is('.truncated')) {
948 post_params.get_full_values = true;
949 post_params.where_clause = PMA_urldecode(where_clause);
952 g.lastXHR = $.post('sql.php', post_params, function (data) {
954 $editArea.removeClass('edit_area_loading');
955 $editArea.append(data.select);
956 $td.data('original_data', $(data.select).val().join());
957 $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
961 $editArea.on('change', 'select', function (e) {
962 $(g.cEdit).find('.edit_box').val($(this).val());
965 else if ($td.is('.truncated, .transformed')) {
966 if ($td.is('.to_be_saved')) { // cell has been edited
967 var value = $td.data('value');
968 $(g.cEdit).find('.edit_box').val(value);
969 $editArea.append('<textarea></textarea>');
970 $editArea.find('textarea').val(value);
972 .on('keyup', 'textarea', function (e) {
973 $(g.cEdit).find('.edit_box').val($(this).val());
975 $(g.cEdit).on('keyup', '.edit_box', function (e) {
976 $editArea.find('textarea').val($(this).val());
978 $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
980 //handle truncated/transformed values values
981 $editArea.addClass('edit_area_loading');
983 // initialize the original data
984 $td.data('original_data', null);
987 * @var sql_query String containing the SQL query used to retrieve value of truncated/transformed data
989 var sql_query = 'SELECT `' + field_name + '` FROM `' + g.table + '` WHERE ' + PMA_urldecode(where_clause);
991 // Make the Ajax call and get the data, wrap it and insert it
992 g.lastXHR = $.post('sql.php', {
996 'ajax_request' : true,
997 'sql_query' : sql_query,
1001 $editArea.removeClass('edit_area_loading');
1002 if (typeof data !== 'undefined' && data.success === true) {
1003 $td.data('original_data', data.value);
1004 $(g.cEdit).find('.edit_box').val(data.value);
1006 PMA_ajaxShowMessage(data.error, false);
1010 g.isEditCellTextEditable = true;
1011 } else if ($td.is('.timefield, .datefield, .datetimefield, .timestampfield')) {
1012 var $input_field = $(g.cEdit).find('.edit_box');
1014 // remember current datetime value in $input_field, if it is not null
1015 var current_datetime_value = !is_null ? $input_field.val() : '';
1016 var datetime_value = current_datetime_value;
1018 var showMillisec = false;
1019 var showMicrosec = false;
1020 var timeFormat = 'HH:mm:ss';
1021 // check for decimal places of seconds
1022 if (($td.attr('data-decimals') > 0) && ($td.attr('data-type').indexOf('time') != -1)){
1023 if (datetime_value && datetime_value.indexOf('.') === false) {
1024 datetime_value += '.';
1026 if ($td.attr('data-decimals') > 3) {
1027 showMillisec = true;
1028 showMicrosec = true;
1029 timeFormat = 'HH:mm:ss.lc';
1031 if (datetime_value) {
1032 datetime_value += '000000';
1033 var datetime_value = datetime_value.substring(0, datetime_value.indexOf('.') + 7);
1034 $input_field.val(datetime_value);
1037 showMillisec = true;
1038 timeFormat = 'HH:mm:ss.l';
1040 if (datetime_value) {
1041 datetime_value += '000';
1042 var datetime_value = datetime_value.substring(0, datetime_value.indexOf('.') + 4);
1043 $input_field.val(datetime_value);
1048 // add datetime picker
1049 PMA_addDatepicker($input_field, $td.attr('data-type'), {
1050 showMillisec: showMillisec,
1051 showMicrosec: showMicrosec,
1052 timeFormat: timeFormat
1055 $input_field.datepicker("show");
1056 // unbind the mousedown event to prevent the problem of
1057 // datepicker getting closed, needs to be checked for any
1058 // change in names when updating
1059 $(document).unbind('mousedown', $.datepicker._checkExternalClick);
1061 //move ui-datepicker-div inside cEdit div
1062 var datepicker_div = $('#ui-datepicker-div');
1063 datepicker_div.css({'top': 0, 'left': 0, 'position': 'relative'});
1064 $(g.cEdit).append(datepicker_div);
1066 // cancel any click on the datepicker element
1067 $editArea.find('> *').click(function (e) {
1068 e.stopPropagation();
1071 g.isEditCellTextEditable = true;
1073 g.isEditCellTextEditable = true;
1074 // only append edit area hint if there is a null checkbox
1075 if ($editArea.children().length > 0) {
1076 $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
1079 if ($editArea.children().length > 0) {
1086 * Post the content of edited cell.
1088 * @param field Optional, this object contains a boolean named move (true, if called from move* functions)
1089 * and a <td> to which the grid_edit should move
1091 postEditedCell: function (options) {
1097 * @var relation_fields Array containing the name/value pairs of relational fields
1099 var relation_fields = {};
1101 * @var relational_display string 'K' if relational key, 'D' if relational display column
1103 var relational_display = $(g.o).find("input[name=relational_display]:checked").val();
1105 * @var transform_fields Array containing the name/value pairs for transformed fields
1107 var transform_fields = {};
1109 * @var transformation_fields Boolean, if there are any transformed fields in the edited cells
1111 var transformation_fields = false;
1113 * @var full_sql_query String containing the complete SQL query to update this table
1115 var full_sql_query = '';
1117 * @var rel_fields_list String, url encoded representation of {@link relations_fields}
1119 var rel_fields_list = '';
1121 * @var transform_fields_list String, url encoded representation of {@link transform_fields}
1123 var transform_fields_list = '';
1125 * @var where_clause Array containing where clause for updated fields
1127 var full_where_clause = [];
1129 * @var is_unique Boolean, whether the rows in this table is unique or not
1131 var is_unique = $(g.t).find('td.edit_row_anchor').is('.nonunique') ? 0 : 1;
1133 * multi edit variables
1135 var me_fields_name = [];
1136 var me_fields_type = [];
1138 var me_fields_null = [];
1140 // alert user if edited table is not unique
1142 alert(g.alertNonUnique);
1145 // loop each edited row
1146 $(g.t).find('td.to_be_saved').parents('tr').each(function () {
1148 var where_clause = $tr.find('.where_clause').val();
1149 if (typeof where_clause === 'undefined') {
1152 full_where_clause.push(PMA_urldecode(where_clause));
1153 var condition_array = jQuery.parseJSON($tr.find('.condition_array').val());
1156 * multi edit variables, for current row
1157 * @TODO array indices are still not correct, they should be md5 of field's name
1159 var fields_name = [];
1160 var fields_type = [];
1162 var fields_null = [];
1164 // loop each edited cell in a row
1165 $tr.find('.to_be_saved').each(function () {
1167 * @var $this_field Object referring to the td that is being edited
1169 var $this_field = $(this);
1172 * @var field_name String containing the name of this field.
1173 * @see getFieldName()
1175 var field_name = getFieldName($(g.t), $this_field);
1178 * @var this_field_params Array temporary storage for the name/value of current field
1180 var this_field_params = {};
1182 if ($this_field.is('.transformed')) {
1183 transformation_fields = true;
1185 this_field_params[field_name] = $this_field.data('value');
1188 * @var is_null String capturing whether 'checkbox_null_<field_name>_<row_index>' is checked.
1190 var is_null = this_field_params[field_name] === null;
1192 fields_name.push(field_name);
1195 fields_null.push('on');
1198 if ($this_field.is('.bit')) {
1199 fields_type.push('bit');
1200 } else if ($this_field.hasClass('hex')) {
1201 fields_type.push('hex');
1203 fields_null.push('');
1204 fields.push($this_field.data('value'));
1206 var cell_index = $this_field.index('.to_be_saved');
1207 if ($this_field.is(":not(.relation, .enum, .set, .bit)")) {
1208 if ($this_field.is('.transformed')) {
1209 transform_fields[cell_index] = {};
1210 $.extend(transform_fields[cell_index], this_field_params);
1212 } else if ($this_field.is('.relation')) {
1213 relation_fields[cell_index] = {};
1214 $.extend(relation_fields[cell_index], this_field_params);
1217 // check if edited field appears in WHERE clause
1218 if (where_clause.indexOf(PMA_urlencode(field_name)) > -1) {
1219 var field_str = '`' + g.table + '`.' + '`' + field_name + '`';
1220 for (var field in condition_array) {
1221 if (field.indexOf(field_str) > -1) {
1222 condition_array[field] = is_null ? 'IS NULL' : "= '" + this_field_params[field_name].replace(/'/g, "''") + "'";
1228 }); // end of loop for every edited cells in a row
1231 var new_clause = '';
1232 for (var field in condition_array) {
1233 new_clause += field + ' ' + condition_array[field] + ' AND ';
1235 new_clause = new_clause.substring(0, new_clause.length - 5); // remove the last AND
1236 new_clause = PMA_urlencode(new_clause);
1237 $tr.data('new_clause', new_clause);
1238 // save condition_array
1239 $tr.find('.condition_array').val(JSON.stringify(condition_array));
1241 me_fields_name.push(fields_name);
1242 me_fields_type.push(fields_type);
1243 me_fields.push(fields);
1244 me_fields_null.push(fields_null);
1246 }); // end of loop for every edited rows
1248 rel_fields_list = $.param(relation_fields);
1249 transform_fields_list = $.param(transform_fields);
1251 // Make the Ajax post after setting all parameters
1253 * @var post_params Object containing parameters for the POST request
1255 var post_params = {'ajax_request' : true,
1256 'sql_query' : full_sql_query,
1258 'server' : g.server,
1261 'clause_is_unique' : is_unique,
1262 'where_clause' : full_where_clause,
1263 'fields[multi_edit]' : me_fields,
1264 'fields_name[multi_edit]' : me_fields_name,
1265 'fields_type[multi_edit]' : me_fields_type,
1266 'fields_null[multi_edit]' : me_fields_null,
1267 'rel_fields_list' : rel_fields_list,
1268 'do_transformations' : transformation_fields,
1269 'transform_fields_list' : transform_fields_list,
1270 'relational_display' : relational_display,
1272 'submit_type' : 'save'
1275 if (!g.saveCellsAtOnce) {
1276 $(g.cEdit).find('*').prop('disabled', true);
1277 $(g.cEdit).find('.edit_box').addClass('edit_box_posting');
1279 $(g.o).find('div.save_edited').addClass('saving_edited_data')
1280 .find('input').prop('disabled', true); // disable the save button
1285 url: 'tbl_replace.php',
1290 if (!g.saveCellsAtOnce) {
1291 $(g.cEdit).find('*').removeProp('disabled');
1292 $(g.cEdit).find('.edit_box').removeClass('edit_box_posting');
1294 $(g.o).find('div.save_edited').removeClass('saving_edited_data')
1295 .find('input').removeProp('disabled'); // enable the save button back
1297 if (typeof data !== 'undefined' && data.success === true) {
1298 if (typeof options === 'undefined' || ! options.move) {
1299 PMA_ajaxShowMessage(data.message);
1302 // update where_clause related data in each edited row
1303 $(g.t).find('td.to_be_saved').parents('tr').each(function () {
1304 var new_clause = $(this).data('new_clause');
1305 var $where_clause = $(this).find('.where_clause');
1306 var old_clause = $where_clause.val();
1307 var decoded_old_clause = PMA_urldecode(old_clause);
1308 var decoded_new_clause = PMA_urldecode(new_clause);
1310 $where_clause.val(new_clause);
1311 // update Edit, Copy, and Delete links also
1312 $(this).find('a').each(function () {
1313 $(this).attr('href', $(this).attr('href').replace(old_clause, new_clause));
1314 // update delete confirmation in Delete link
1315 if ($(this).attr('href').indexOf('DELETE') > -1) {
1316 $(this).removeAttr('onclick')
1318 .bind('click', function () {
1319 return confirmLink(this, 'DELETE FROM `' + g.db + '`.`' + g.table + '` WHERE ' +
1320 decoded_new_clause + (is_unique ? '' : ' LIMIT 1'));
1324 // update the multi edit checkboxes
1325 $(this).find('input[type=checkbox]').each(function () {
1326 var $checkbox = $(this);
1327 var checkbox_name = $checkbox.attr('name');
1328 var checkbox_value = $checkbox.val();
1330 $checkbox.attr('name', checkbox_name.replace(old_clause, new_clause));
1331 $checkbox.val(checkbox_value.replace(decoded_old_clause, decoded_new_clause));
1334 // update the display of executed SQL query command
1335 if (typeof data.sql_query != 'undefined') {
1337 var $result_query = $($.parseHTML(data.sql_query));
1338 var sqlOuter = $result_query.find('.sqlOuter').wrap('<p>').parent().html();
1339 var tools = $result_query.find('.tools').wrap('<p>').parent().html();
1340 // sqlOuter and tools will not be present if 'Show SQL queries' configuration is off
1341 if (typeof sqlOuter != 'undefined' && typeof tools != 'undefined') {
1342 var $existing_query = $(g.o).find('.result_query');
1343 // If two query box exists update query in second else add a second box
1344 if ($existing_query.find('div.sqlOuter').length > 1) {
1345 $existing_query.children(":nth-child(4)").remove();
1346 $existing_query.children(":nth-child(4)").remove();
1347 $existing_query.append(sqlOuter + tools);
1349 $existing_query.append(sqlOuter + tools);
1351 PMA_highlightSQL($existing_query);
1354 // hide and/or update the successfully saved cells
1355 g.hideEditCell(true, data);
1357 // remove the "Save edited cells" button
1358 $(g.o).find('div.save_edited').hide();
1359 // update saved fields
1360 $(g.t).find('.to_be_saved')
1361 .removeClass('to_be_saved')
1362 .data('value', null)
1363 .data('original_data', null);
1365 g.isCellEdited = false;
1367 PMA_ajaxShowMessage(data.error, false);
1368 if (!g.saveCellsAtOnce) {
1369 $(g.t).find('.to_be_saved')
1370 .removeClass('to_be_saved');
1375 if (options !== undefined && options.move) {
1376 g.showEditCell(options.cell);
1382 * Save edited cell, so it can be posted later.
1384 saveEditedCell: function () {
1386 * @var $this_field Object referring to the td that is being edited
1388 var $this_field = $(g.currentEditCell);
1389 var $test_element = ''; // to test the presence of a element
1391 var need_to_post = false;
1394 * @var field_name String containing the name of this field.
1395 * @see getFieldName()
1397 var field_name = getFieldName($(g.t), $this_field);
1400 * @var this_field_params Array temporary storage for the name/value of current field
1402 var this_field_params = {};
1405 * @var is_null String capturing whether 'checkbox_null_<field_name>_<row_index>' is checked.
1407 var is_null = $(g.cEdit).find('input:checkbox').is(':checked');
1410 if ($(g.cEdit).find('.edit_area').is('.edit_area_loading')) {
1411 // the edit area is still loading (retrieving cell data), no need to post
1412 need_to_post = false;
1413 } else if (is_null) {
1414 if (!g.wasEditedCellNull) {
1415 this_field_params[field_name] = null;
1416 need_to_post = true;
1419 if ($this_field.is('.bit')) {
1420 this_field_params[field_name] = $(g.cEdit).find('.edit_box').val();
1421 } else if ($this_field.is('.set')) {
1422 $test_element = $(g.cEdit).find('select');
1423 this_field_params[field_name] = $test_element.map(function () {
1424 return $(this).val();
1426 } else if ($this_field.is('.relation, .enum')) {
1427 // for relation and enumeration, take the results from edit box value,
1428 // because selected value from drop-down, new window or multiple
1429 // selection list will always be updated to the edit box
1430 this_field_params[field_name] = $(g.cEdit).find('.edit_box').val();
1431 } else if ($this_field.hasClass('hex')) {
1432 if ($(g.cEdit).find('.edit_box').val().match(/^[a-f0-9]*$/i) !== null) {
1433 this_field_params[field_name] = $(g.cEdit).find('.edit_box').val();
1435 var hexError = '<div class="error">' + PMA_messages.strEnterValidHex + '</div>';
1436 PMA_ajaxShowMessage(hexError, false);
1437 this_field_params[field_name] = PMA_getCellValue(g.currentEditCell);
1440 this_field_params[field_name] = $(g.cEdit).find('.edit_box').val();
1442 if (g.wasEditedCellNull || this_field_params[field_name] != PMA_getCellValue(g.currentEditCell)) {
1443 need_to_post = true;
1448 $(g.currentEditCell).addClass('to_be_saved')
1449 .data('value', this_field_params[field_name]);
1450 if (g.saveCellsAtOnce) {
1451 $(g.o).find('div.save_edited').show();
1453 g.isCellEdited = true;
1456 return need_to_post;
1460 * Save or post currently edited cell, depending on the "saveCellsAtOnce" configuration.
1462 * @param field Optional, this object contains a boolean named move (true, if called from move* functions)
1463 * and a <td> to which the grid_edit should move
1465 saveOrPostEditedCell: function (options) {
1466 var saved = g.saveEditedCell();
1467 // Check if $cfg['SaveCellsAtOnce'] is false
1468 if (!g.saveCellsAtOnce) {
1469 // Check if need_to_post is true
1471 // Check if this function called from 'move' functions
1472 if (options !== undefined && options.move) {
1473 g.postEditedCell(options);
1477 // need_to_post is false
1479 // Check if this function called from 'move' functions
1480 if (options !== undefined && options.move) {
1481 g.hideEditCell(true);
1482 g.showEditCell(options.cell);
1483 // NOT called from 'move' functions
1485 g.hideEditCell(true);
1488 // $cfg['SaveCellsAtOnce'] is true
1492 // If this function called from 'move' functions
1493 if (options !== undefined && options.move) {
1494 g.hideEditCell(true, true, false, options);
1495 g.showEditCell(options.cell);
1496 // NOT called from 'move' functions
1498 g.hideEditCell(true, true);
1501 // If this function called from 'move' functions
1502 if (options !== undefined && options.move) {
1503 g.hideEditCell(true, false, false, options);
1504 g.showEditCell(options.cell);
1505 // NOT called from 'move' functions
1507 g.hideEditCell(true);
1514 * Initialize column resize feature.
1516 initColResize: function () {
1517 // create column resizer div
1518 g.cRsz = document.createElement('div');
1519 g.cRsz.className = 'cRsz';
1521 // get data columns in the first row of the table
1522 var $firstRowCols = $(g.t).find('tr:first th.draggable');
1524 // create column borders
1525 $firstRowCols.each(function () {
1526 var cb = document.createElement('div'); // column border
1527 $(cb).addClass('colborder')
1528 .mousedown(function (e) {
1529 g.dragStartRsz(e, this);
1531 $(g.cRsz).append(cb);
1535 // attach to global div
1536 $(g.gDiv).prepend(g.cRsz);
1540 * Initialize column reordering feature.
1542 initColReorder: function () {
1543 g.cCpy = document.createElement('div'); // column copy, to store copy of dragged column header
1544 g.cPointer = document.createElement('div'); // column pointer, used when reordering column
1547 g.cCpy.className = 'cCpy';
1550 // adjust g.cPointer
1551 g.cPointer.className = 'cPointer';
1552 $(g.cPointer).css('visibility', 'hidden'); // set visibility to hidden instead of calling hide() to force browsers to cache the image in cPointer class
1554 // assign column reordering hint
1555 g.reorderHint = PMA_messages.strColOrderHint;
1557 // get data columns in the first row of the table
1558 var $firstRowCols = $(g.t).find('tr:first th.draggable');
1560 // initialize column order
1561 $col_order = $(g.o).find('.col_order'); // check if column order is passed from PHP
1562 if ($col_order.length > 0) {
1563 g.colOrder = $col_order.val().split(',');
1564 for (var i = 0; i < g.colOrder.length; i++) {
1565 g.colOrder[i] = parseInt(g.colOrder[i], 10);
1569 for (var i = 0; i < $firstRowCols.length; i++) {
1575 $(g.t).find('th.draggable')
1576 .mousedown(function (e) {
1577 $(g.o).addClass("turnOffSelect");
1578 if (g.visibleHeadersCount > 1) {
1579 g.dragStartReorder(e, this);
1582 .mouseenter(function (e) {
1583 if (g.visibleHeadersCount > 1) {
1584 $(this).css('cursor', 'move');
1586 $(this).css('cursor', 'inherit');
1589 .mouseleave(function (e) {
1590 g.showReorderHint = false;
1591 $(this).tooltip("option", {
1592 content: g.updateHint()
1595 .dblclick(function (e) {
1598 .prop("title", PMA_messages.strColNameCopyTitle)
1599 .addClass("modal-copy")
1600 .text(PMA_messages.strColNameCopyText)
1603 .prop("readonly", true)
1604 .val($(this).data("column"))
1610 .find("input").focus().select();
1612 $(g.t).find('th.draggable a')
1613 .dblclick(function (e) {
1614 e.stopPropagation();
1616 // restore column order when the restore button is clicked
1617 $(g.o).find('div.restore_column').click(function () {
1618 g.restoreColOrder();
1621 // attach to global div
1622 $(g.gDiv).append(g.cPointer);
1623 $(g.gDiv).append(g.cCpy);
1625 // prevent default "dragstart" event when dragging a link
1626 $(g.t).find('th a').bind('dragstart', function () {
1630 // refresh the restore column button state
1631 g.refreshRestoreButton();
1635 * Initialize column visibility feature.
1637 initColVisib: function () {
1638 g.cDrop = document.createElement('div'); // column drop-down arrows
1639 g.cList = document.createElement('div'); // column visibility list
1642 g.cDrop.className = 'cDrop';
1645 g.cList.className = 'cList';
1648 // assign column visibility related hints
1649 g.showAllColText = PMA_messages.strShowAllCol;
1651 // get data columns in the first row of the table
1652 var $firstRowCols = $(g.t).find('tr:first th.draggable');
1655 // initialize column visibility
1656 var $col_visib = $(g.o).find('.col_visib'); // check if column visibility is passed from PHP
1657 if ($col_visib.length > 0) {
1658 g.colVisib = $col_visib.val().split(',');
1659 for (i = 0; i < g.colVisib.length; i++) {
1660 g.colVisib[i] = parseInt(g.colVisib[i], 10);
1664 for (i = 0; i < $firstRowCols.length; i++) {
1669 // make sure we have more than one column
1670 if ($firstRowCols.length > 1) {
1671 var $colVisibTh = $(g.t).find('th:not(.draggable)');
1675 PMA_messages.strColVisibHint
1678 // create column visibility drop-down arrow(s)
1679 $colVisibTh.each(function () {
1681 var cd = document.createElement('div'); // column drop-down arrow
1682 var pos = $th.position();
1683 $(cd).addClass('coldrop')
1684 .click(function () {
1685 if (g.cList.style.display == 'none') {
1686 g.showColList(this);
1691 $(g.cDrop).append(cd);
1694 // add column visibility control
1695 g.cList.innerHTML = '<div class="lDiv"></div>';
1696 var $listDiv = $(g.cList).find('div');
1698 var tempClick = function () {
1699 if (g.toggleCol($(this).index())) {
1704 for (i = 0; i < $firstRowCols.length; i++) {
1705 var currHeader = $firstRowCols[i];
1706 var listElmt = document.createElement('div');
1707 $(listElmt).text($(currHeader).text())
1708 .prepend('<input type="checkbox" ' + (g.colVisib[i] ? 'checked="checked" ' : '') + '/>');
1709 $listDiv.append(listElmt);
1710 // add event on click
1711 $(listElmt).click(tempClick);
1713 // add "show all column" button
1714 var showAll = document.createElement('div');
1715 $(showAll).addClass('showAllColBtn')
1716 .text(g.showAllColText);
1717 $(g.cList).append(showAll);
1718 $(showAll).click(function () {
1721 // prepend "show all column" button at top if the list is too long
1722 if ($firstRowCols.length > 10) {
1723 var clone = showAll.cloneNode(true);
1724 $(g.cList).prepend(clone);
1725 $(clone).click(function () {
1731 // hide column visibility list if we move outside the list
1732 $(g.t).find('td, th.draggable').mouseenter(function () {
1736 // attach to global div
1737 $(g.gDiv).append(g.cDrop);
1738 $(g.gDiv).append(g.cList);
1745 * Move currently Editing Cell to Up
1747 moveUp: function(e) {
1749 var $this_field = $(g.currentEditCell);
1750 var field_name = getFieldName($(g.t), $this_field);
1752 var where_clause = $this_field.parents('tr').first().find('.where_clause').val();
1753 if (typeof where_clause === 'undefined') {
1756 where_clause = PMA_urldecode(where_clause);
1762 $this_field.parents('tr').first().parents('tbody').children().each(function(){
1763 if (PMA_urldecode($(this).find('.where_clause').val()) == where_clause) {
1765 $found_row = $(this);
1768 $prev_row = $(this);
1774 if (found && $prev_row) {
1775 $prev_row.children('td').each(function(){
1776 if (getFieldName($(g.t), $(this)) == field_name) {
1783 g.hideEditCell(false, false, false, {move : true, cell : new_cell});
1788 * Move currently Editing Cell to Down
1790 moveDown: function(e) {
1793 var $this_field = $(g.currentEditCell);
1794 var field_name = getFieldName($(g.t), $this_field);
1796 var where_clause = $this_field.parents('tr').first().find('.where_clause').val();
1797 if (typeof where_clause === 'undefined') {
1800 where_clause = PMA_urldecode(where_clause);
1805 var next_row_found = false;
1806 $this_field.parents('tr').first().parents('tbody').children().each(function(){
1807 if (PMA_urldecode($(this).find('.where_clause').val()) == where_clause) {
1809 $found_row = $(this);
1812 if (j >= 1 && ! next_row_found) {
1813 $next_row = $(this);
1814 next_row_found = true;
1822 if (found && $next_row) {
1823 $next_row.children('td').each(function(){
1824 if (getFieldName($(g.t), $(this)) == field_name) {
1831 g.hideEditCell(false, false, false, {move : true, cell : new_cell});
1836 * Move currently Editing Cell to Left
1838 moveLeft: function(e) {
1841 var $this_field = $(g.currentEditCell);
1842 var field_name = getFieldName($(g.t), $this_field);
1844 var where_clause = $this_field.parents('tr').first().find('.where_clause').val();
1845 if (typeof where_clause === 'undefined') {
1848 where_clause = PMA_urldecode(where_clause);
1852 $this_field.parents('tr').first().parents('tbody').children().each(function(){
1853 if (PMA_urldecode($(this).find('.where_clause').val()) == where_clause) {
1855 $found_row = $(this);
1860 var cell_found = false;
1862 $found_row.children('td.grid_edit').each(function(){
1863 if (getFieldName($(g.t), $(this)) === field_name) {
1873 g.hideEditCell(false, false, false, {move : true, cell : left_cell});
1878 * Move currently Editing Cell to Right
1880 moveRight: function(e) {
1883 var $this_field = $(g.currentEditCell);
1884 var field_name = getFieldName($(g.t), $this_field);
1886 var where_clause = $this_field.parents('tr').first().find('.where_clause').val();
1887 if (typeof where_clause === 'undefined') {
1890 where_clause = PMA_urldecode(where_clause);
1894 $this_field.parents('tr').first().parents('tbody').children().each(function(){
1895 if (PMA_urldecode($(this).find('.where_clause').val()) == where_clause) {
1897 $found_row = $(this);
1902 var cell_found = false;
1903 var next_cell_found = false;
1905 $found_row.children('td.grid_edit').each(function(){
1906 if (getFieldName($(g.t), $(this)) === field_name) {
1910 if (j >= 1 && ! next_cell_found) {
1912 next_cell_found = true;
1921 g.hideEditCell(false, false, false, {move : true, cell : right_cell});
1926 * Initialize grid editing feature.
1928 initGridEdit: function () {
1930 function startGridEditing(e, cell) {
1931 if (g.isCellEditActive) {
1932 g.saveOrPostEditedCell();
1934 g.showEditCell(cell);
1936 e.stopPropagation();
1939 function handleCtrlNavigation(e) {
1940 if ((e.ctrlKey && e.which == 38 ) || (e.altKey && e.which == 38)) {
1942 } else if ((e.ctrlKey && e.which == 40) || (e.altKey && e.which == 40)) {
1944 } else if ((e.ctrlKey && e.which == 37 ) || (e.altKey && e.which == 37)) {
1946 } else if ((e.ctrlKey && e.which == 39) || (e.altKey && e.which == 39)) {
1951 // create cell edit wrapper element
1952 g.cEditStd = document.createElement('div');
1953 g.cEdit = g.cEditStd;
1954 g.cEditTextarea = document.createElement('div');
1956 // adjust g.cEditStd
1957 g.cEditStd.className = 'cEdit';
1958 $(g.cEditStd).html('<input class="edit_box" rows="1" ></input><div class="edit_area" />');
1959 $(g.cEditStd).hide();
1962 g.cEditTextarea.className = 'cEdit';
1963 $(g.cEditTextarea).html('<textarea class="edit_box" rows="1" ></textarea><div class="edit_area" />');
1964 $(g.cEditTextarea).hide();
1966 // assign cell editing hint
1967 g.cellEditHint = PMA_messages.strCellEditHint;
1968 g.saveCellWarning = PMA_messages.strSaveCellWarning;
1969 g.alertNonUnique = PMA_messages.strAlertNonUnique;
1970 g.gotoLinkText = PMA_messages.strGoToLink;
1972 // initialize cell editing configuration
1973 g.saveCellsAtOnce = $(g.o).find('.save_cells_at_once').val();
1974 g.maxTruncatedLen = PMA_commonParams.get('LimitChars');
1977 $(g.t).find('td.data.click1')
1978 .click(function (e) {
1979 startGridEditing(e, this);
1980 // prevent default action when clicking on "link" in a table
1981 if ($(e.target).is('.grid_edit a')) {
1986 $(g.t).find('td.data.click2')
1987 .click(function (e) {
1988 var $cell = $(this);
1989 // In the case of relational link, We want single click on the link
1990 // to goto the link and double click to start grid-editing.
1991 var $link = $(e.target);
1992 if ($link.is('.grid_edit.relation a')) {
1994 // get the click count and increase
1995 var clicks = $cell.data('clicks');
1996 clicks = (typeof clicks === 'undefined') ? 1 : clicks + 1;
1999 // if there are no previous clicks,
2000 // start the single click timer
2001 var timer = setTimeout(function () {
2002 // temporarily remove ajax class so the page loader will not handle it,
2003 // submit and then add it back
2004 $link.removeClass('ajax');
2005 AJAX.requestHandler.call($link[0]);
2006 $link.addClass('ajax');
2007 $cell.data('clicks', 0);
2009 $cell.data('clicks', clicks);
2010 $cell.data('timer', timer);
2012 // this is a double click, cancel the single click timer
2013 // and make the click count 0
2014 clearTimeout($cell.data('timer'));
2015 $cell.data('clicks', 0);
2016 // start grid-editing
2017 startGridEditing(e, this);
2021 .dblclick(function (e) {
2022 if ($(e.target).is('.grid_edit a')) {
2025 startGridEditing(e, this);
2029 $(g.cEditStd).on('keydown', 'input.edit_box, select', handleCtrlNavigation);
2031 $(g.cEditStd).find('.edit_box').focus(function (e) {
2034 $(g.cEditStd).on('keydown', '.edit_box, select', function (e) {
2035 if (e.which == 13) {
2036 // post on pressing "Enter"
2038 g.saveOrPostEditedCell();
2041 $(g.cEditStd).keydown(function (e) {
2042 if (!g.isEditCellTextEditable) {
2043 // prevent text editing
2048 $(g.cEditTextarea).on('keydown', 'textarea.edit_box, select', handleCtrlNavigation);
2050 $(g.cEditTextarea).find('.edit_box').focus(function (e) {
2053 $(g.cEditTextarea).on('keydown', '.edit_box, select', function (e) {
2054 if (e.which == 13 && !e.shiftKey) {
2055 // post on pressing "Enter"
2057 g.saveOrPostEditedCell();
2060 $(g.cEditTextarea).keydown(function (e) {
2061 if (!g.isEditCellTextEditable) {
2062 // prevent text editing
2066 $('html').click(function (e) {
2067 // hide edit cell if the click is not fromDat edit area
2068 if ($(e.target).parents().index($(g.cEdit)) == -1 &&
2069 !$(e.target).parents('.ui-datepicker-header').length &&
2070 !$('.browse_foreign_modal.ui-dialog:visible').length
2074 }).keydown(function (e) {
2075 if (e.which == 27 && g.isCellEditActive) {
2077 // cancel on pressing "Esc"
2078 g.hideEditCell(true);
2081 $(g.o).find('div.save_edited').click(function () {
2085 $(window).bind('beforeunload', function (e) {
2086 if (g.isCellEdited) {
2087 return g.saveCellWarning;
2091 // attach to global div
2092 $(g.gDiv).append(g.cEditStd);
2093 $(g.gDiv).append(g.cEditTextarea);
2095 // add hint for grid editing feature when hovering "Edit" link in each table row
2096 if (PMA_messages.strGridEditFeatureHint !== undefined) {
2098 $(g.t).find('.edit_row_anchor a'),
2100 PMA_messages.strGridEditFeatureHint
2110 // wrap all truncated data cells with span indicating the original length
2111 // todo update the original length after a grid edit
2112 $(t).find('td.data.truncated:not(:has(span))')
2113 .wrapInner(function() {
2114 return '<span title="' + PMA_messages.strOriginalLength + ' ' +
2115 $(this).data('originallength') + '"></span>';
2118 // wrap remaining cells, except actions cell, with span
2119 $(t).find('th, td:not(:has(span))')
2120 .wrapInner('<span />');
2122 // create grid elements
2123 g.gDiv = document.createElement('div'); // create global div
2125 // initialize the table variable
2128 // enclosing .sqlqueryresults div
2129 g.o = $(t).parents('.sqlqueryresults');
2131 // get data columns in the first row of the table
2132 var $firstRowCols = $(t).find('tr:first th.draggable');
2134 // initialize visible headers count
2135 g.visibleHeadersCount = $firstRowCols.filter(':visible').length;
2137 // assign first column (actions) span
2138 if (! $(t).find('tr:first th:first').hasClass('draggable')) { // action header exist
2139 g.actionSpan = $(t).find('tr:first th:first').prop('colspan');
2144 // assign table create time
2145 // table_create_time will only available if we are in "Browse" tab
2146 g.tableCreateTime = $(g.o).find('.table_create_time').val();
2149 g.sortHint = PMA_messages.strSortHint;
2150 g.strMultiSortHint = PMA_messages.strMultiSortHint;
2151 g.markHint = PMA_messages.strColMarkHint;
2152 g.copyHint = PMA_messages.strColNameCopyHint;
2154 // assign common hidden inputs
2155 var $common_hidden_inputs = $(g.o).find('div.common_hidden_inputs');
2156 g.token = $common_hidden_inputs.find('input[name=token]').val();
2157 g.server = $common_hidden_inputs.find('input[name=server]').val();
2158 g.db = $common_hidden_inputs.find('input[name=db]').val();
2159 g.table = $common_hidden_inputs.find('input[name=table]').val();
2162 $(t).addClass('pma_table');
2164 // add relative position to global div so that resize handlers are correctly positioned
2165 $(g.gDiv).css('position', 'relative');
2167 // link the global div
2168 $(t).before(g.gDiv);
2169 $(g.gDiv).append(t);
2172 enableResize = enableResize === undefined ? true : enableResize;
2173 enableReorder = enableReorder === undefined ? true : enableReorder;
2174 enableVisib = enableVisib === undefined ? true : enableVisib;
2175 enableGridEdit = enableGridEdit === undefined ? true : enableGridEdit;
2179 if (enableReorder &&
2180 $(g.o).find('table.navigation').length > 0) // disable reordering for result from EXPLAIN or SHOW syntax, which do not have a table navigation panel
2187 if (enableGridEdit &&
2188 $(t).is('.ajax')) // make sure we have the ajax class
2193 // create tooltip for each <th> with draggable class
2195 $(t).find("th.draggable"),
2200 // register events for hint tooltip (anchors inside draggable th)
2201 $(t).find('th.draggable a')
2202 .mouseenter(function (e) {
2203 g.showSortHint = true;
2204 g.showMultiSortHint = true;
2205 $(t).find("th.draggable").tooltip("option", {
2206 content: g.updateHint()
2209 .mouseleave(function (e) {
2210 g.showSortHint = false;
2211 g.showMultiSortHint = false;
2212 $(t).find("th.draggable").tooltip("option", {
2213 content: g.updateHint()
2217 // register events for dragging-related feature
2218 if (enableResize || enableReorder) {
2219 $(document).mousemove(function (e) {
2222 $(document).mouseup(function (e) {
2223 $(g.o).removeClass("turnOffSelect");
2229 $(t).removeClass('data');
2230 $(g.gDiv).addClass('data');