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)
83 $(obj).addClass('colborder_active');
88 objLeft: $(obj).position().left,
89 objWidth: $(g.t).find('th.draggable:visible:eq(' + n + ') span').outerWidth()
91 $('body').css('cursor', 'col-resize');
93 if (g.isCellEditActive) {
99 * Start to reorder column. Called when clicking on table header.
102 * @param obj table header object
104 dragStartReorder: function(e, obj) {
105 // prepare the cCpy (column copy) and cPointer (column pointer) from the dragged column
106 $(g.cCpy).text($(obj).text());
107 var objPos = $(obj).position();
109 top: objPos.top + 20,
111 height: $(obj).height(),
112 width: $(obj).width()
118 // get the column index, zero-based
119 var n = g.getHeaderIdx(obj);
131 $('body').css('cursor', 'move');
132 $('body').noSelect();
133 if (g.isCellEditActive) {
139 * Handle mousemove event when dragging.
143 dragMove: function(e) {
145 var dx = e.pageX - g.colRsz.x0;
146 if (g.colRsz.objWidth + dx > g.minColWidth) {
147 $(g.colRsz.obj).css('left', g.colRsz.objLeft + dx + 'px');
149 } else if (g.colReorder) {
150 // dragged column animation
151 var dx = e.pageX - g.colReorder.x0;
153 .css('left', g.colReorder.objLeft + dx)
157 var hoveredCol = g.getHoveredCol(e);
159 var newn = g.getHeaderIdx(hoveredCol);
160 g.colReorder.newn = newn;
161 if (newn != g.colReorder.n) {
162 // show the column pointer in the right place
163 var colPos = $(hoveredCol).position();
164 var newleft = newn < g.colReorder.n ?
166 colPos.left + $(hoveredCol).outerWidth();
170 visibility: 'visible'
173 // no movement to other column, hide the column pointer
174 $(g.cPointer).css('visibility', 'hidden');
181 * Stop the dragging action.
185 dragEnd: function(e) {
187 var dx = e.pageX - g.colRsz.x0;
188 var nw = g.colRsz.objWidth + dx;
189 if (nw < g.minColWidth) {
199 $(g.cRsz).find('div').removeClass('colborder_active');
200 } else if (g.colReorder) {
202 if (g.colReorder.newn != g.colReorder.n) {
203 g.shiftCol(g.colReorder.n, g.colReorder.newn);
204 // assign new position
205 var objPos = $(g.colReorder.obj).position();
206 g.colReorder.objTop = objPos.top;
207 g.colReorder.objLeft = objPos.left;
208 g.colReorder.n = g.colReorder.newn;
209 // send request to server to remember the column order
210 if (g.tableCreateTime) {
213 g.refreshRestoreButton();
216 // animate new column position
217 $(g.cCpy).stop(true, true)
219 top: g.colReorder.objTop,
220 left: g.colReorder.objLeft
223 $(g.cPointer).css('visibility', 'hidden');
225 g.colReorder = false;
227 $('body').css('cursor', 'inherit');
228 $('body').noSelect(false);
232 * Resize column n to new width "nw"
234 * @param n zero-based column index
235 * @param nw new width of the column in pixel
237 resize: function(n, nw) {
238 $(g.t).find('tr').each(function() {
239 $(this).find('th.draggable:visible:eq(' + n + ') span,' +
240 'td:visible:eq(' + (g.actionSpan + n) + ') span')
246 * Reposition column resize bars.
248 reposRsz: function() {
249 $(g.cRsz).find('div').hide();
250 var $firstRowCols = $(g.t).find('tr:first th.draggable:visible');
251 var $resizeHandles = $(g.cRsz).find('div').removeClass('condition');
252 $('.pma_table').find('thead th:first').removeClass('before-condition');
253 for (var n = 0; n < $firstRowCols.length; n++) {
254 var $col = $($firstRowCols[n]);
255 $($resizeHandles[n]).css('left', $col.position().left + $col.outerWidth(true))
257 if ($($firstRowCols[n]).hasClass('condition')) {
258 $($resizeHandles[n]).addClass('condition');
260 $($resizeHandles[n-1]).addClass('condition');
264 if ($($resizeHandles[0]).hasClass('condition')) {
265 $('.pma_table').find('thead th:first').addClass('before-condition');
267 $(g.cRsz).css('height', $(g.t).height());
271 * Shift column from index oldn to newn.
273 * @param oldn old zero-based column index
274 * @param newn new zero-based column index
276 shiftCol: function(oldn, newn) {
277 $(g.t).find('tr').each(function() {
279 $(this).find('th.draggable:eq(' + newn + '),' +
280 'td:eq(' + (g.actionSpan + newn) + ')')
281 .before($(this).find('th.draggable:eq(' + oldn + '),' +
282 'td:eq(' + (g.actionSpan + oldn) + ')'));
284 $(this).find('th.draggable:eq(' + newn + '),' +
285 'td:eq(' + (g.actionSpan + newn) + ')')
286 .after($(this).find('th.draggable:eq(' + oldn + '),' +
287 'td:eq(' + (g.actionSpan + oldn) + ')'));
290 // reposition the column resize bars
293 // adjust the column visibility list
295 $(g.cList).find('.lDiv div:eq(' + newn + ')')
296 .before($(g.cList).find('.lDiv div:eq(' + oldn + ')'));
298 $(g.cList).find('.lDiv div:eq(' + newn + ')')
299 .after($(g.cList).find('.lDiv div:eq(' + oldn + ')'));
301 // adjust the colOrder
302 var tmp = g.colOrder[oldn];
303 g.colOrder.splice(oldn, 1);
304 g.colOrder.splice(newn, 0, tmp);
305 // adjust the colVisib
306 if (g.colVisib.length > 0) {
307 var tmp = g.colVisib[oldn];
308 g.colVisib.splice(oldn, 1);
309 g.colVisib.splice(newn, 0, tmp);
314 * Find currently hovered table column's header (excluding actions column).
317 * @return the hovered column's th object or undefined if no hovered column found.
319 getHoveredCol: function(e) {
321 $headers = $(g.t).find('th.draggable:visible');
322 $headers.each(function() {
323 var left = $(this).offset().left;
324 var right = left + $(this).outerWidth();
325 if (left <= e.pageX && e.pageX <= right) {
333 * Get a zero-based index from a <th class="draggable"> tag in a table.
335 * @param obj table header <th> object
336 * @return zero-based index of the specified table header in the set of table headers (visible or not)
338 getHeaderIdx: function(obj) {
339 return $(obj).parents('tr').find('th.draggable').index(obj);
343 * Reposition the columns back to normal order.
345 restoreColOrder: function() {
346 // use insertion sort, since we already have shiftCol function
347 for (var i = 1; i < g.colOrder.length; i++) {
348 var x = g.colOrder[i];
350 while (j >= 0 && x < g.colOrder[j]) {
354 g.shiftCol(i, j + 1);
357 if (g.tableCreateTime) {
358 // send request to server to remember the column order
361 g.refreshRestoreButton();
365 * Send column preferences (column order and visibility) to the server.
367 sendColPrefs: function() {
368 if ($(g.t).is('.ajax')) { // only send preferences if AjaxEnable is true
376 table_create_time: g.tableCreateTime
378 if (g.colOrder.length > 0) {
379 $.extend(post_params, { col_order: g.colOrder.toString() });
381 if (g.colVisib.length > 0) {
382 $.extend(post_params, { col_visib: g.colVisib.toString() });
384 $.post('sql.php', post_params, function(data) {
385 if (data.success != true) {
386 var $temp_div = $(document.createElement('div'));
387 $temp_div.html(data.error);
388 $temp_div.addClass("error");
389 PMA_ajaxShowMessage($temp_div, false);
396 * Refresh restore button state.
397 * Make restore button disabled if the table is similar with initial state.
399 refreshRestoreButton: function() {
400 // check if table state is as initial state
401 var isInitial = true;
402 for (var i = 0; i < g.colOrder.length; i++) {
403 if (g.colOrder[i] != i) {
408 // check if only one visible column left
409 var isOneColumn = g.visibleHeadersCount == 1;
410 // enable or disable restore button
411 if (isInitial || isOneColumn) {
412 $('.restore_column').hide();
414 $('.restore_column').show();
419 * Update current hint using the boolean values (showReorderHint, showSortHint, etc.).
420 * It will hide the hint if all the boolean values is false.
424 updateHint: function(e) {
425 if (!g.colRsz && !g.colReorder) { // if not resizing or dragging
427 if (g.showReorderHint && g.reorderHint) {
428 text += g.reorderHint;
430 if (g.showSortHint && g.sortHint) {
431 text += text.length > 0 ? '<br />' : '';
434 if (g.showMarkHint && g.markHint &&
435 !g.showSortHint // we do not show mark hint, when sort hint is shown
437 text += text.length > 0 ? '<br />' : '';
440 if (g.showColVisibHint && g.colVisibHint) {
441 text += text.length > 0 ? '<br />' : '';
442 text += g.colVisibHint;
445 // hide the hint if no text and the event is mouseenter
447 g.qtip.disable(!text && e.type == 'mouseenter');
448 g.qtip.updateContent(text, false);
455 hideHint: function() {
458 g.qtip.disable(true);
463 * Toggle column's visibility.
464 * After calling this function and it returns true, afterToggleCol() must be called.
466 * @return boolean True if the column is toggled successfully.
468 toggleCol: function(n) {
470 // can hide if more than one column is visible
471 if (g.visibleHeadersCount > 1) {
472 $(g.t).find('tr').each(function() {
473 $(this).find('th.draggable:eq(' + n + '),' +
474 'td:eq(' + (g.actionSpan + n) + ')')
478 $(g.cList).find('.lDiv div:eq(' + n + ') input').removeAttr('checked');
480 // cannot hide, force the checkbox to stay checked
481 $(g.cList).find('.lDiv div:eq(' + n + ') input').attr('checked', 'checked');
484 } else { // column n is not visible
485 $(g.t).find('tr').each(function() {
486 $(this).find('th.draggable:eq(' + n + '),' +
487 'td:eq(' + (g.actionSpan + n) + ')')
491 $(g.cList).find('.lDiv div:eq(' + n + ') input').attr('checked', 'checked');
497 * This must be called if toggleCol() returns is true.
499 * This function is separated from toggleCol because, sometimes, we want to toggle
500 * some columns together at one time and do just one adjustment after it, e.g. in showAllColumns().
502 afterToggleCol: function() {
503 // some adjustments after hiding column
508 // check visible first row headers count
509 g.visibleHeadersCount = $(g.t).find('tr:first th.draggable:visible').length;
510 g.refreshRestoreButton();
514 * Show columns' visibility list.
516 * @param obj The drop down arrow of column visibility list
518 showColList: function(obj) {
519 // only show when not resizing or reordering
520 if (!g.colRsz && !g.colReorder) {
521 var pos = $(obj).position();
522 // check if the list position is too right
523 if (pos.left + $(g.cList).outerWidth(true) > $(document).width()) {
524 pos.left = $(document).width() - $(g.cList).outerWidth(true);
528 top: pos.top + $(obj).outerHeight(true)
531 $(obj).addClass('coldrop-hover');
536 * Hide columns' visibility list.
538 hideColList: function() {
540 $(g.cDrop).find('.coldrop-hover').removeClass('coldrop-hover');
544 * Reposition the column visibility drop-down arrow.
546 reposDrop: function() {
547 var $th = $(t).find('th:not(.draggable)');
548 for (var i = 0; i < $th.length; i++) {
549 var $cd = $(g.cDrop).find('div:eq(' + i + ')'); // column drop-down arrow
550 var pos = $($th[i]).position();
552 left: pos.left + $($th[i]).width() - $cd.width(),
559 * Show all hidden columns.
561 showAllColumns: function() {
562 for (var i = 0; i < g.colVisib.length; i++) {
563 if (!g.colVisib[i]) {
571 * Show edit cell, if it can be shown
573 * @param cell <td> element to be edited
575 showEditCell: function(cell) {
576 if ($(cell).is('.grid_edit') &&
577 !g.colRsz && !g.colReorder)
579 if (!g.isCellEditActive) {
581 // remove all edit area and hide it
582 $(g.cEdit).find('.edit_area').empty().hide();
583 // reposition the cEdit element
585 top: $cell.position().top,
586 left: $cell.position().left
591 width: $cell.outerWidth(),
592 height: $cell.outerHeight()
594 // fill the cell edit with text from <td>
595 var value = PMA_getCellValue(cell);
596 $(g.cEdit).find('.edit_box').val(value);
598 g.currentEditCell = cell;
599 $(g.cEdit).find('.edit_box').focus();
600 $(g.cEdit).find('*').removeAttr('disabled');
606 * Remove edit cell and the edit area, if it is shown.
608 * @param force Optional, force to hide edit cell without saving edited field.
609 * @param data Optional, data from the POST AJAX request to save the edited field
610 * or just specify "true", if we want to replace the edited field with the new value.
611 * @param field Optional, the edited <td>. If not specified, the function will
612 * use currently edited <td> from g.currentEditCell.
614 hideEditCell: function(force, data, field) {
615 if (g.isCellEditActive && !force) {
616 // cell is being edited, save or post the edited data
617 g.saveOrPostEditedCell();
621 // cancel any previous request
622 if (g.lastXHR != null) {
628 if (g.currentEditCell) { // save value of currently edited cell
629 // replace current edited field with the new value
630 var $this_field = $(g.currentEditCell);
631 var is_null = $this_field.data('value') == null;
633 $this_field.find('span').html('NULL');
634 $this_field.addClass('null');
636 $this_field.removeClass('null');
637 var new_html = $this_field.data('value');
638 if ($this_field.is('.truncated')) {
639 if (new_html.length > g.maxTruncatedLen) {
640 new_html = new_html.substring(0, g.maxTruncatedLen) + '...';
643 $this_field.find('span').text(new_html);
646 if (data.transformations != undefined) {
647 $.each(data.transformations, function(cell_index, value) {
648 var $this_field = $(g.t).find('.to_be_saved:eq(' + cell_index + ')');
649 $this_field.find('span').html(value);
652 if (data.relations != undefined) {
653 $.each(data.relations, function(cell_index, value) {
654 var $this_field = $(g.t).find('.to_be_saved:eq(' + cell_index + ')');
655 $this_field.find('span').html(value);
664 // hide the cell editing area
666 $(g.cEdit).find('.edit_box').blur();
667 g.isCellEditActive = false;
668 g.currentEditCell = null;
669 // destroy datepicker in edit area, if exist
670 var $dp = $(g.cEdit).find('.hasDatepicker');
671 if ($dp.length > 0) {
672 $dp.datepicker('destroy');
673 // change the cursor in edit box back to normal
674 // (the cursor become a hand pointer when we add datepicker)
675 $(g.cEdit).find('.edit_box').css('cursor', 'inherit');
680 * Show drop-down edit area when edit cell is focused.
682 showEditArea: function() {
683 if (!g.isCellEditActive) { // make sure the edit area has not been shown
684 g.isCellEditActive = true;
685 g.isEditCellTextEditable = false;
687 * @var $td current edited cell
689 var $td = $(g.currentEditCell);
691 * @var $editArea the editing area
693 var $editArea = $(g.cEdit).find('.edit_area');
695 * @var where_clause WHERE clause for the edited cell
697 var where_clause = $td.parent('tr').find('.where_clause').val();
699 * @var field_name String containing the name of this field.
700 * @see getFieldName()
702 var field_name = getFieldName($td);
704 * @var relation_curr_value String current value of the field (for fields that are foreign keyed).
706 var relation_curr_value = $td.text();
708 * @var relation_key_or_display_column String relational key if in 'Relational display column' mode,
709 * relational display column if in 'Relational key' mode (for fields that are foreign keyed).
711 var relation_key_or_display_column = $td.find('a').attr('title');
713 * @var curr_value String current value of the field (for fields that are of type enum or set).
715 var curr_value = $td.find('span').text();
717 // empty all edit area, then rebuild it based on $td classes
720 // add goto link, if this cell contains a link
721 if ($td.find('a').length > 0) {
722 var gotoLink = document.createElement('div');
723 gotoLink.className = 'goto_link';
724 $(gotoLink).append(g.gotoLinkText + ': ')
725 .append($td.find('a').clone());
726 $editArea.append(gotoLink);
729 g.wasEditedCellNull = false;
730 if ($td.is(':not(.not_null)')) {
731 // append a null checkbox
732 $editArea.append('<div class="null_div">Null :<input type="checkbox"></div>');
733 var $checkbox = $editArea.find('.null_div input');
734 // check if current <td> is NULL
735 if ($td.is('.null')) {
736 $checkbox.attr('checked', true);
737 g.wasEditedCellNull = true;
740 // if the select/editor is changed un-check the 'checkbox_null_<field_name>_<row_index>'.
741 if ($td.is('.enum, .set')) {
742 $editArea.find('select').live('change', function(e) {
743 $checkbox.attr('checked', false);
745 } else if ($td.is('.relation')) {
746 $editArea.find('select').live('change', function(e) {
747 $checkbox.attr('checked', false);
749 $editArea.find('.browse_foreign').live('click', function(e) {
750 $checkbox.attr('checked', false);
753 $(g.cEdit).find('.edit_box').live('keypress change', function(e) {
754 $checkbox.attr('checked', false);
756 $editArea.find('textarea').live('keydown', function(e) {
757 $checkbox.attr('checked', false);
761 // if null checkbox is clicked empty the corresponding select/editor.
762 $checkbox.click(function(e) {
763 if ($td.is('.enum')) {
764 $editArea.find('select').attr('value', '');
765 } else if ($td.is('.set')) {
766 $editArea.find('select').find('option').each(function() {
767 var $option = $(this);
768 $option.attr('selected', false);
770 } else if ($td.is('.relation')) {
771 // if the dropdown is there to select the foreign value
772 if ($editArea.find('select').length > 0) {
773 $editArea.find('select').attr('value', '');
776 $editArea.find('textarea').val('');
778 $(g.cEdit).find('.edit_box').val('');
782 if ($td.is('.relation')) {
784 $editArea.addClass('edit_area_loading');
786 // initialize the original data
787 $td.data('original_data', null);
790 * @var post_params Object containing parameters for the POST request
793 'ajax_request' : true,
794 'get_relational_values' : true,
798 'column' : field_name,
800 'curr_value' : relation_curr_value,
801 'relation_key_or_display_column' : relation_key_or_display_column
804 g.lastXHR = $.post('sql.php', post_params, function(data) {
806 $editArea.removeClass('edit_area_loading');
807 if ($(data.dropdown).is('select')) {
808 // save original_data
809 var value = $(data.dropdown).val();
810 $td.data('original_data', value);
811 // update the text input field, in case where the "Relational display column" is checked
812 $(g.cEdit).find('.edit_box').val(value);
815 $editArea.append(data.dropdown);
816 $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
820 $editArea.find('select').live('change', function(e) {
821 $(g.cEdit).find('.edit_box').val($(this).val());
824 else if($td.is('.enum')) {
826 $editArea.addClass('edit_area_loading');
829 * @var post_params Object containing parameters for the POST request
832 'ajax_request' : true,
833 'get_enum_values' : true,
837 'column' : field_name,
839 'curr_value' : curr_value
841 g.lastXHR = $.post('sql.php', post_params, function(data) {
843 $editArea.removeClass('edit_area_loading');
844 $editArea.append(data.dropdown);
845 $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
849 $editArea.find('select').live('change', function(e) {
850 $(g.cEdit).find('.edit_box').val($(this).val());
853 else if($td.is('.set')) {
855 $editArea.addClass('edit_area_loading');
858 * @var post_params Object containing parameters for the POST request
861 'ajax_request' : true,
862 'get_set_values' : true,
866 'column' : field_name,
868 'curr_value' : curr_value
871 g.lastXHR = $.post('sql.php', post_params, function(data) {
873 $editArea.removeClass('edit_area_loading');
874 $editArea.append(data.select);
875 $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
879 $editArea.find('select').live('change', function(e) {
880 $(g.cEdit).find('.edit_box').val($(this).val());
883 else if($td.is('.truncated, .transformed')) {
884 if ($td.is('.to_be_saved')) { // cell has been edited
885 var value = $td.data('value');
886 $(g.cEdit).find('.edit_box').val(value);
887 $editArea.append('<textarea></textarea>');
888 $editArea.find('textarea')
890 .live('keyup', function(e) {
891 $(g.cEdit).find('.edit_box').val($(this).val());
893 $(g.cEdit).find('.edit_box').live('keyup', function(e) {
894 $editArea.find('textarea').val($(this).val());
896 $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
898 //handle truncated/transformed values values
899 $editArea.addClass('edit_area_loading');
901 // initialize the original data
902 $td.data('original_data', null);
905 * @var sql_query String containing the SQL query used to retrieve value of truncated/transformed data
907 var sql_query = 'SELECT `' + field_name + '` FROM `' + g.table + '` WHERE ' + PMA_urldecode(where_clause);
909 // Make the Ajax call and get the data, wrap it and insert it
910 g.lastXHR = $.post('sql.php', {
914 'ajax_request' : true,
915 'sql_query' : sql_query,
919 $editArea.removeClass('edit_area_loading');
920 if(data.success == true) {
921 if ($td.is('.truncated')) {
922 // get the truncated data length
923 g.maxTruncatedLen = $(g.currentEditCell).text().length - 3;
926 $td.data('original_data', data.value);
927 $(g.cEdit).find('.edit_box').val(data.value);
928 $editArea.append('<textarea></textarea>');
929 $editArea.find('textarea')
931 .live('keyup', function(e) {
932 $(g.cEdit).find('.edit_box').val($(this).val());
934 $(g.cEdit).find('.edit_box').live('keyup', function(e) {
935 $editArea.find('textarea').val($(this).val());
937 $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
940 PMA_ajaxShowMessage(data.error, false);
945 g.isEditCellTextEditable = true;
946 } else if ($td.is('.datefield, .datetimefield, .timestampfield')) {
947 var $input_field = $(g.cEdit).find('.edit_box');
949 // remember current datetime value in $input_field, if it is not null
950 var is_null = $td.is('.null');
951 var current_datetime_value = !is_null ? $input_field.val() : '';
953 var showTimeOption = true;
954 if ($td.is('.datefield')) {
955 showTimeOption = false;
957 PMA_addDatepicker($editArea, {
958 altField: $input_field,
959 showTimepicker: showTimeOption,
960 onSelect: function(dateText, inst) {
961 // remove null checkbox if it exists
962 $(g.cEdit).find('.null_div input[type=checkbox]').attr('checked', false);
966 // cancel any click on the datepicker element
967 $editArea.find('> *').click(function(e) {
971 // force to restore modified $input_field value after adding datepicker
972 // (after adding a datepicker, the input field doesn't display the time anymore, only the date)
974 $editArea.datetimepicker('setDate', current_datetime_value);
976 $input_field.val('');
978 $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
980 g.isEditCellTextEditable = true;
981 // only append edit area hint if there is a null checkbox
982 if ($editArea.children().length > 0) {
983 $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
986 if ($editArea.children().length > 0) {
993 * Post the content of edited cell.
995 postEditedCell: function() {
1002 * @var relation_fields Array containing the name/value pairs of relational fields
1004 var relation_fields = {};
1006 * @var relational_display string 'K' if relational key, 'D' if relational display column
1008 var relational_display = $("#relational_display_K").attr('checked') ? 'K' : 'D';
1010 * @var transform_fields Array containing the name/value pairs for transformed fields
1012 var transform_fields = {};
1014 * @var transformation_fields Boolean, if there are any transformed fields in the edited cells
1016 var transformation_fields = false;
1018 * @var full_sql_query String containing the complete SQL query to update this table
1020 var full_sql_query = '';
1022 * @var rel_fields_list String, url encoded representation of {@link relations_fields}
1024 var rel_fields_list = '';
1026 * @var transform_fields_list String, url encoded representation of {@link transform_fields}
1028 var transform_fields_list = '';
1030 * @var where_clause Array containing where clause for updated fields
1032 var full_where_clause = Array();
1034 * @var is_unique Boolean, whether the rows in this table is unique or not
1036 var is_unique = $('.edit_row_anchor').is('.nonunique') ? 0 : 1;
1038 * multi edit variables
1040 var me_fields_name = Array();
1041 var me_fields = Array();
1042 var me_fields_null = Array();
1044 // alert user if edited table is not unique
1046 alert(g.alertNonUnique);
1049 // loop each edited row
1050 $('.to_be_saved').parents('tr').each(function() {
1052 var where_clause = $tr.find('.where_clause').val();
1053 full_where_clause.push(PMA_urldecode(where_clause));
1054 var condition_array = jQuery.parseJSON($tr.find('.condition_array').val());
1057 * multi edit variables, for current row
1058 * @TODO array indices are still not correct, they should be md5 of field's name
1060 var fields_name = Array();
1061 var fields = Array();
1062 var fields_null = Array();
1064 // loop each edited cell in a row
1065 $tr.find('.to_be_saved').each(function() {
1067 * @var $this_field Object referring to the td that is being edited
1069 var $this_field = $(this);
1072 * @var field_name String containing the name of this field.
1073 * @see getFieldName()
1075 var field_name = getFieldName($this_field);
1078 * @var this_field_params Array temporary storage for the name/value of current field
1080 var this_field_params = {};
1082 if($this_field.is('.transformed')) {
1083 transformation_fields = true;
1085 this_field_params[field_name] = $this_field.data('value');
1088 * @var is_null String capturing whether 'checkbox_null_<field_name>_<row_index>' is checked.
1090 var is_null = this_field_params[field_name] === null;
1092 fields_name.push(field_name);
1095 fields_null.push('on');
1098 fields_null.push('');
1099 fields.push($this_field.data('value'));
1101 var cell_index = $this_field.index('.to_be_saved');
1102 if($this_field.is(":not(.relation, .enum, .set, .bit)")) {
1103 if($this_field.is('.transformed')) {
1104 transform_fields[cell_index] = {};
1105 $.extend(transform_fields[cell_index], this_field_params);
1107 } else if($this_field.is('.relation')) {
1108 relation_fields[cell_index] = {};
1109 $.extend(relation_fields[cell_index], this_field_params);
1112 // check if edited field appears in WHERE clause
1113 if (where_clause.indexOf(PMA_urlencode(field_name)) > -1) {
1114 var field_str = '`' + g.table + '`.' + '`' + field_name + '`';
1115 for (var field in condition_array) {
1116 if (field.indexOf(field_str) > -1) {
1117 condition_array[field] = is_null ? 'IS NULL' : "= '" + this_field_params[field_name].replace(/'/g,"''") + "'";
1123 }); // end of loop for every edited cells in a row
1126 var new_clause = '';
1127 for (var field in condition_array) {
1128 new_clause += field + ' ' + condition_array[field] + ' AND ';
1130 new_clause = new_clause.substring(0, new_clause.length - 5); // remove the last AND
1131 new_clause = PMA_urlencode(new_clause);
1132 $tr.data('new_clause', new_clause);
1133 // save condition_array
1134 $tr.find('.condition_array').val(JSON.stringify(condition_array));
1136 me_fields_name.push(fields_name);
1137 me_fields.push(fields);
1138 me_fields_null.push(fields_null);
1140 }); // end of loop for every edited rows
1142 rel_fields_list = $.param(relation_fields);
1143 transform_fields_list = $.param(transform_fields);
1145 // Make the Ajax post after setting all parameters
1147 * @var post_params Object containing parameters for the POST request
1149 var post_params = {'ajax_request' : true,
1150 'sql_query' : full_sql_query,
1152 'server' : g.server,
1155 'clause_is_unique' : is_unique,
1156 'where_clause' : full_where_clause,
1157 'fields[multi_edit]' : me_fields,
1158 'fields_name[multi_edit]' : me_fields_name,
1159 'fields_null[multi_edit]' : me_fields_null,
1160 'rel_fields_list' : rel_fields_list,
1161 'do_transformations' : transformation_fields,
1162 'transform_fields_list' : transform_fields_list,
1163 'relational_display' : relational_display,
1165 'submit_type' : 'save'
1168 if (!g.saveCellsAtOnce) {
1169 $(g.cEdit).find('*').attr('disabled', 'disabled');
1170 var $editArea = $(g.cEdit).find('.edit_area');
1171 $(g.cEdit).find('.edit_box').addClass('edit_box_posting');
1173 $('.save_edited').addClass('saving_edited_data')
1174 .find('input').attr('disabled', 'disabled'); // disable the save button
1179 url: 'tbl_replace.php',
1184 if (!g.saveCellsAtOnce) {
1185 $(g.cEdit).find('*').removeAttr('disabled');
1186 $(g.cEdit).find('.edit_box').removeClass('edit_box_posting');
1188 $('.save_edited').removeClass('saving_edited_data')
1189 .find('input').removeAttr('disabled'); // enable the save button back
1191 if(data.success == true) {
1192 PMA_ajaxShowMessage(data.message);
1193 // update where_clause related data in each edited row
1194 $('.to_be_saved').parents('tr').each(function() {
1195 var new_clause = $(this).data('new_clause');
1196 var $where_clause = $(this).find('.where_clause');
1197 var old_clause = $where_clause.attr('value');
1198 var decoded_old_clause = PMA_urldecode(old_clause);
1199 var decoded_new_clause = PMA_urldecode(new_clause);
1201 $where_clause.attr('value', new_clause);
1202 // update Edit, Copy, and Delete links also
1203 $(this).find('a').each(function() {
1204 $(this).attr('href', $(this).attr('href').replace(old_clause, new_clause));
1205 // update delete confirmation in Delete link
1206 if ($(this).attr('href').indexOf('DELETE') > -1) {
1207 $(this).removeAttr('onclick')
1209 .bind('click', function() {
1210 return confirmLink(this, 'DELETE FROM `' + g.db + '`.`' + g.table + '` WHERE ' +
1211 decoded_new_clause + (is_unique ? '' : ' LIMIT 1'));
1215 // update the multi edit checkboxes
1216 $(this).find('input[type=checkbox]').each(function() {
1217 var $checkbox = $(this);
1218 var checkbox_name = $checkbox.attr('name');
1219 var checkbox_value = $checkbox.attr('value');
1221 $checkbox.attr('name', checkbox_name.replace(old_clause, new_clause));
1222 $checkbox.attr('value', checkbox_value.replace(decoded_old_clause, decoded_new_clause));
1225 // update the display of executed SQL query command
1226 $('#result_query').remove();
1227 if (typeof data.sql_query != 'undefined') {
1229 $('#sqlqueryresults').prepend(data.sql_query);
1231 // hide and/or update the successfully saved cells
1232 g.hideEditCell(true, data);
1234 // remove the "Save edited cells" button
1235 $('.save_edited').hide();
1236 // update saved fields
1237 $(g.t).find('.to_be_saved')
1238 .removeClass('to_be_saved')
1239 .data('value', null)
1240 .data('original_data', null);
1242 g.isCellEdited = false;
1244 PMA_ajaxShowMessage(data.error, false);
1251 * Save edited cell, so it can be posted later.
1253 saveEditedCell: function() {
1255 * @var $this_field Object referring to the td that is being edited
1257 var $this_field = $(g.currentEditCell);
1258 var $test_element = ''; // to test the presence of a element
1260 var need_to_post = false;
1263 * @var field_name String containing the name of this field.
1264 * @see getFieldName()
1266 var field_name = getFieldName($this_field);
1269 * @var this_field_params Array temporary storage for the name/value of current field
1271 var this_field_params = {};
1274 * @var is_null String capturing whether 'checkbox_null_<field_name>_<row_index>' is checked.
1276 var is_null = $(g.cEdit).find('input:checkbox').is(':checked');
1279 if ($(g.cEdit).find('.edit_area').is('.edit_area_loading')) {
1280 // the edit area is still loading (retrieving cell data), no need to post
1281 need_to_post = false;
1282 } else if (is_null) {
1283 if (!g.wasEditedCellNull) {
1284 this_field_params[field_name] = null;
1285 need_to_post = true;
1288 if ($this_field.is('.bit')) {
1289 this_field_params[field_name] = '0b' + $(g.cEdit).find('.edit_box').val();
1290 } else if ($this_field.is('.set')) {
1291 $test_element = $(g.cEdit).find('select');
1292 this_field_params[field_name] = $test_element.map(function(){
1293 return $(this).val();
1295 } else if ($this_field.is('.relation, .enum')) {
1296 // results from a drop-down
1297 $test_element = $(g.cEdit).find('select');
1298 if ($test_element.length != 0) {
1299 this_field_params[field_name] = $test_element.val();
1302 // results from Browse foreign value
1303 $test_element = $(g.cEdit).find('span.curr_value');
1304 if ($test_element.length != 0) {
1305 this_field_params[field_name] = $test_element.text();
1308 this_field_params[field_name] = $(g.cEdit).find('.edit_box').val();
1310 if (g.wasEditedCellNull || this_field_params[field_name] != PMA_getCellValue(g.currentEditCell)) {
1311 need_to_post = true;
1316 $(g.currentEditCell).addClass('to_be_saved')
1317 .data('value', this_field_params[field_name]);
1318 if (g.saveCellsAtOnce) {
1319 $('.save_edited').show();
1321 g.isCellEdited = true;
1324 return need_to_post;
1328 * Save or post currently edited cell, depending on the "saveCellsAtOnce" configuration.
1330 saveOrPostEditedCell: function() {
1331 var saved = g.saveEditedCell();
1332 if (!g.saveCellsAtOnce) {
1336 g.hideEditCell(true);
1340 g.hideEditCell(true, true);
1342 g.hideEditCell(true);
1348 * Initialize column resize feature.
1350 initColResize: function() {
1351 // create column resizer div
1352 g.cRsz = document.createElement('div');
1353 g.cRsz.className = 'cRsz';
1355 // get data columns in the first row of the table
1356 var $firstRowCols = $(g.t).find('tr:first th.draggable');
1358 // create column borders
1359 $firstRowCols.each(function() {
1360 var cb = document.createElement('div'); // column border
1361 $(cb).addClass('colborder')
1362 .mousedown(function(e) {
1363 g.dragStartRsz(e, this);
1365 $(g.cRsz).append(cb);
1369 // attach to global div
1370 $(g.gDiv).prepend(g.cRsz);
1374 * Initialize column reordering feature.
1376 initColReorder: function() {
1377 g.cCpy = document.createElement('div'); // column copy, to store copy of dragged column header
1378 g.cPointer = document.createElement('div'); // column pointer, used when reordering column
1381 g.cCpy.className = 'cCpy';
1384 // adjust g.cPointer
1385 g.cPointer.className = 'cPointer';
1386 $(g.cPointer).css('visibility', 'hidden'); // set visibility to hidden instead of calling hide() to force browsers to cache the image in cPointer class
1388 // assign column reordering hint
1389 g.reorderHint = PMA_messages['strColOrderHint'];
1391 // get data columns in the first row of the table
1392 var $firstRowCols = $(g.t).find('tr:first th.draggable');
1394 // initialize column order
1395 $col_order = $('#col_order'); // check if column order is passed from PHP
1396 if ($col_order.length > 0) {
1397 g.colOrder = $col_order.val().split(',');
1398 for (var i = 0; i < g.colOrder.length; i++) {
1399 g.colOrder[i] = parseInt(g.colOrder[i]);
1402 g.colOrder = new Array();
1403 for (var i = 0; i < $firstRowCols.length; i++) {
1409 $(t).find('th.draggable')
1410 .mousedown(function(e) {
1411 if (g.visibleHeadersCount > 1) {
1412 g.dragStartReorder(e, this);
1415 .mouseenter(function(e) {
1416 if (g.visibleHeadersCount > 1) {
1417 g.showReorderHint = true;
1418 $(this).css('cursor', 'move');
1420 $(this).css('cursor', 'inherit');
1423 .mouseleave(function(e) {
1424 g.showReorderHint = false;
1426 // restore column order when the restore button is clicked
1427 $('.restore_column').click(function() {
1428 g.restoreColOrder();
1431 // attach to global div
1432 $(g.gDiv).append(g.cPointer);
1433 $(g.gDiv).append(g.cCpy);
1435 // prevent default "dragstart" event when dragging a link
1436 $(t).find('th a').bind('dragstart', function() {
1440 // refresh the restore column button state
1441 g.refreshRestoreButton();
1445 * Initialize column visibility feature.
1447 initColVisib: function() {
1448 g.cDrop = document.createElement('div'); // column drop-down arrows
1449 g.cList = document.createElement('div'); // column visibility list
1452 g.cDrop.className = 'cDrop';
1455 g.cList.className = 'cList';
1458 // assign column visibility related hints
1459 g.colVisibHint = PMA_messages['strColVisibHint'];
1460 g.showAllColText = PMA_messages['strShowAllCol'];
1462 // get data columns in the first row of the table
1463 var $firstRowCols = $(g.t).find('tr:first th.draggable');
1465 // initialize column visibility
1466 var $col_visib = $('#col_visib'); // check if column visibility is passed from PHP
1467 if ($col_visib.length > 0) {
1468 g.colVisib = $col_visib.val().split(',');
1469 for (var i = 0; i < g.colVisib.length; i++) {
1470 g.colVisib[i] = parseInt(g.colVisib[i]);
1473 g.colVisib = new Array();
1474 for (var i = 0; i < $firstRowCols.length; i++) {
1479 // make sure we have more than one column
1480 if ($firstRowCols.length > 1) {
1481 var $colVisibTh = $(g.t).find('th:not(.draggable)');
1482 PMA_createqTip($colVisibTh);
1484 // create column visibility drop-down arrow(s)
1485 $colVisibTh.each(function() {
1487 var cd = document.createElement('div'); // column drop-down arrow
1488 var pos = $th.position();
1489 $(cd).addClass('coldrop')
1491 if (g.cList.style.display == 'none') {
1492 g.showColList(this);
1497 $(g.cDrop).append(cd);
1499 .mouseenter(function(e) {
1500 g.showColVisibHint = true;
1502 .mouseleave(function(e) {
1503 g.showColVisibHint = false;
1506 // add column visibility control
1507 g.cList.innerHTML = '<div class="lDiv"></div>';
1508 var $listDiv = $(g.cList).find('div');
1509 for (var i = 0; i < $firstRowCols.length; i++) {
1510 var currHeader = $firstRowCols[i];
1511 var listElmt = document.createElement('div');
1512 $(listElmt).text($(currHeader).text())
1513 .prepend('<input type="checkbox" ' + (g.colVisib[i] ? 'checked="checked" ' : '') + '/>');
1514 $listDiv.append(listElmt);
1515 // add event on click
1516 $(listElmt).click(function() {
1517 if ( g.toggleCol($(this).index()) ) {
1522 // add "show all column" button
1523 var showAll = document.createElement('div');
1524 $(showAll).addClass('showAllColBtn')
1525 .text(g.showAllColText);
1526 $(g.cList).append(showAll);
1527 $(showAll).click(function() {
1530 // prepend "show all column" button at top if the list is too long
1531 if ($firstRowCols.length > 10) {
1532 var clone = showAll.cloneNode(true);
1533 $(g.cList).prepend(clone);
1534 $(clone).click(function() {
1540 // hide column visibility list if we move outside the list
1541 $(t).find('td, th.draggable').mouseenter(function() {
1545 // attach to global div
1546 $(g.gDiv).append(g.cDrop);
1547 $(g.gDiv).append(g.cList);
1554 * Initialize grid editing feature.
1556 initGridEdit: function() {
1557 // create cell edit wrapper element
1558 g.cEdit = document.createElement('div');
1561 g.cEdit.className = 'cEdit';
1562 $(g.cEdit).html('<textarea class="edit_box" rows="1" ></textarea><div class="edit_area" />');
1565 // assign cell editing hint
1566 g.cellEditHint = PMA_messages['strCellEditHint'];
1567 g.saveCellWarning = PMA_messages['strSaveCellWarning'];
1568 g.alertNonUnique = PMA_messages['strAlertNonUnique'];
1569 g.gotoLinkText = PMA_messages['strGoToLink'];
1571 // initialize cell editing configuration
1572 g.saveCellsAtOnce = $('#save_cells_at_once').val();
1575 $(t).find('td.data')
1576 .click(function(e) {
1577 if (g.isCellEditActive) {
1578 g.saveOrPostEditedCell();
1579 e.stopPropagation();
1581 g.showEditCell(this);
1582 e.stopPropagation();
1584 // prevent default action when clicking on "link" in a table
1585 if ($(e.target).is('a')) {
1589 $(g.cEdit).find('.edit_box').focus(function(e) {
1592 $(g.cEdit).find('.edit_box, select').live('keydown', function(e) {
1593 if (e.which == 13) {
1594 // post on pressing "Enter"
1596 g.saveOrPostEditedCell();
1599 $(g.cEdit).keydown(function(e) {
1600 if (!g.isEditCellTextEditable) {
1601 // prevent text editing
1605 $('html').click(function(e) {
1606 // hide edit cell if the click is not from g.cEdit
1607 if ($(e.target).parents().index(g.cEdit) == -1) {
1611 $('html').keydown(function(e) {
1612 if (e.which == 27 && g.isCellEditActive) {
1614 // cancel on pressing "Esc"
1615 g.hideEditCell(true);
1618 $('.save_edited').click(function() {
1622 $(window).bind('beforeunload', function(e) {
1623 if (g.isCellEdited) {
1624 return g.saveCellWarning;
1628 // attach to global div
1629 $(g.gDiv).append(g.cEdit);
1631 // add hint for grid editing feature when hovering "Edit" link in each table row
1632 PMA_createqTip($(g.t).find('.edit_row_anchor a'), PMA_messages['strGridEditFeatureHint']);
1640 // wrap all data cells, except actions cell, with span
1641 $(t).find('th, td:not(:has(span))')
1642 .wrapInner('<span />');
1644 // create grid elements
1645 g.gDiv = document.createElement('div'); // create global div
1647 // initialize the table variable
1650 // get data columns in the first row of the table
1651 var $firstRowCols = $(t).find('tr:first th.draggable');
1653 // initialize visible headers count
1654 g.visibleHeadersCount = $firstRowCols.filter(':visible').length;
1656 // assign first column (actions) span
1657 if (! $(t).find('tr:first th:first').hasClass('draggable')) { // action header exist
1658 g.actionSpan = $(t).find('tr:first th:first').prop('colspan');
1663 // assign table create time
1664 // #table_create_time will only available if we are in "Browse" tab
1665 g.tableCreateTime = $('#table_create_time').val();
1668 g.sortHint = PMA_messages['strSortHint'];
1669 g.markHint = PMA_messages['strColMarkHint'];
1671 // assign common hidden inputs
1672 var $common_hidden_inputs = $('.common_hidden_inputs');
1673 g.token = $common_hidden_inputs.find('input[name=token]').val();
1674 g.server = $common_hidden_inputs.find('input[name=server]').val();
1675 g.db = $common_hidden_inputs.find('input[name=db]').val();
1676 g.table = $common_hidden_inputs.find('input[name=table]').val();
1679 $(t).addClass('pma_table');
1681 // add relative position to global div so that resize handlers are correctly positioned
1682 $(g.gDiv).css('position', 'relative');
1684 // link the global div
1685 $(t).before(g.gDiv);
1686 $(g.gDiv).append(t);
1689 enableResize = enableResize == undefined ? true : enableResize;
1690 enableReorder = enableReorder == undefined ? true : enableReorder;
1691 enableVisib = enableVisib == undefined ? true : enableVisib;
1692 enableGridEdit = enableGridEdit == undefined ? true : enableGridEdit;
1696 if (enableReorder &&
1697 $('.navigation').length > 0) // disable reordering for result from EXPLAIN or SHOW syntax, which do not have a table navigation panel
1704 if (enableGridEdit &&
1705 $(t).is('.ajax')) // make sure AjaxEnable is enabled in Settings
1710 // create qtip for each <th> with draggable class
1711 PMA_createqTip($(t).find('th.draggable'));
1713 // register events for hint tooltip
1714 $(t).find('th.draggable a')
1715 .attr('title', '') // hide default tooltip for sorting
1716 .mouseenter(function(e) {
1717 g.showSortHint = true;
1720 .mouseleave(function(e) {
1721 g.showSortHint = false;
1724 $(t).find('th.marker')
1725 .mouseenter(function(e) {
1726 g.showMarkHint = true;
1728 .mouseleave(function(e) {
1729 g.showMarkHint = false;
1731 // register events for dragging-related feature
1732 if (enableResize || enableReorder) {
1733 $(document).mousemove(function(e) {
1736 $(document).mouseup(function(e) {
1741 // bind event to update currently hovered qtip API
1743 .mouseenter(function(e) {
1744 g.qtip = $(this).qtip('api');
1747 .mouseleave(function(e) {
1752 $(t).removeClass('data');
1753 $(g.gDiv).addClass('data');