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 // Capture ctrl+v (on IE and Chrome)
757 $(g.cEdit).find('.edit_box').live('keydown', function(e) {
758 if (e.ctrlKey && e.which == 86) {
759 $checkbox.prop('checked', false);
762 $editArea.find('textarea').live('keydown', function(e) {
763 $checkbox.attr('checked', false);
767 // if null checkbox is clicked empty the corresponding select/editor.
768 $checkbox.click(function(e) {
769 if ($td.is('.enum')) {
770 $editArea.find('select').attr('value', '');
771 } else if ($td.is('.set')) {
772 $editArea.find('select').find('option').each(function() {
773 var $option = $(this);
774 $option.attr('selected', false);
776 } else if ($td.is('.relation')) {
777 // if the dropdown is there to select the foreign value
778 if ($editArea.find('select').length > 0) {
779 $editArea.find('select').attr('value', '');
782 $editArea.find('textarea').val('');
784 $(g.cEdit).find('.edit_box').val('');
788 if ($td.is('.relation')) {
790 $editArea.addClass('edit_area_loading');
792 // initialize the original data
793 $td.data('original_data', null);
796 * @var post_params Object containing parameters for the POST request
799 'ajax_request' : true,
800 'get_relational_values' : true,
804 'column' : field_name,
806 'curr_value' : relation_curr_value,
807 'relation_key_or_display_column' : relation_key_or_display_column
810 g.lastXHR = $.post('sql.php', post_params, function(data) {
812 $editArea.removeClass('edit_area_loading');
813 if ($(data.dropdown).is('select')) {
814 // save original_data
815 var value = $(data.dropdown).val();
816 $td.data('original_data', value);
817 // update the text input field, in case where the "Relational display column" is checked
818 $(g.cEdit).find('.edit_box').val(value);
821 $editArea.append(data.dropdown);
822 $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
826 $editArea.find('select').live('change', function(e) {
827 $(g.cEdit).find('.edit_box').val($(this).val());
830 else if($td.is('.enum')) {
832 $editArea.addClass('edit_area_loading');
835 * @var post_params Object containing parameters for the POST request
838 'ajax_request' : true,
839 'get_enum_values' : true,
843 'column' : field_name,
845 'curr_value' : curr_value
847 g.lastXHR = $.post('sql.php', post_params, function(data) {
849 $editArea.removeClass('edit_area_loading');
850 $editArea.append(data.dropdown);
851 $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
855 $editArea.find('select').live('change', function(e) {
856 $(g.cEdit).find('.edit_box').val($(this).val());
859 else if($td.is('.set')) {
861 $editArea.addClass('edit_area_loading');
864 * @var post_params Object containing parameters for the POST request
867 'ajax_request' : true,
868 'get_set_values' : true,
872 'column' : field_name,
874 'curr_value' : curr_value
877 g.lastXHR = $.post('sql.php', post_params, function(data) {
879 $editArea.removeClass('edit_area_loading');
880 $editArea.append(data.select);
881 $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
885 $editArea.find('select').live('change', function(e) {
886 $(g.cEdit).find('.edit_box').val($(this).val());
889 else if($td.is('.truncated, .transformed')) {
890 if ($td.is('.to_be_saved')) { // cell has been edited
891 var value = $td.data('value');
892 $(g.cEdit).find('.edit_box').val(value);
893 $editArea.append('<textarea></textarea>');
894 $editArea.find('textarea')
896 .live('keyup', function(e) {
897 $(g.cEdit).find('.edit_box').val($(this).val());
899 $(g.cEdit).find('.edit_box').live('keyup', function(e) {
900 $editArea.find('textarea').val($(this).val());
902 $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
904 //handle truncated/transformed values values
905 $editArea.addClass('edit_area_loading');
907 // initialize the original data
908 $td.data('original_data', null);
911 * @var sql_query String containing the SQL query used to retrieve value of truncated/transformed data
913 var sql_query = 'SELECT `' + field_name + '` FROM `' + g.table + '` WHERE ' + PMA_urldecode(where_clause);
915 // Make the Ajax call and get the data, wrap it and insert it
916 g.lastXHR = $.post('sql.php', {
920 'ajax_request' : true,
921 'sql_query' : sql_query,
925 $editArea.removeClass('edit_area_loading');
926 if(data.success == true) {
927 if ($td.is('.truncated')) {
928 // get the truncated data length
929 g.maxTruncatedLen = $(g.currentEditCell).text().length - 3;
932 $td.data('original_data', data.value);
933 $(g.cEdit).find('.edit_box').val(data.value);
934 $editArea.append('<textarea></textarea>');
935 $editArea.find('textarea')
937 .live('keyup', function(e) {
938 $(g.cEdit).find('.edit_box').val($(this).val());
940 $(g.cEdit).find('.edit_box').live('keyup', function(e) {
941 $editArea.find('textarea').val($(this).val());
943 $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
946 PMA_ajaxShowMessage(data.error, false);
951 g.isEditCellTextEditable = true;
952 } else if ($td.is('.datefield, .datetimefield, .timestampfield')) {
953 var $input_field = $(g.cEdit).find('.edit_box');
955 // remember current datetime value in $input_field, if it is not null
956 var is_null = $td.is('.null');
957 var current_datetime_value = !is_null ? $input_field.val() : '';
959 var showTimeOption = true;
960 if ($td.is('.datefield')) {
961 showTimeOption = false;
963 PMA_addDatepicker($editArea, {
964 altField: $input_field,
965 showTimepicker: showTimeOption,
966 onSelect: function(dateText, inst) {
967 // remove null checkbox if it exists
968 $(g.cEdit).find('.null_div input[type=checkbox]').attr('checked', false);
972 // cancel any click on the datepicker element
973 $editArea.find('> *').click(function(e) {
977 // force to restore modified $input_field value after adding datepicker
978 // (after adding a datepicker, the input field doesn't display the time anymore, only the date)
980 || current_datetime_value == '0000-00-00'
981 || current_datetime_value == '0000-00-00 00:00:00'
983 $input_field.val(current_datetime_value);
985 $editArea.datetimepicker('setDate', current_datetime_value);
987 $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
989 // remove {cursor: 'pointer'} added inside timepicker.js
990 $input_field.css('cursor', '');
991 // make the cell editable, so one can can bypass the timepicker
992 // and enter date/time value manually
993 g.isEditCellTextEditable = true;
995 g.isEditCellTextEditable = true;
996 // only append edit area hint if there is a null checkbox
997 if ($editArea.children().length > 0) {
998 $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
1001 if ($editArea.children().length > 0) {
1008 * Post the content of edited cell.
1010 postEditedCell: function() {
1017 * @var relation_fields Array containing the name/value pairs of relational fields
1019 var relation_fields = {};
1021 * @var relational_display string 'K' if relational key, 'D' if relational display column
1023 var relational_display = $("#relational_display_K").attr('checked') ? 'K' : 'D';
1025 * @var transform_fields Array containing the name/value pairs for transformed fields
1027 var transform_fields = {};
1029 * @var transformation_fields Boolean, if there are any transformed fields in the edited cells
1031 var transformation_fields = false;
1033 * @var full_sql_query String containing the complete SQL query to update this table
1035 var full_sql_query = '';
1037 * @var rel_fields_list String, url encoded representation of {@link relations_fields}
1039 var rel_fields_list = '';
1041 * @var transform_fields_list String, url encoded representation of {@link transform_fields}
1043 var transform_fields_list = '';
1045 * @var where_clause Array containing where clause for updated fields
1047 var full_where_clause = Array();
1049 * @var is_unique Boolean, whether the rows in this table is unique or not
1051 var is_unique = $('.edit_row_anchor').is('.nonunique') ? 0 : 1;
1053 * multi edit variables
1055 var me_fields_name = Array();
1056 var me_fields = Array();
1057 var me_fields_null = Array();
1059 // alert user if edited table is not unique
1061 alert(g.alertNonUnique);
1064 // loop each edited row
1065 $('.to_be_saved').parents('tr').each(function() {
1067 var where_clause = $tr.find('.where_clause').val();
1068 full_where_clause.push(PMA_urldecode(where_clause));
1069 var condition_array = jQuery.parseJSON($tr.find('.condition_array').val());
1072 * multi edit variables, for current row
1073 * @TODO array indices are still not correct, they should be md5 of field's name
1075 var fields_name = Array();
1076 var fields = Array();
1077 var fields_null = Array();
1079 // loop each edited cell in a row
1080 $tr.find('.to_be_saved').each(function() {
1082 * @var $this_field Object referring to the td that is being edited
1084 var $this_field = $(this);
1087 * @var field_name String containing the name of this field.
1088 * @see getFieldName()
1090 var field_name = getFieldName($this_field);
1093 * @var this_field_params Array temporary storage for the name/value of current field
1095 var this_field_params = {};
1097 if($this_field.is('.transformed')) {
1098 transformation_fields = true;
1100 this_field_params[field_name] = $this_field.data('value');
1103 * @var is_null String capturing whether 'checkbox_null_<field_name>_<row_index>' is checked.
1105 var is_null = this_field_params[field_name] === null;
1107 fields_name.push(field_name);
1110 fields_null.push('on');
1113 fields_null.push('');
1114 fields.push($this_field.data('value'));
1116 var cell_index = $this_field.index('.to_be_saved');
1117 if($this_field.is(":not(.relation, .enum, .set, .bit)")) {
1118 if($this_field.is('.transformed')) {
1119 transform_fields[cell_index] = {};
1120 $.extend(transform_fields[cell_index], this_field_params);
1122 } else if($this_field.is('.relation')) {
1123 relation_fields[cell_index] = {};
1124 $.extend(relation_fields[cell_index], this_field_params);
1127 // check if edited field appears in WHERE clause
1128 if (where_clause.indexOf(PMA_urlencode(field_name)) > -1) {
1129 var field_str = '`' + g.table + '`.' + '`' + field_name + '`';
1130 for (var field in condition_array) {
1131 if (field.indexOf(field_str) > -1) {
1132 condition_array[field] = is_null ? 'IS NULL' : "= '" + this_field_params[field_name].replace(/'/g,"''") + "'";
1138 }); // end of loop for every edited cells in a row
1141 var new_clause = '';
1142 for (var field in condition_array) {
1143 new_clause += field + ' ' + condition_array[field] + ' AND ';
1145 new_clause = new_clause.substring(0, new_clause.length - 5); // remove the last AND
1146 new_clause = PMA_urlencode(new_clause);
1147 $tr.data('new_clause', new_clause);
1148 // save condition_array
1149 $tr.find('.condition_array').val(JSON.stringify(condition_array));
1151 me_fields_name.push(fields_name);
1152 me_fields.push(fields);
1153 me_fields_null.push(fields_null);
1155 }); // end of loop for every edited rows
1157 rel_fields_list = $.param(relation_fields);
1158 transform_fields_list = $.param(transform_fields);
1160 // Make the Ajax post after setting all parameters
1162 * @var post_params Object containing parameters for the POST request
1164 var post_params = {'ajax_request' : true,
1165 'sql_query' : full_sql_query,
1167 'server' : g.server,
1170 'clause_is_unique' : is_unique,
1171 'where_clause' : full_where_clause,
1172 'fields[multi_edit]' : me_fields,
1173 'fields_name[multi_edit]' : me_fields_name,
1174 'fields_null[multi_edit]' : me_fields_null,
1175 'rel_fields_list' : rel_fields_list,
1176 'do_transformations' : transformation_fields,
1177 'transform_fields_list' : transform_fields_list,
1178 'relational_display' : relational_display,
1180 'submit_type' : 'save'
1183 if (!g.saveCellsAtOnce) {
1184 $(g.cEdit).find('*').attr('disabled', 'disabled');
1185 var $editArea = $(g.cEdit).find('.edit_area');
1186 $(g.cEdit).find('.edit_box').addClass('edit_box_posting');
1188 $('.save_edited').addClass('saving_edited_data')
1189 .find('input').attr('disabled', 'disabled'); // disable the save button
1194 url: 'tbl_replace.php',
1199 if (!g.saveCellsAtOnce) {
1200 $(g.cEdit).find('*').removeAttr('disabled');
1201 $(g.cEdit).find('.edit_box').removeClass('edit_box_posting');
1203 $('.save_edited').removeClass('saving_edited_data')
1204 .find('input').removeAttr('disabled'); // enable the save button back
1206 if(data.success == true) {
1207 PMA_ajaxShowMessage(data.message);
1208 // update where_clause related data in each edited row
1209 $('.to_be_saved').parents('tr').each(function() {
1210 var new_clause = $(this).data('new_clause');
1211 var $where_clause = $(this).find('.where_clause');
1212 var old_clause = $where_clause.attr('value');
1213 var decoded_old_clause = PMA_urldecode(old_clause);
1214 var decoded_new_clause = PMA_urldecode(new_clause);
1216 $where_clause.attr('value', new_clause);
1217 // update Edit, Copy, and Delete links also
1218 $(this).find('a').each(function() {
1219 $(this).attr('href', $(this).attr('href').replace(old_clause, new_clause));
1220 // update delete confirmation in Delete link
1221 if ($(this).attr('href').indexOf('DELETE') > -1) {
1222 $(this).removeAttr('onclick')
1224 .bind('click', function() {
1225 return confirmLink(this, 'DELETE FROM `' + g.db + '`.`' + g.table + '` WHERE ' +
1226 decoded_new_clause + (is_unique ? '' : ' LIMIT 1'));
1230 // update the multi edit checkboxes
1231 $(this).find('input[type=checkbox]').each(function() {
1232 var $checkbox = $(this);
1233 var checkbox_name = $checkbox.attr('name');
1234 var checkbox_value = $checkbox.attr('value');
1236 $checkbox.attr('name', checkbox_name.replace(old_clause, new_clause));
1237 $checkbox.attr('value', checkbox_value.replace(decoded_old_clause, decoded_new_clause));
1240 // update the display of executed SQL query command
1241 $('#result_query').remove();
1242 if (typeof data.sql_query != 'undefined') {
1244 $('#sqlqueryresults').prepend(data.sql_query);
1246 // hide and/or update the successfully saved cells
1247 g.hideEditCell(true, data);
1249 // remove the "Save edited cells" button
1250 $('.save_edited').hide();
1251 // update saved fields
1252 $(g.t).find('.to_be_saved')
1253 .removeClass('to_be_saved')
1254 .data('value', null)
1255 .data('original_data', null);
1257 g.isCellEdited = false;
1259 PMA_ajaxShowMessage(data.error, false);
1266 * Save edited cell, so it can be posted later.
1268 saveEditedCell: function() {
1270 * @var $this_field Object referring to the td that is being edited
1272 var $this_field = $(g.currentEditCell);
1273 var $test_element = ''; // to test the presence of a element
1275 var need_to_post = false;
1278 * @var field_name String containing the name of this field.
1279 * @see getFieldName()
1281 var field_name = getFieldName($this_field);
1284 * @var this_field_params Array temporary storage for the name/value of current field
1286 var this_field_params = {};
1289 * @var is_null String capturing whether 'checkbox_null_<field_name>_<row_index>' is checked.
1291 var is_null = $(g.cEdit).find('input:checkbox').is(':checked');
1294 if ($(g.cEdit).find('.edit_area').is('.edit_area_loading')) {
1295 // the edit area is still loading (retrieving cell data), no need to post
1296 need_to_post = false;
1297 } else if (is_null) {
1298 if (!g.wasEditedCellNull) {
1299 this_field_params[field_name] = null;
1300 need_to_post = true;
1303 if ($this_field.is('.bit')) {
1304 this_field_params[field_name] = '0b' + $(g.cEdit).find('.edit_box').val();
1305 } else if ($this_field.is('.set')) {
1306 $test_element = $(g.cEdit).find('select');
1307 this_field_params[field_name] = $test_element.map(function(){
1308 return $(this).val();
1310 } else if ($this_field.is('.relation, .enum')) {
1311 // results from a drop-down
1312 $test_element = $(g.cEdit).find('select');
1313 if ($test_element.length != 0) {
1314 this_field_params[field_name] = $test_element.val();
1317 // results from Browse foreign value
1318 $test_element = $(g.cEdit).find('span.curr_value');
1319 if ($test_element.length != 0) {
1320 this_field_params[field_name] = $test_element.text();
1323 this_field_params[field_name] = $(g.cEdit).find('.edit_box').val();
1325 if (g.wasEditedCellNull || this_field_params[field_name] != PMA_getCellValue(g.currentEditCell)) {
1326 need_to_post = true;
1331 $(g.currentEditCell).addClass('to_be_saved')
1332 .data('value', this_field_params[field_name]);
1333 if (g.saveCellsAtOnce) {
1334 $('.save_edited').show();
1336 g.isCellEdited = true;
1339 return need_to_post;
1343 * Save or post currently edited cell, depending on the "saveCellsAtOnce" configuration.
1345 saveOrPostEditedCell: function() {
1346 var saved = g.saveEditedCell();
1347 if (!g.saveCellsAtOnce) {
1351 g.hideEditCell(true);
1355 g.hideEditCell(true, true);
1357 g.hideEditCell(true);
1363 * Initialize column resize feature.
1365 initColResize: function() {
1366 // create column resizer div
1367 g.cRsz = document.createElement('div');
1368 g.cRsz.className = 'cRsz';
1370 // get data columns in the first row of the table
1371 var $firstRowCols = $(g.t).find('tr:first th.draggable');
1373 // create column borders
1374 $firstRowCols.each(function() {
1375 var cb = document.createElement('div'); // column border
1376 $(cb).addClass('colborder')
1377 .mousedown(function(e) {
1378 g.dragStartRsz(e, this);
1380 $(g.cRsz).append(cb);
1384 // attach to global div
1385 $(g.gDiv).prepend(g.cRsz);
1389 * Initialize column reordering feature.
1391 initColReorder: function() {
1392 g.cCpy = document.createElement('div'); // column copy, to store copy of dragged column header
1393 g.cPointer = document.createElement('div'); // column pointer, used when reordering column
1396 g.cCpy.className = 'cCpy';
1399 // adjust g.cPointer
1400 g.cPointer.className = 'cPointer';
1401 $(g.cPointer).css('visibility', 'hidden'); // set visibility to hidden instead of calling hide() to force browsers to cache the image in cPointer class
1403 // assign column reordering hint
1404 g.reorderHint = PMA_messages['strColOrderHint'];
1406 // get data columns in the first row of the table
1407 var $firstRowCols = $(g.t).find('tr:first th.draggable');
1409 // initialize column order
1410 $col_order = $('#col_order'); // check if column order is passed from PHP
1411 if ($col_order.length > 0) {
1412 g.colOrder = $col_order.val().split(',');
1413 for (var i = 0; i < g.colOrder.length; i++) {
1414 g.colOrder[i] = parseInt(g.colOrder[i]);
1417 g.colOrder = new Array();
1418 for (var i = 0; i < $firstRowCols.length; i++) {
1424 $(t).find('th.draggable')
1425 .mousedown(function(e) {
1426 if (g.visibleHeadersCount > 1) {
1427 g.dragStartReorder(e, this);
1430 .mouseenter(function(e) {
1431 if (g.visibleHeadersCount > 1) {
1432 g.showReorderHint = true;
1433 $(this).css('cursor', 'move');
1435 $(this).css('cursor', 'inherit');
1438 .mouseleave(function(e) {
1439 g.showReorderHint = false;
1441 // restore column order when the restore button is clicked
1442 $('.restore_column').click(function() {
1443 g.restoreColOrder();
1446 // attach to global div
1447 $(g.gDiv).append(g.cPointer);
1448 $(g.gDiv).append(g.cCpy);
1450 // prevent default "dragstart" event when dragging a link
1451 $(t).find('th a').bind('dragstart', function() {
1455 // refresh the restore column button state
1456 g.refreshRestoreButton();
1460 * Initialize column visibility feature.
1462 initColVisib: function() {
1463 g.cDrop = document.createElement('div'); // column drop-down arrows
1464 g.cList = document.createElement('div'); // column visibility list
1467 g.cDrop.className = 'cDrop';
1470 g.cList.className = 'cList';
1473 // assign column visibility related hints
1474 g.colVisibHint = PMA_messages['strColVisibHint'];
1475 g.showAllColText = PMA_messages['strShowAllCol'];
1477 // get data columns in the first row of the table
1478 var $firstRowCols = $(g.t).find('tr:first th.draggable');
1480 // initialize column visibility
1481 var $col_visib = $('#col_visib'); // check if column visibility is passed from PHP
1482 if ($col_visib.length > 0) {
1483 g.colVisib = $col_visib.val().split(',');
1484 for (var i = 0; i < g.colVisib.length; i++) {
1485 g.colVisib[i] = parseInt(g.colVisib[i]);
1488 g.colVisib = new Array();
1489 for (var i = 0; i < $firstRowCols.length; i++) {
1494 // make sure we have more than one column
1495 if ($firstRowCols.length > 1) {
1496 var $colVisibTh = $(g.t).find('th:not(.draggable)');
1497 PMA_createqTip($colVisibTh);
1499 // create column visibility drop-down arrow(s)
1500 $colVisibTh.each(function() {
1502 var cd = document.createElement('div'); // column drop-down arrow
1503 var pos = $th.position();
1504 $(cd).addClass('coldrop')
1506 if (g.cList.style.display == 'none') {
1507 g.showColList(this);
1512 $(g.cDrop).append(cd);
1514 .mouseenter(function(e) {
1515 g.showColVisibHint = true;
1517 .mouseleave(function(e) {
1518 g.showColVisibHint = false;
1521 // add column visibility control
1522 g.cList.innerHTML = '<div class="lDiv"></div>';
1523 var $listDiv = $(g.cList).find('div');
1524 for (var i = 0; i < $firstRowCols.length; i++) {
1525 var currHeader = $firstRowCols[i];
1526 var listElmt = document.createElement('div');
1527 $(listElmt).text($(currHeader).text())
1528 .prepend('<input type="checkbox" ' + (g.colVisib[i] ? 'checked="checked" ' : '') + '/>');
1529 $listDiv.append(listElmt);
1530 // add event on click
1531 $(listElmt).click(function() {
1532 if ( g.toggleCol($(this).index()) ) {
1537 // add "show all column" button
1538 var showAll = document.createElement('div');
1539 $(showAll).addClass('showAllColBtn')
1540 .text(g.showAllColText);
1541 $(g.cList).append(showAll);
1542 $(showAll).click(function() {
1545 // prepend "show all column" button at top if the list is too long
1546 if ($firstRowCols.length > 10) {
1547 var clone = showAll.cloneNode(true);
1548 $(g.cList).prepend(clone);
1549 $(clone).click(function() {
1555 // hide column visibility list if we move outside the list
1556 $(t).find('td, th.draggable').mouseenter(function() {
1560 // attach to global div
1561 $(g.gDiv).append(g.cDrop);
1562 $(g.gDiv).append(g.cList);
1569 * Initialize grid editing feature.
1571 initGridEdit: function() {
1572 // create cell edit wrapper element
1573 g.cEdit = document.createElement('div');
1576 g.cEdit.className = 'cEdit';
1577 $(g.cEdit).html('<textarea class="edit_box" rows="1" ></textarea><div class="edit_area" />');
1580 // assign cell editing hint
1581 g.cellEditHint = PMA_messages['strCellEditHint'];
1582 g.saveCellWarning = PMA_messages['strSaveCellWarning'];
1583 g.alertNonUnique = PMA_messages['strAlertNonUnique'];
1584 g.gotoLinkText = PMA_messages['strGoToLink'];
1586 // initialize cell editing configuration
1587 g.saveCellsAtOnce = $('#save_cells_at_once').val();
1590 $(t).find('td.data')
1591 .click(function(e) {
1592 if (g.isCellEditActive) {
1593 g.saveOrPostEditedCell();
1594 e.stopPropagation();
1596 g.showEditCell(this);
1597 e.stopPropagation();
1599 // prevent default action when clicking on "link" in a table
1600 if ($(e.target).is('.grid_edit a')) {
1604 $(g.cEdit).find('.edit_box').focus(function(e) {
1607 $(g.cEdit).find('.edit_box, select').live('keydown', function(e) {
1608 if (e.which == 13) {
1609 // post on pressing "Enter"
1611 g.saveOrPostEditedCell();
1614 $(g.cEdit).keydown(function(e) {
1615 if (!g.isEditCellTextEditable) {
1616 // prevent text editing
1620 $('html').click(function(e) {
1621 // hide edit cell if the click is not from g.cEdit
1622 if ($(e.target).parents().index(g.cEdit) == -1) {
1626 $('html').keydown(function(e) {
1627 if (e.which == 27 && g.isCellEditActive) {
1629 // cancel on pressing "Esc"
1630 g.hideEditCell(true);
1633 $('.save_edited').click(function() {
1637 $(window).bind('beforeunload', function(e) {
1638 if (g.isCellEdited) {
1639 return g.saveCellWarning;
1643 // attach to global div
1644 $(g.gDiv).append(g.cEdit);
1646 // add hint for grid editing feature when hovering "Edit" link in each table row
1647 PMA_createqTip($(g.t).find('.edit_row_anchor a'), PMA_messages['strGridEditFeatureHint']);
1655 // wrap all data cells, except actions cell, with span
1656 $(t).find('th, td:not(:has(span))')
1657 .wrapInner('<span />');
1659 // create grid elements
1660 g.gDiv = document.createElement('div'); // create global div
1662 // initialize the table variable
1665 // get data columns in the first row of the table
1666 var $firstRowCols = $(t).find('tr:first th.draggable');
1668 // initialize visible headers count
1669 g.visibleHeadersCount = $firstRowCols.filter(':visible').length;
1671 // assign first column (actions) span
1672 if (! $(t).find('tr:first th:first').hasClass('draggable')) { // action header exist
1673 g.actionSpan = $(t).find('tr:first th:first').prop('colspan');
1678 // assign table create time
1679 // #table_create_time will only available if we are in "Browse" tab
1680 g.tableCreateTime = $('#table_create_time').val();
1683 g.sortHint = PMA_messages['strSortHint'];
1684 g.markHint = PMA_messages['strColMarkHint'];
1686 // assign common hidden inputs
1687 var $common_hidden_inputs = $('.common_hidden_inputs');
1688 g.token = $common_hidden_inputs.find('input[name=token]').val();
1689 g.server = $common_hidden_inputs.find('input[name=server]').val();
1690 g.db = $common_hidden_inputs.find('input[name=db]').val();
1691 g.table = $common_hidden_inputs.find('input[name=table]').val();
1694 $(t).addClass('pma_table');
1696 // add relative position to global div so that resize handlers are correctly positioned
1697 $(g.gDiv).css('position', 'relative');
1699 // link the global div
1700 $(t).before(g.gDiv);
1701 $(g.gDiv).append(t);
1704 enableResize = enableResize == undefined ? true : enableResize;
1705 enableReorder = enableReorder == undefined ? true : enableReorder;
1706 enableVisib = enableVisib == undefined ? true : enableVisib;
1707 enableGridEdit = enableGridEdit == undefined ? true : enableGridEdit;
1711 if (enableReorder &&
1712 $('.navigation').length > 0) // disable reordering for result from EXPLAIN or SHOW syntax, which do not have a table navigation panel
1719 if (enableGridEdit &&
1720 $(t).is('.ajax')) // make sure AjaxEnable is enabled in Settings
1725 // create qtip for each <th> with draggable class
1726 PMA_createqTip($(t).find('th.draggable'));
1728 // register events for hint tooltip
1729 $(t).find('th.draggable a')
1730 .attr('title', '') // hide default tooltip for sorting
1731 .mouseenter(function(e) {
1732 g.showSortHint = true;
1735 .mouseleave(function(e) {
1736 g.showSortHint = false;
1739 $(t).find('th.marker')
1740 .mouseenter(function(e) {
1741 g.showMarkHint = true;
1743 .mouseleave(function(e) {
1744 g.showMarkHint = false;
1746 // register events for dragging-related feature
1747 if (enableResize || enableReorder) {
1748 $(document).mousemove(function(e) {
1751 $(document).mouseup(function(e) {
1756 // bind event to update currently hovered qtip API
1758 .mouseenter(function(e) {
1759 g.qtip = $(this).qtip('api');
1762 .mouseleave(function(e) {
1767 $(t).removeClass('data');
1768 $(g.gDiv).addClass('data');