2 * Create advanced table (resize, reorder, and show/hide columns; and also grid editing).
3 * This function is designed mainly for table DOM generated from browsing a table in the database.
4 * For using this function in other table DOM, you may need to:
5 * - add "draggable" class in the table header <th>, in order to make it resizable, sortable or hidable
6 * - have at least one non-"draggable" header in the table DOM for placing column visibility drop-down arrow
7 * - pass the value "false" for the parameter "enableGridEdit"
8 * - adjust other parameter value, to select which features that will be enabled
10 * @param t the table DOM element
11 * @param enableResize Optional, if false, column resizing feature will be disabled
12 * @param enableReorder Optional, if false, column reordering feature will be disabled
13 * @param enableVisib Optional, if false, show/hide column feature will be disabled
14 * @param enableGridEdit Optional, if false, grid editing feature will be disabled
16 function PMA_makegrid(t, enableResize, enableReorder, enableVisib, enableGridEdit) {
25 * Variables, assigned with default value, changed later
27 actionSpan: 5, // number of colspan in Actions header in a table
28 tableCreateTime: null, // table creation time, used for saving column order and visibility to server, only available in "Browse tab"
30 // Column reordering variables
31 colOrder: new Array(), // array of column order
33 // Column visibility variables
34 colVisib: new Array(), // array of column visibility
35 showAllColText: '', // string, text for "show all" button under column visibility list
36 visibleHeadersCount: 0, // number of visible data headers
38 // Table hint variables
39 qtip: null, // qtip API
40 reorderHint: '', // string, hint for column reordering
41 sortHint: '', // string, hint for column sorting
42 markHint: '', // string, hint for column marking
43 colVisibHint: '', // string, hint for column visibility drop-down
44 showReorderHint: false,
47 showColVisibHint: false,
50 isCellEditActive: false, // true if current focus is in edit cell
51 isEditCellTextEditable: false, // true if current edit cell is editable in the text input box (not textarea)
52 currentEditCell: null, // reference to <td> that currently being edited
53 cellEditHint: '', // hint shown when doing grid edit
54 gotoLinkText: '', // "Go to link" text
55 wasEditedCellNull: false, // true if last value of the edited cell was NULL
56 maxTruncatedLen: 0, // number of characters that can be displayed in a cell
57 saveCellsAtOnce: false, // $cfg[saveCellsAtOnce]
58 isCellEdited: false, // true if at least one cell has been edited
59 saveCellWarning: '', // string, warning text when user want to leave a page with unsaved edited data
60 lastXHR : null, // last XHR object used in AJAX request
61 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
62 alertNonUnique: '', // string, alert shown when saving edited nonunique table
64 // Common hidden inputs
76 * Start to resize column. Called when clicking on column separator.
79 * @param obj dragged div object
81 dragStartRsz: function(e, obj) {
82 var n = $(g.cRsz).find('div').index(obj); // get the index of separator (i.e., column index)
87 objLeft: $(obj).position().left,
88 objWidth: $(g.t).find('th.draggable:visible:eq(' + n + ') span').outerWidth()
90 $('body').css('cursor', 'col-resize');
92 if (g.isCellEditActive) {
98 * Start to reorder column. Called when clicking on table header.
101 * @param obj table header object
103 dragStartReorder: function(e, obj) {
104 // prepare the cCpy (column copy) and cPointer (column pointer) from the dragged column
105 $(g.cCpy).text($(obj).text());
106 var objPos = $(obj).position();
108 top: objPos.top + 20,
110 height: $(obj).height(),
111 width: $(obj).width()
117 // get the column index, zero-based
118 var n = g.getHeaderIdx(obj);
130 $('body').css('cursor', 'move');
131 $('body').noSelect();
132 if (g.isCellEditActive) {
138 * Handle mousemove event when dragging.
142 dragMove: function(e) {
144 var dx = e.pageX - g.colRsz.x0;
145 if (g.colRsz.objWidth + dx > g.minColWidth) {
146 $(g.colRsz.obj).css('left', g.colRsz.objLeft + dx + 'px');
148 } else if (g.colReorder) {
149 // dragged column animation
150 var dx = e.pageX - g.colReorder.x0;
152 .css('left', g.colReorder.objLeft + dx)
156 var hoveredCol = g.getHoveredCol(e);
158 var newn = g.getHeaderIdx(hoveredCol);
159 g.colReorder.newn = newn;
160 if (newn != g.colReorder.n) {
161 // show the column pointer in the right place
162 var colPos = $(hoveredCol).position();
163 var newleft = newn < g.colReorder.n ?
165 colPos.left + $(hoveredCol).outerWidth();
169 visibility: 'visible'
172 // no movement to other column, hide the column pointer
173 $(g.cPointer).css('visibility', 'hidden');
180 * Stop the dragging action.
184 dragEnd: function(e) {
186 var dx = e.pageX - g.colRsz.x0;
187 var nw = g.colRsz.objWidth + dx;
188 if (nw < g.minColWidth) {
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;
225 $('body').css('cursor', 'inherit');
226 $('body').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 $('.pma_table').find('thead th:first').removeClass('before-condition');
251 for (var n = 0; n < $firstRowCols.length; n++) {
252 var $col = $($firstRowCols[n]);
253 $($resizeHandles[n]).css('left', $col.position().left + $col.outerWidth(true))
255 if ($($firstRowCols[n]).hasClass('condition')) {
256 $($resizeHandles[n]).addClass('condition');
258 $($resizeHandles[n-1]).addClass('condition');
262 if ($($resizeHandles[0]).hasClass('condition')) {
263 $('.pma_table').find('thead th:first').addClass('before-condition');
265 $(g.cRsz).css('height', $(g.t).height());
269 * Shift column from index oldn to newn.
271 * @param oldn old zero-based column index
272 * @param newn new zero-based column index
274 shiftCol: function(oldn, newn) {
275 $(g.t).find('tr').each(function() {
277 $(this).find('th.draggable:eq(' + newn + '),' +
278 'td:eq(' + (g.actionSpan + newn) + ')')
279 .before($(this).find('th.draggable:eq(' + oldn + '),' +
280 'td:eq(' + (g.actionSpan + oldn) + ')'));
282 $(this).find('th.draggable:eq(' + newn + '),' +
283 'td:eq(' + (g.actionSpan + newn) + ')')
284 .after($(this).find('th.draggable:eq(' + oldn + '),' +
285 'td:eq(' + (g.actionSpan + oldn) + ')'));
288 // reposition the column resize bars
291 // adjust the column visibility list
293 $(g.cList).find('.lDiv div:eq(' + newn + ')')
294 .before($(g.cList).find('.lDiv div:eq(' + oldn + ')'));
296 $(g.cList).find('.lDiv div:eq(' + newn + ')')
297 .after($(g.cList).find('.lDiv div:eq(' + oldn + ')'));
299 // adjust the colOrder
300 var tmp = g.colOrder[oldn];
301 g.colOrder.splice(oldn, 1);
302 g.colOrder.splice(newn, 0, tmp);
303 // adjust the colVisib
304 if (g.colVisib.length > 0) {
305 var tmp = g.colVisib[oldn];
306 g.colVisib.splice(oldn, 1);
307 g.colVisib.splice(newn, 0, tmp);
312 * Find currently hovered table column's header (excluding actions column).
315 * @return the hovered column's th object or undefined if no hovered column found.
317 getHoveredCol: function(e) {
319 $headers = $(g.t).find('th.draggable:visible');
320 $headers.each(function() {
321 var left = $(this).offset().left;
322 var right = left + $(this).outerWidth();
323 if (left <= e.pageX && e.pageX <= right) {
331 * Get a zero-based index from a <th class="draggable"> tag in a table.
333 * @param obj table header <th> object
334 * @return zero-based index of the specified table header in the set of table headers (visible or not)
336 getHeaderIdx: function(obj) {
337 return $(obj).parents('tr').find('th.draggable').index(obj);
341 * Reposition the columns back to normal order.
343 restoreColOrder: function() {
344 // use insertion sort, since we already have shiftCol function
345 for (var i = 1; i < g.colOrder.length; i++) {
346 var x = g.colOrder[i];
348 while (j >= 0 && x < g.colOrder[j]) {
352 g.shiftCol(i, j + 1);
355 if (g.tableCreateTime) {
356 // send request to server to remember the column order
359 g.refreshRestoreButton();
363 * Send column preferences (column order and visibility) to the server.
365 sendColPrefs: function() {
366 if ($(g.t).is('.ajax')) { // only send preferences if AjaxEnable is true
374 table_create_time: g.tableCreateTime
376 if (g.colOrder.length > 0) {
377 $.extend(post_params, { col_order: g.colOrder.toString() });
379 if (g.colVisib.length > 0) {
380 $.extend(post_params, { col_visib: g.colVisib.toString() });
382 $.post('sql.php', post_params, function(data) {
383 if (data.success != true) {
384 var $temp_div = $(document.createElement('div'));
385 $temp_div.html(data.error);
386 $temp_div.addClass("error");
387 PMA_ajaxShowMessage($temp_div);
394 * Refresh restore button state.
395 * Make restore button disabled if the table is similar with initial state.
397 refreshRestoreButton: function() {
398 // check if table state is as initial state
399 var isInitial = true;
400 for (var i = 0; i < g.colOrder.length; i++) {
401 if (g.colOrder[i] != i) {
406 // check if only one visible column left
407 var isOneColumn = g.visibleHeadersCount == 1;
408 // enable or disable restore button
409 if (isInitial || isOneColumn) {
410 $('.restore_column').hide();
412 $('.restore_column').show();
417 * Update current hint using the boolean values (showReorderHint, showSortHint, etc.).
418 * It will hide the hint if all the boolean values is false.
422 updateHint: function(e) {
423 if (!g.colRsz && !g.colReorder) { // if not resizing or dragging
425 if (g.showReorderHint && g.reorderHint) {
426 text += g.reorderHint;
428 if (g.showSortHint && g.sortHint) {
429 text += text.length > 0 ? '<br />' : '';
432 if (g.showMarkHint && g.markHint &&
433 !g.showSortHint // we do not show mark hint, when sort hint is shown
435 text += text.length > 0 ? '<br />' : '';
438 if (g.showColVisibHint && g.colVisibHint) {
439 text += text.length > 0 ? '<br />' : '';
440 text += g.colVisibHint;
443 // hide the hint if no text and the event is mouseenter
445 g.qtip.disable(!text && e.type == 'mouseenter');
446 g.qtip.updateContent(text, false);
453 hideHint: function() {
456 g.qtip.disable(true);
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').removeAttr('checked');
478 // cannot hide, force the checkbox to stay checked
479 $(g.cList).find('.lDiv div:eq(' + n + ') input').attr('checked', 'checked');
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').attr('checked', 'checked');
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) {
579 // remove all edit area and hide it
580 $(g.cEdit).find('.edit_area').empty().hide();
581 // reposition the cEdit element
583 top: $cell.position().top,
584 left: $cell.position().left
589 width: $cell.outerWidth(),
590 height: $cell.outerHeight()
592 // fill the cell edit with text from <td>
593 var value = PMA_getCellValue(cell);
594 $(g.cEdit).find('.edit_box').val(value);
596 g.currentEditCell = cell;
597 $(g.cEdit).find('.edit_box').focus();
598 $(g.cEdit).find('*').removeAttr('disabled');
604 * Remove edit cell and the edit area, if it is shown.
606 * @param force Optional, force to hide edit cell without saving edited field.
607 * @param data Optional, data from the POST AJAX request to save the edited field
608 * or just specify "true", if we want to replace the edited field with the new value.
609 * @param field Optional, the edited <td>. If not specified, the function will
610 * use currently edited <td> from g.currentEditCell.
612 hideEditCell: function(force, data, field) {
613 if (g.isCellEditActive && !force) {
614 // cell is being edited, save or post the edited data
615 g.saveOrPostEditedCell();
619 // cancel any previous request
620 if (g.lastXHR != null) {
626 if (g.currentEditCell) { // save value of currently edited cell
627 // replace current edited field with the new value
628 var $this_field = $(g.currentEditCell);
629 var is_null = $this_field.data('value') == null;
631 $this_field.find('span').html('NULL');
632 $this_field.addClass('null');
634 $this_field.removeClass('null');
635 var new_html = $this_field.data('value');
636 if ($this_field.is('.truncated')) {
637 if (new_html.length > g.maxTruncatedLen) {
638 new_html = new_html.substring(0, g.maxTruncatedLen) + '...';
641 $this_field.find('span').text(new_html);
644 if (data.transformations != undefined) {
645 $.each(data.transformations, function(cell_index, value) {
646 var $this_field = $(g.t).find('.to_be_saved:eq(' + cell_index + ')');
647 $this_field.find('span').html(value);
650 if (data.relations != undefined) {
651 $.each(data.relations, function(cell_index, value) {
652 var $this_field = $(g.t).find('.to_be_saved:eq(' + cell_index + ')');
653 $this_field.find('span').html(value);
662 // hide the cell editing area
664 $(g.cEdit).find('.edit_box').blur();
665 g.isCellEditActive = false;
666 g.currentEditCell = null;
667 // destroy datepicker in edit area, if exist
668 var $dp = $(g.cEdit).find('.hasDatepicker');
669 if ($dp.length > 0) {
670 $dp.datepicker('destroy');
671 // change the cursor in edit box back to normal
672 // (the cursor become a hand pointer when we add datepicker)
673 $(g.cEdit).find('.edit_box').css('cursor', 'inherit');
678 * Show drop-down edit area when edit cell is focused.
680 showEditArea: function() {
681 if (!g.isCellEditActive) { // make sure the edit area has not been shown
682 g.isCellEditActive = true;
683 g.isEditCellTextEditable = false;
685 * @var $td current edited cell
687 var $td = $(g.currentEditCell);
689 * @var $editArea the editing area
691 var $editArea = $(g.cEdit).find('.edit_area');
693 * @var where_clause WHERE clause for the edited cell
695 var where_clause = $td.parent('tr').find('.where_clause').val();
697 * @var field_name String containing the name of this field.
698 * @see getFieldName()
700 var field_name = getFieldName($td);
702 * @var relation_curr_value String current value of the field (for fields that are foreign keyed).
704 var relation_curr_value = $td.text();
706 * @var relation_key_or_display_column String relational key if in 'Relational display column' mode,
707 * relational display column if in 'Relational key' mode (for fields that are foreign keyed).
709 var relation_key_or_display_column = $td.find('a').attr('title');
711 * @var curr_value String current value of the field (for fields that are of type enum or set).
713 var curr_value = $td.find('span').text();
715 // empty all edit area, then rebuild it based on $td classes
718 // add goto link, if this cell contains a link
719 if ($td.find('a').length > 0) {
720 var gotoLink = document.createElement('div');
721 gotoLink.className = 'goto_link';
722 $(gotoLink).append(g.gotoLinkText + ': ')
723 .append($td.find('a').clone());
724 $editArea.append(gotoLink);
727 g.wasEditedCellNull = false;
728 if ($td.is(':not(.not_null)')) {
729 // append a null checkbox
730 $editArea.append('<div class="null_div">Null :<input type="checkbox"></div>');
731 var $checkbox = $editArea.find('.null_div input');
732 // check if current <td> is NULL
733 if ($td.is('.null')) {
734 $checkbox.attr('checked', true);
735 g.wasEditedCellNull = true;
738 // if the select/editor is changed un-check the 'checkbox_null_<field_name>_<row_index>'.
739 if ($td.is('.enum, .set')) {
740 $editArea.find('select').live('change', function(e) {
741 $checkbox.attr('checked', false);
743 } else if ($td.is('.relation')) {
744 $editArea.find('select').live('change', function(e) {
745 $checkbox.attr('checked', false);
747 $editArea.find('.browse_foreign').live('click', function(e) {
748 $checkbox.attr('checked', false);
751 $(g.cEdit).find('.edit_box').live('keypress change', function(e) {
752 $checkbox.attr('checked', false);
754 $editArea.find('textarea').live('keydown', function(e) {
755 $checkbox.attr('checked', false);
759 // if null checkbox is clicked empty the corresponding select/editor.
760 $checkbox.click(function(e) {
761 if ($td.is('.enum')) {
762 $editArea.find('select').attr('value', '');
763 } else if ($td.is('.set')) {
764 $editArea.find('select').find('option').each(function() {
765 var $option = $(this);
766 $option.attr('selected', false);
768 } else if ($td.is('.relation')) {
769 // if the dropdown is there to select the foreign value
770 if ($editArea.find('select').length > 0) {
771 $editArea.find('select').attr('value', '');
774 $editArea.find('textarea').val('');
776 $(g.cEdit).find('.edit_box').val('');
780 if ($td.is('.relation')) {
782 $editArea.addClass('edit_area_loading');
784 // initialize the original data
785 $td.data('original_data', null);
788 * @var post_params Object containing parameters for the POST request
791 'ajax_request' : true,
792 'get_relational_values' : true,
796 'column' : field_name,
798 'curr_value' : relation_curr_value,
799 'relation_key_or_display_column' : relation_key_or_display_column
802 g.lastXHR = $.post('sql.php', post_params, function(data) {
804 $editArea.removeClass('edit_area_loading');
805 if ($(data.dropdown).is('select')) {
806 // save original_data
807 var value = $(data.dropdown).val();
808 $td.data('original_data', value);
809 // update the text input field, in case where the "Relational display column" is checked
810 $(g.cEdit).find('.edit_box').val(value);
813 $editArea.append(data.dropdown);
814 $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
818 $editArea.find('select').live('change', function(e) {
819 $(g.cEdit).find('.edit_box').val($(this).val());
822 else if($td.is('.enum')) {
824 $editArea.addClass('edit_area_loading');
827 * @var post_params Object containing parameters for the POST request
830 'ajax_request' : true,
831 'get_enum_values' : true,
835 'column' : field_name,
837 'curr_value' : curr_value
839 g.lastXHR = $.post('sql.php', post_params, function(data) {
841 $editArea.removeClass('edit_area_loading');
842 $editArea.append(data.dropdown);
843 $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
847 $editArea.find('select').live('change', function(e) {
848 $(g.cEdit).find('.edit_box').val($(this).val());
851 else if($td.is('.set')) {
853 $editArea.addClass('edit_area_loading');
856 * @var post_params Object containing parameters for the POST request
859 'ajax_request' : true,
860 'get_set_values' : true,
864 'column' : field_name,
866 'curr_value' : curr_value
869 g.lastXHR = $.post('sql.php', post_params, function(data) {
871 $editArea.removeClass('edit_area_loading');
872 $editArea.append(data.select);
873 $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
877 $editArea.find('select').live('change', function(e) {
878 $(g.cEdit).find('.edit_box').val($(this).val());
881 else if($td.is('.truncated, .transformed')) {
882 if ($td.is('.to_be_saved')) { // cell has been edited
883 var value = $td.data('value');
884 $(g.cEdit).find('.edit_box').val(value);
885 $editArea.append('<textarea></textarea>');
886 $editArea.find('textarea')
888 .live('keyup', function(e) {
889 $(g.cEdit).find('.edit_box').val($(this).val());
891 $(g.cEdit).find('.edit_box').live('keyup', function(e) {
892 $editArea.find('textarea').val($(this).val());
894 $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
896 //handle truncated/transformed values values
897 $editArea.addClass('edit_area_loading');
899 // initialize the original data
900 $td.data('original_data', null);
903 * @var sql_query String containing the SQL query used to retrieve value of truncated/transformed data
905 var sql_query = 'SELECT `' + field_name + '` FROM `' + g.table + '` WHERE ' + PMA_urldecode(where_clause);
907 // Make the Ajax call and get the data, wrap it and insert it
908 g.lastXHR = $.post('sql.php', {
912 'ajax_request' : true,
913 'sql_query' : sql_query,
917 $editArea.removeClass('edit_area_loading');
918 if(data.success == true) {
919 if ($td.is('.truncated')) {
920 // get the truncated data length
921 g.maxTruncatedLen = $(g.currentEditCell).text().length - 3;
924 $td.data('original_data', data.value);
925 $(g.cEdit).find('.edit_box').val(data.value);
926 $editArea.append('<textarea></textarea>');
927 $editArea.find('textarea')
929 .live('keyup', function(e) {
930 $(g.cEdit).find('.edit_box').val($(this).val());
932 $(g.cEdit).find('.edit_box').live('keyup', function(e) {
933 $editArea.find('textarea').val($(this).val());
935 $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
938 PMA_ajaxShowMessage(data.error);
943 g.isEditCellTextEditable = true;
944 } else if ($td.is('.datefield, .datetimefield, .timestampfield')) {
945 var $input_field = $(g.cEdit).find('.edit_box');
947 // remember current datetime value in $input_field, if it is not null
948 var is_null = $td.is('.null');
949 var current_datetime_value = !is_null ? $input_field.val() : '';
951 var showTimeOption = true;
952 if ($td.is('.datefield')) {
953 showTimeOption = false;
955 PMA_addDatepicker($editArea, {
956 altField: $input_field,
957 showTimepicker: showTimeOption,
958 onSelect: function(dateText, inst) {
959 // remove null checkbox if it exists
960 $(g.cEdit).find('.null_div input[type=checkbox]').attr('checked', false);
964 // cancel any click on the datepicker element
965 $editArea.find('> *').click(function(e) {
969 // force to restore modified $input_field value after adding datepicker
970 // (after adding a datepicker, the input field doesn't display the time anymore, only the date)
972 $editArea.datetimepicker('setDate', current_datetime_value);
974 $input_field.val('');
976 $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
978 g.isEditCellTextEditable = true;
979 // only append edit area hint if there is a null checkbox
980 if ($editArea.children().length > 0) {
981 $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
984 if ($editArea.children().length > 0) {
991 * Post the content of edited cell.
993 postEditedCell: function() {
1000 * @var relation_fields Array containing the name/value pairs of relational fields
1002 var relation_fields = {};
1004 * @var relational_display string 'K' if relational key, 'D' if relational display column
1006 var relational_display = $("#relational_display_K").attr('checked') ? 'K' : 'D';
1008 * @var transform_fields Array containing the name/value pairs for transformed fields
1010 var transform_fields = {};
1012 * @var transformation_fields Boolean, if there are any transformed fields in the edited cells
1014 var transformation_fields = false;
1016 * @var full_sql_query String containing the complete SQL query to update this table
1018 var full_sql_query = '';
1020 * @var rel_fields_list String, url encoded representation of {@link relations_fields}
1022 var rel_fields_list = '';
1024 * @var transform_fields_list String, url encoded representation of {@link transform_fields}
1026 var transform_fields_list = '';
1028 * @var where_clause Array containing where clause for updated fields
1030 var full_where_clause = Array();
1032 * @var is_unique Boolean, whether the rows in this table is unique or not
1034 var is_unique = $('.edit_row_anchor').is('.nonunique') ? 0 : 1;
1036 * multi edit variables
1038 var me_fields_name = Array();
1039 var me_fields = Array();
1040 var me_fields_null = Array();
1042 // alert user if edited table is not unique
1044 alert(g.alertNonUnique);
1047 // loop each edited row
1048 $('.to_be_saved').parents('tr').each(function() {
1050 var where_clause = $tr.find('.where_clause').val();
1051 full_where_clause.push(PMA_urldecode(where_clause));
1052 var condition_array = jQuery.parseJSON($tr.find('.condition_array').val());
1055 * multi edit variables, for current row
1056 * @TODO array indices are still not correct, they should be md5 of field's name
1058 var fields_name = Array();
1059 var fields = Array();
1060 var fields_null = Array();
1062 // loop each edited cell in a row
1063 $tr.find('.to_be_saved').each(function() {
1065 * @var $this_field Object referring to the td that is being edited
1067 var $this_field = $(this);
1070 * @var field_name String containing the name of this field.
1071 * @see getFieldName()
1073 var field_name = getFieldName($this_field);
1076 * @var this_field_params Array temporary storage for the name/value of current field
1078 var this_field_params = {};
1080 if($this_field.is('.transformed')) {
1081 transformation_fields = true;
1083 this_field_params[field_name] = $this_field.data('value');
1086 * @var is_null String capturing whether 'checkbox_null_<field_name>_<row_index>' is checked.
1088 var is_null = this_field_params[field_name] === null;
1090 fields_name.push(field_name);
1093 fields_null.push('on');
1096 fields_null.push('');
1097 fields.push($this_field.data('value'));
1099 var cell_index = $this_field.index('.to_be_saved');
1100 if($this_field.is(":not(.relation, .enum, .set, .bit)")) {
1101 if($this_field.is('.transformed')) {
1102 transform_fields[cell_index] = {};
1103 $.extend(transform_fields[cell_index], this_field_params);
1105 } else if($this_field.is('.relation')) {
1106 relation_fields[cell_index] = {};
1107 $.extend(relation_fields[cell_index], this_field_params);
1110 // check if edited field appears in WHERE clause
1111 if (where_clause.indexOf(PMA_urlencode(field_name)) > -1) {
1112 var field_str = '`' + g.table + '`.' + '`' + field_name + '`';
1113 for (var field in condition_array) {
1114 if (field.indexOf(field_str) > -1) {
1115 condition_array[field] = is_null ? 'IS NULL' : "= '" + this_field_params[field_name].replace(/'/g,"''") + "'";
1121 }); // end of loop for every edited cells in a row
1124 var new_clause = '';
1125 for (var field in condition_array) {
1126 new_clause += field + ' ' + condition_array[field] + ' AND ';
1128 new_clause = new_clause.substring(0, new_clause.length - 5); // remove the last AND
1129 new_clause = PMA_urlencode(new_clause);
1130 $tr.data('new_clause', new_clause);
1131 // save condition_array
1132 $tr.find('.condition_array').val(JSON.stringify(condition_array));
1134 me_fields_name.push(fields_name);
1135 me_fields.push(fields);
1136 me_fields_null.push(fields_null);
1138 }); // end of loop for every edited rows
1140 rel_fields_list = $.param(relation_fields);
1141 transform_fields_list = $.param(transform_fields);
1143 // Make the Ajax post after setting all parameters
1145 * @var post_params Object containing parameters for the POST request
1147 var post_params = {'ajax_request' : true,
1148 'sql_query' : full_sql_query,
1150 'server' : g.server,
1153 'clause_is_unique' : is_unique,
1154 'where_clause' : full_where_clause,
1155 'fields[multi_edit]' : me_fields,
1156 'fields_name[multi_edit]' : me_fields_name,
1157 'fields_null[multi_edit]' : me_fields_null,
1158 'rel_fields_list' : rel_fields_list,
1159 'do_transformations' : transformation_fields,
1160 'transform_fields_list' : transform_fields_list,
1161 'relational_display' : relational_display,
1163 'submit_type' : 'save'
1166 if (!g.saveCellsAtOnce) {
1167 $(g.cEdit).find('*').attr('disabled', 'disabled');
1168 var $editArea = $(g.cEdit).find('.edit_area');
1169 $(g.cEdit).find('.edit_box').addClass('edit_box_posting');
1171 $('.save_edited').addClass('saving_edited_data')
1172 .find('input').attr('disabled', 'disabled'); // disable the save button
1177 url: 'tbl_replace.php',
1182 if (!g.saveCellsAtOnce) {
1183 $(g.cEdit).find('*').removeAttr('disabled');
1184 $(g.cEdit).find('.edit_box').removeClass('edit_box_posting');
1186 $('.save_edited').removeClass('saving_edited_data')
1187 .find('input').removeAttr('disabled'); // enable the save button back
1189 if(data.success == true) {
1190 PMA_ajaxShowMessage(data.message);
1191 // update where_clause related data in each edited row
1192 $('.to_be_saved').parents('tr').each(function() {
1193 var new_clause = $(this).data('new_clause');
1194 var $where_clause = $(this).find('.where_clause');
1195 var old_clause = $where_clause.attr('value');
1196 var decoded_old_clause = PMA_urldecode(old_clause);
1197 var decoded_new_clause = PMA_urldecode(new_clause);
1199 $where_clause.attr('value', new_clause);
1200 // update Edit, Copy, and Delete links also
1201 $(this).find('a').each(function() {
1202 $(this).attr('href', $(this).attr('href').replace(old_clause, new_clause));
1203 // update delete confirmation in Delete link
1204 if ($(this).attr('href').indexOf('DELETE') > -1) {
1205 $(this).removeAttr('onclick')
1207 .bind('click', function() {
1208 return confirmLink(this, 'DELETE FROM `' + g.db + '`.`' + g.table + '` WHERE ' +
1209 decoded_new_clause + (is_unique ? '' : ' LIMIT 1'));
1213 // update the multi edit checkboxes
1214 $(this).find('input[type=checkbox]').each(function() {
1215 var $checkbox = $(this);
1216 var checkbox_name = $checkbox.attr('name');
1217 var checkbox_value = $checkbox.attr('value');
1219 $checkbox.attr('name', checkbox_name.replace(old_clause, new_clause));
1220 $checkbox.attr('value', checkbox_value.replace(decoded_old_clause, decoded_new_clause));
1223 // update the display of executed SQL query command
1224 $('#result_query').remove();
1225 if (typeof data.sql_query != 'undefined') {
1227 $('#sqlqueryresults').prepend(data.sql_query);
1229 // hide and/or update the successfully saved cells
1230 g.hideEditCell(true, data);
1232 // remove the "Save edited cells" button
1233 $('.save_edited').hide();
1234 // update saved fields
1235 $(g.t).find('.to_be_saved')
1236 .removeClass('to_be_saved')
1237 .data('value', null)
1238 .data('original_data', null);
1240 g.isCellEdited = false;
1242 PMA_ajaxShowMessage(data.error);
1249 * Save edited cell, so it can be posted later.
1251 saveEditedCell: function() {
1253 * @var $this_field Object referring to the td that is being edited
1255 var $this_field = $(g.currentEditCell);
1256 var $test_element = ''; // to test the presence of a element
1258 var need_to_post = false;
1261 * @var field_name String containing the name of this field.
1262 * @see getFieldName()
1264 var field_name = getFieldName($this_field);
1267 * @var this_field_params Array temporary storage for the name/value of current field
1269 var this_field_params = {};
1272 * @var is_null String capturing whether 'checkbox_null_<field_name>_<row_index>' is checked.
1274 var is_null = $(g.cEdit).find('input:checkbox').is(':checked');
1277 if ($(g.cEdit).find('.edit_area').is('.edit_area_loading')) {
1278 // the edit area is still loading (retrieving cell data), no need to post
1279 need_to_post = false;
1280 } else if (is_null) {
1281 if (!g.wasEditedCellNull) {
1282 this_field_params[field_name] = null;
1283 need_to_post = true;
1286 if ($this_field.is('.bit')) {
1287 this_field_params[field_name] = '0b' + $(g.cEdit).find('.edit_box').val();
1288 } else if ($this_field.is('.set')) {
1289 $test_element = $(g.cEdit).find('select');
1290 this_field_params[field_name] = $test_element.map(function(){
1291 return $(this).val();
1293 } else if ($this_field.is('.relation, .enum')) {
1294 // results from a drop-down
1295 $test_element = $(g.cEdit).find('select');
1296 if ($test_element.length != 0) {
1297 this_field_params[field_name] = $test_element.val();
1300 // results from Browse foreign value
1301 $test_element = $(g.cEdit).find('span.curr_value');
1302 if ($test_element.length != 0) {
1303 this_field_params[field_name] = $test_element.text();
1306 this_field_params[field_name] = $(g.cEdit).find('.edit_box').val();
1308 if (g.wasEditedCellNull || this_field_params[field_name] != PMA_getCellValue(g.currentEditCell)) {
1309 need_to_post = true;
1314 $(g.currentEditCell).addClass('to_be_saved')
1315 .data('value', this_field_params[field_name]);
1316 if (g.saveCellsAtOnce) {
1317 $('.save_edited').show();
1319 g.isCellEdited = true;
1322 return need_to_post;
1326 * Save or post currently edited cell, depending on the "saveCellsAtOnce" configuration.
1328 saveOrPostEditedCell: function() {
1329 var saved = g.saveEditedCell();
1330 if (!g.saveCellsAtOnce) {
1334 g.hideEditCell(true);
1338 g.hideEditCell(true, true);
1340 g.hideEditCell(true);
1346 * Initialize column resize feature.
1348 initColResize: function() {
1349 // create column resizer div
1350 g.cRsz = document.createElement('div');
1351 g.cRsz.className = 'cRsz';
1353 // get data columns in the first row of the table
1354 var $firstRowCols = $(g.t).find('tr:first th.draggable');
1356 // create column borders
1357 $firstRowCols.each(function() {
1358 var cb = document.createElement('div'); // column border
1359 $(cb).addClass('colborder')
1360 .mousedown(function(e) {
1361 g.dragStartRsz(e, this);
1363 $(g.cRsz).append(cb);
1367 // attach to global div
1368 $(g.gDiv).prepend(g.cRsz);
1372 * Initialize column reordering feature.
1374 initColReorder: function() {
1375 g.cCpy = document.createElement('div'); // column copy, to store copy of dragged column header
1376 g.cPointer = document.createElement('div'); // column pointer, used when reordering column
1379 g.cCpy.className = 'cCpy';
1382 // adjust g.cPointer
1383 g.cPointer.className = 'cPointer';
1384 $(g.cPointer).css('visibility', 'hidden'); // set visibility to hidden instead of calling hide() to force browsers to cache the image in cPointer class
1386 // assign column reordering hint
1387 g.reorderHint = PMA_messages['strColOrderHint'];
1389 // get data columns in the first row of the table
1390 var $firstRowCols = $(g.t).find('tr:first th.draggable');
1392 // initialize column order
1393 $col_order = $('#col_order'); // check if column order is passed from PHP
1394 if ($col_order.length > 0) {
1395 g.colOrder = $col_order.val().split(',');
1396 for (var i = 0; i < g.colOrder.length; i++) {
1397 g.colOrder[i] = parseInt(g.colOrder[i]);
1400 g.colOrder = new Array();
1401 for (var i = 0; i < $firstRowCols.length; i++) {
1407 $(t).find('th.draggable')
1408 .mousedown(function(e) {
1409 if (g.visibleHeadersCount > 1) {
1410 g.dragStartReorder(e, this);
1413 .mouseenter(function(e) {
1414 if (g.visibleHeadersCount > 1) {
1415 g.showReorderHint = true;
1416 $(this).css('cursor', 'move');
1418 $(this).css('cursor', 'inherit');
1421 .mouseleave(function(e) {
1422 g.showReorderHint = false;
1424 // restore column order when the restore button is clicked
1425 $('.restore_column').click(function() {
1426 g.restoreColOrder();
1429 // attach to global div
1430 $(g.gDiv).append(g.cPointer);
1431 $(g.gDiv).append(g.cCpy);
1433 // prevent default "dragstart" event when dragging a link
1434 $(t).find('th a').bind('dragstart', function() {
1438 // refresh the restore column button state
1439 g.refreshRestoreButton();
1443 * Initialize column visibility feature.
1445 initColVisib: function() {
1446 g.cDrop = document.createElement('div'); // column drop-down arrows
1447 g.cList = document.createElement('div'); // column visibility list
1450 g.cDrop.className = 'cDrop';
1453 g.cList.className = 'cList';
1456 // assign column visibility related hints
1457 g.colVisibHint = PMA_messages['strColVisibHint'];
1458 g.showAllColText = PMA_messages['strShowAllCol'];
1460 // get data columns in the first row of the table
1461 var $firstRowCols = $(g.t).find('tr:first th.draggable');
1463 // initialize column visibility
1464 var $col_visib = $('#col_visib'); // check if column visibility is passed from PHP
1465 if ($col_visib.length > 0) {
1466 g.colVisib = $col_visib.val().split(',');
1467 for (var i = 0; i < g.colVisib.length; i++) {
1468 g.colVisib[i] = parseInt(g.colVisib[i]);
1471 g.colVisib = new Array();
1472 for (var i = 0; i < $firstRowCols.length; i++) {
1477 // make sure we have more than one column
1478 if ($firstRowCols.length > 1) {
1479 var $colVisibTh = $(g.t).find('th:not(.draggable)');
1480 PMA_createqTip($colVisibTh);
1482 // create column visibility drop-down arrow(s)
1483 $colVisibTh.each(function() {
1485 var cd = document.createElement('div'); // column drop-down arrow
1486 var pos = $th.position();
1487 $(cd).addClass('coldrop')
1489 if (g.cList.style.display == 'none') {
1490 g.showColList(this);
1495 $(g.cDrop).append(cd);
1497 .mouseenter(function(e) {
1498 g.showColVisibHint = true;
1500 .mouseleave(function(e) {
1501 g.showColVisibHint = false;
1504 // add column visibility control
1505 g.cList.innerHTML = '<div class="lDiv"></div>';
1506 var $listDiv = $(g.cList).find('div');
1507 for (var i = 0; i < $firstRowCols.length; i++) {
1508 var currHeader = $firstRowCols[i];
1509 var listElmt = document.createElement('div');
1510 $(listElmt).text($(currHeader).text())
1511 .prepend('<input type="checkbox" ' + (g.colVisib[i] ? 'checked="checked" ' : '') + '/>');
1512 $listDiv.append(listElmt);
1513 // add event on click
1514 $(listElmt).click(function() {
1515 if ( g.toggleCol($(this).index()) ) {
1520 // add "show all column" button
1521 var showAll = document.createElement('div');
1522 $(showAll).addClass('showAllColBtn')
1523 .text(g.showAllColText);
1524 $(g.cList).append(showAll);
1525 $(showAll).click(function() {
1528 // prepend "show all column" button at top if the list is too long
1529 if ($firstRowCols.length > 10) {
1530 var clone = showAll.cloneNode(true);
1531 $(g.cList).prepend(clone);
1532 $(clone).click(function() {
1538 // hide column visibility list if we move outside the list
1539 $(t).find('td, th.draggable').mouseenter(function() {
1543 // attach to global div
1544 $(g.gDiv).append(g.cDrop);
1545 $(g.gDiv).append(g.cList);
1552 * Initialize grid editing feature.
1554 initGridEdit: function() {
1555 // create cell edit wrapper element
1556 g.cEdit = document.createElement('div');
1559 g.cEdit.className = 'cEdit';
1560 $(g.cEdit).html('<textarea class="edit_box" rows="1" ></textarea><div class="edit_area" />');
1563 // assign cell editing hint
1564 g.cellEditHint = PMA_messages['strCellEditHint'];
1565 g.saveCellWarning = PMA_messages['strSaveCellWarning'];
1566 g.alertNonUnique = PMA_messages['strAlertNonUnique'];
1567 g.gotoLinkText = PMA_messages['strGoToLink'];
1569 // initialize cell editing configuration
1570 g.saveCellsAtOnce = $('#save_cells_at_once').val();
1573 $(t).find('td.data')
1574 .click(function(e) {
1575 if (g.isCellEditActive) {
1576 g.saveOrPostEditedCell();
1577 e.stopPropagation();
1579 g.showEditCell(this);
1580 e.stopPropagation();
1582 // prevent default action when clicking on "link" in a table
1583 if ($(e.target).is('a')) {
1587 $(g.cEdit).find('.edit_box').focus(function(e) {
1590 $(g.cEdit).find('.edit_box, select').live('keydown', function(e) {
1591 if (e.which == 13) {
1592 // post on pressing "Enter"
1594 g.saveOrPostEditedCell();
1597 $(g.cEdit).keydown(function(e) {
1598 if (!g.isEditCellTextEditable) {
1599 // prevent text editing
1603 $('html').click(function(e) {
1604 // hide edit cell if the click is not from g.cEdit
1605 if ($(e.target).parents().index(g.cEdit) == -1) {
1609 $('html').keydown(function(e) {
1610 if (e.which == 27 && g.isCellEditActive) {
1612 // cancel on pressing "Esc"
1613 g.hideEditCell(true);
1616 $('.save_edited').click(function() {
1620 $(window).bind('beforeunload', function(e) {
1621 if (g.isCellEdited) {
1622 return g.saveCellWarning;
1626 // attach to global div
1627 $(g.gDiv).append(g.cEdit);
1629 // add hint for grid editing feature when hovering "Edit" link in each table row
1630 PMA_createqTip($(g.t).find('.edit_row_anchor a'), PMA_messages['strGridEditFeatureHint']);
1638 // wrap all data cells, except actions cell, with span
1639 $(t).find('th, td:not(:has(span))')
1640 .wrapInner('<span />');
1642 // create grid elements
1643 g.gDiv = document.createElement('div'); // create global div
1645 // initialize the table variable
1648 // get data columns in the first row of the table
1649 var $firstRowCols = $(t).find('tr:first th.draggable');
1651 // initialize visible headers count
1652 g.visibleHeadersCount = $firstRowCols.filter(':visible').length;
1654 // assign first column (actions) span
1655 if (! $(t).find('tr:first th:first').hasClass('draggable')) { // action header exist
1656 g.actionSpan = $(t).find('tr:first th:first').prop('colspan');
1661 // assign table create time
1662 // #table_create_time will only available if we are in "Browse" tab
1663 g.tableCreateTime = $('#table_create_time').val();
1666 g.sortHint = PMA_messages['strSortHint'];
1667 g.markHint = PMA_messages['strColMarkHint'];
1669 // assign common hidden inputs
1670 var $common_hidden_inputs = $('.common_hidden_inputs');
1671 g.token = $common_hidden_inputs.find('input[name=token]').val();
1672 g.server = $common_hidden_inputs.find('input[name=server]').val();
1673 g.db = $common_hidden_inputs.find('input[name=db]').val();
1674 g.table = $common_hidden_inputs.find('input[name=table]').val();
1677 $(t).addClass('pma_table');
1679 // add relative position to global div so that resize handlers are correctly positioned
1680 $(g.gDiv).css('position', 'relative');
1682 // link the global div
1683 $(t).before(g.gDiv);
1684 $(g.gDiv).append(t);
1687 enableResize = enableResize == undefined ? true : enableResize;
1688 enableReorder = enableReorder == undefined ? true : enableReorder;
1689 enableVisib = enableVisib == undefined ? true : enableVisib;
1690 enableGridEdit = enableGridEdit == undefined ? true : enableGridEdit;
1694 if (enableReorder &&
1695 $('.navigation').length > 0) // disable reordering for result from EXPLAIN or SHOW syntax, which do not have a table navigation panel
1702 if (enableGridEdit &&
1703 $(t).is('.ajax')) // make sure AjaxEnable is enabled in Settings
1708 // create qtip for each <th> with draggable class
1709 PMA_createqTip($(t).find('th.draggable'));
1711 // register events for hint tooltip
1712 $(t).find('th.draggable a')
1713 .attr('title', '') // hide default tooltip for sorting
1714 .mouseenter(function(e) {
1715 g.showSortHint = true;
1718 .mouseleave(function(e) {
1719 g.showSortHint = false;
1722 $(t).find('th.marker')
1723 .mouseenter(function(e) {
1724 g.showMarkHint = true;
1726 .mouseleave(function(e) {
1727 g.showMarkHint = false;
1729 // register events for dragging-related feature
1730 if (enableResize || enableReorder) {
1731 $(document).mousemove(function(e) {
1734 $(document).mouseup(function(e) {
1739 // bind event to update currently hovered qtip API
1741 .mouseenter(function(e) {
1742 g.qtip = $(this).qtip('api');
1745 .mouseleave(function(e) {
1750 $(t).removeClass('data');
1751 $(g.gDiv).addClass('data');