2 * Create advanced table (resize, reorder, and show/hide columns; and also grid editing).
3 * This function is designed mainly for table DOM generated from browsing a table in the database.
4 * For using this function in other table DOM, you may need to:
5 * - add "draggable" class in the table header <th>, in order to make it resizable, sortable or hidable
6 * - have at least one non-"draggable" header in the table DOM for placing column visibility drop-down arrow
7 * - pass the value "false" for the parameter "enableGridEdit"
8 * - adjust other parameter value, to select which features that will be enabled
10 * @param t the table DOM element
11 * @param enableResize Optional, if false, column resizing feature will be disabled
12 * @param enableReorder Optional, if false, column reordering feature will be disabled
13 * @param enableVisib Optional, if false, show/hide column feature will be disabled
14 * @param enableGridEdit Optional, if false, grid editing feature will be disabled
16 function PMA_makegrid(t, enableResize, enableReorder, enableVisib, enableGridEdit) {
25 * Variables, assigned with default value, changed later
27 actionSpan: 5, // number of colspan in Actions header in a table
28 tableCreateTime: null, // table creation time, used for saving column order and visibility to server, only available in "Browse tab"
30 // Column reordering variables
31 colOrder: new Array(), // array of column order
33 // Column visibility variables
34 colVisib: new Array(), // array of column visibility
35 showAllColText: '', // string, text for "show all" button under column visibility list
36 visibleHeadersCount: 0, // number of visible data headers
38 // Table hint variables
39 qtip: null, // qtip API
40 reorderHint: '', // string, hint for column reordering
41 sortHint: '', // string, hint for column sorting
42 markHint: '', // string, hint for column marking
43 colVisibHint: '', // string, hint for column visibility drop-down
44 showReorderHint: false,
47 showColVisibHint: false,
50 isCellEditActive: false, // true if current focus is in edit cell
51 isEditCellTextEditable: false, // true if current edit cell is editable in the text input box (not textarea)
52 currentEditCell: null, // reference to <td> that currently being edited
53 cellEditHint: '', // hint shown when doing grid edit
54 gotoLinkText: '', // "Go to link" text
55 wasEditedCellNull: false, // true if last value of the edited cell was NULL
56 maxTruncatedLen: 0, // number of characters that can be displayed in a cell
57 saveCellsAtOnce: false, // $cfg[saveCellsAtOnce]
58 isCellEdited: false, // true if at least one cell has been edited
59 saveCellWarning: '', // string, warning text when user want to leave a page with unsaved edited data
60 lastXHR : null, // last XHR object used in AJAX request
61 isSaving: false, // true when currently saving edited data, used to handle double posting caused by pressing ENTER in grid edit text box in Chrome browser
62 alertNonUnique: '', // string, alert shown when saving edited nonunique table
64 // Common hidden inputs
76 * Start to resize column. Called when clicking on column separator.
79 * @param obj dragged div object
81 dragStartRsz: function(e, obj) {
82 var n = $(g.cRsz).find('div').index(obj); // get the index of separator (i.e., column index)
87 objLeft: $(obj).position().left,
88 objWidth: $(g.t).find('th.draggable:visible:eq(' + n + ') span').outerWidth()
90 $('body').css('cursor', 'col-resize');
92 if (g.isCellEditActive) {
98 * Start to reorder column. Called when clicking on table header.
101 * @param obj table header object
103 dragStartReorder: function(e, obj) {
104 // prepare the cCpy (column copy) and cPointer (column pointer) from the dragged column
105 $(g.cCpy).text($(obj).text());
106 var objPos = $(obj).position();
108 top: objPos.top + 20,
110 height: $(obj).height(),
111 width: $(obj).width()
117 // get the column index, zero-based
118 var n = g.getHeaderIdx(obj);
130 $('body').css('cursor', 'move');
131 $('body').noSelect();
132 if (g.isCellEditActive) {
138 * Handle mousemove event when dragging.
142 dragMove: function(e) {
144 var dx = e.pageX - g.colRsz.x0;
145 if (g.colRsz.objWidth + dx > g.minColWidth) {
146 $(g.colRsz.obj).css('left', g.colRsz.objLeft + dx + 'px');
148 } else if (g.colReorder) {
149 // dragged column animation
150 var dx = e.pageX - g.colReorder.x0;
152 .css('left', g.colReorder.objLeft + dx)
156 var hoveredCol = g.getHoveredCol(e);
158 var newn = g.getHeaderIdx(hoveredCol);
159 g.colReorder.newn = newn;
160 if (newn != g.colReorder.n) {
161 // show the column pointer in the right place
162 var colPos = $(hoveredCol).position();
163 var newleft = newn < g.colReorder.n ?
165 colPos.left + $(hoveredCol).outerWidth();
169 visibility: 'visible'
172 // no movement to other column, hide the column pointer
173 $(g.cPointer).css('visibility', 'hidden');
180 * Stop the dragging action.
184 dragEnd: function(e) {
186 var dx = e.pageX - g.colRsz.x0;
187 var nw = g.colRsz.objWidth + dx;
188 if (nw < g.minColWidth) {
198 } else if (g.colReorder) {
200 if (g.colReorder.newn != g.colReorder.n) {
201 g.shiftCol(g.colReorder.n, g.colReorder.newn);
202 // assign new position
203 var objPos = $(g.colReorder.obj).position();
204 g.colReorder.objTop = objPos.top;
205 g.colReorder.objLeft = objPos.left;
206 g.colReorder.n = g.colReorder.newn;
207 // send request to server to remember the column order
208 if (g.tableCreateTime) {
211 g.refreshRestoreButton();
214 // animate new column position
215 $(g.cCpy).stop(true, true)
217 top: g.colReorder.objTop,
218 left: g.colReorder.objLeft
221 $(g.cPointer).css('visibility', 'hidden');
223 g.colReorder = false;
225 $('body').css('cursor', 'inherit');
226 $('body').noSelect(false);
230 * Resize column n to new width "nw"
232 * @param n zero-based column index
233 * @param nw new width of the column in pixel
235 resize: function(n, nw) {
236 $(g.t).find('tr').each(function() {
237 $(this).find('th.draggable:visible:eq(' + n + ') span,' +
238 'td:visible:eq(' + (g.actionSpan + n) + ') span')
244 * Reposition column resize bars.
246 reposRsz: function() {
247 $(g.cRsz).find('div').hide();
248 var $firstRowCols = $(g.t).find('tr:first th.draggable:visible');
249 for (var n = 0; n < $firstRowCols.length; n++) {
250 var $col = $($firstRowCols[n]);
251 $cb = $(g.cRsz).find('div:eq(' + n + ')'); // column border
252 $cb.css('left', $col.position().left + $col.outerWidth(true))
255 $(g.cRsz).css('height', $(g.t).height());
259 * Shift column from index oldn to newn.
261 * @param oldn old zero-based column index
262 * @param newn new zero-based column index
264 shiftCol: function(oldn, newn) {
265 $(g.t).find('tr').each(function() {
267 $(this).find('th.draggable:eq(' + newn + '),' +
268 'td:eq(' + (g.actionSpan + newn) + ')')
269 .before($(this).find('th.draggable:eq(' + oldn + '),' +
270 'td:eq(' + (g.actionSpan + oldn) + ')'));
272 $(this).find('th.draggable:eq(' + newn + '),' +
273 'td:eq(' + (g.actionSpan + newn) + ')')
274 .after($(this).find('th.draggable:eq(' + oldn + '),' +
275 'td:eq(' + (g.actionSpan + oldn) + ')'));
278 // reposition the column resize bars
281 // adjust the column visibility list
283 $(g.cList).find('.lDiv div:eq(' + newn + ')')
284 .before($(g.cList).find('.lDiv div:eq(' + oldn + ')'));
286 $(g.cList).find('.lDiv div:eq(' + newn + ')')
287 .after($(g.cList).find('.lDiv div:eq(' + oldn + ')'));
289 // adjust the colOrder
290 var tmp = g.colOrder[oldn];
291 g.colOrder.splice(oldn, 1);
292 g.colOrder.splice(newn, 0, tmp);
293 // adjust the colVisib
294 if (g.colVisib.length > 0) {
295 var tmp = g.colVisib[oldn];
296 g.colVisib.splice(oldn, 1);
297 g.colVisib.splice(newn, 0, tmp);
302 * Find currently hovered table column's header (excluding actions column).
305 * @return the hovered column's th object or undefined if no hovered column found.
307 getHoveredCol: function(e) {
309 $headers = $(g.t).find('th.draggable:visible');
310 $headers.each(function() {
311 var left = $(this).offset().left;
312 var right = left + $(this).outerWidth();
313 if (left <= e.pageX && e.pageX <= right) {
321 * Get a zero-based index from a <th class="draggable"> tag in a table.
323 * @param obj table header <th> object
324 * @return zero-based index of the specified table header in the set of table headers (visible or not)
326 getHeaderIdx: function(obj) {
327 return $(obj).parents('tr').find('th.draggable').index(obj);
331 * Reposition the columns back to normal order.
333 restoreColOrder: function() {
334 // use insertion sort, since we already have shiftCol function
335 for (var i = 1; i < g.colOrder.length; i++) {
336 var x = g.colOrder[i];
338 while (j >= 0 && x < g.colOrder[j]) {
342 g.shiftCol(i, j + 1);
345 if (g.tableCreateTime) {
346 // send request to server to remember the column order
349 g.refreshRestoreButton();
353 * Send column preferences (column order and visibility) to the server.
355 sendColPrefs: function() {
356 if ($(g.t).is('.ajax')) { // only send preferences if AjaxEnable is true
364 table_create_time: g.tableCreateTime
366 if (g.colOrder.length > 0) {
367 $.extend(post_params, { col_order: g.colOrder.toString() });
369 if (g.colVisib.length > 0) {
370 $.extend(post_params, { col_visib: g.colVisib.toString() });
372 $.post('sql.php', post_params, function(data) {
373 if (data.success != true) {
374 var $temp_div = $(document.createElement('div'));
375 $temp_div.html(data.error);
376 $temp_div.addClass("error");
377 PMA_ajaxShowMessage($temp_div);
384 * Refresh restore button state.
385 * Make restore button disabled if the table is similar with initial state.
387 refreshRestoreButton: function() {
388 // check if table state is as initial state
389 var isInitial = true;
390 for (var i = 0; i < g.colOrder.length; i++) {
391 if (g.colOrder[i] != i) {
396 // check if only one visible column left
397 var isOneColumn = g.visibleHeadersCount == 1;
398 // enable or disable restore button
399 if (isInitial || isOneColumn) {
400 $('.restore_column').hide();
402 $('.restore_column').show();
407 * Update current hint using the boolean values (showReorderHint, showSortHint, etc.).
408 * It will hide the hint if all the boolean values is false.
412 updateHint: function(e) {
413 if (!g.colRsz && !g.colReorder) { // if not resizing or dragging
415 if (g.showReorderHint && g.reorderHint) {
416 text += g.reorderHint;
418 if (g.showSortHint && g.sortHint) {
419 text += text.length > 0 ? '<br />' : '';
422 if (g.showMarkHint && g.markHint &&
423 !g.showSortHint // we do not show mark hint, when sort hint is shown
425 text += text.length > 0 ? '<br />' : '';
428 if (g.showColVisibHint && g.colVisibHint) {
429 text += text.length > 0 ? '<br />' : '';
430 text += g.colVisibHint;
433 // hide the hint if no text and the event is mouseenter
434 g.qtip.disable(!text && e.type == 'mouseenter');
436 g.qtip.updateContent(text, false);
442 hideHint: function() {
445 g.qtip.disable(true);
450 * Toggle column's visibility.
451 * After calling this function and it returns true, afterToggleCol() must be called.
453 * @return boolean True if the column is toggled successfully.
455 toggleCol: function(n) {
457 // can hide if more than one column is visible
458 if (g.visibleHeadersCount > 1) {
459 $(g.t).find('tr').each(function() {
460 $(this).find('th.draggable:eq(' + n + '),' +
461 'td:eq(' + (g.actionSpan + n) + ')')
465 $(g.cList).find('.lDiv div:eq(' + n + ') input').removeAttr('checked');
467 // cannot hide, force the checkbox to stay checked
468 $(g.cList).find('.lDiv div:eq(' + n + ') input').attr('checked', 'checked');
471 } else { // column n is not visible
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').attr('checked', 'checked');
484 * This must be called if toggleCol() returns is true.
486 * This function is separated from toggleCol because, sometimes, we want to toggle
487 * some columns together at one time and do just one adjustment after it, e.g. in showAllColumns().
489 afterToggleCol: function() {
490 // some adjustments after hiding column
495 // check visible first row headers count
496 g.visibleHeadersCount = $(g.t).find('tr:first th.draggable:visible').length;
497 g.refreshRestoreButton();
501 * Show columns' visibility list.
503 * @param obj The drop down arrow of column visibility list
505 showColList: function(obj) {
506 // only show when not resizing or reordering
507 if (!g.colRsz && !g.colReorder) {
508 var pos = $(obj).position();
509 // check if the list position is too right
510 if (pos.left + $(g.cList).outerWidth(true) > $(document).width()) {
511 pos.left = $(document).width() - $(g.cList).outerWidth(true);
515 top: pos.top + $(obj).outerHeight(true)
518 $(obj).addClass('coldrop-hover');
523 * Hide columns' visibility list.
525 hideColList: function() {
527 $(g.cDrop).find('.coldrop-hover').removeClass('coldrop-hover');
531 * Reposition the column visibility drop-down arrow.
533 reposDrop: function() {
534 $th = $(t).find('th:not(.draggable)');
535 for (var i = 0; i < $th.length; i++) {
536 var $cd = $(g.cDrop).find('div:eq(' + i + ')'); // column drop-down arrow
537 var pos = $($th[i]).position();
539 left: pos.left + $($th[i]).width() - $cd.width(),
546 * Show all hidden columns.
548 showAllColumns: function() {
549 for (var i = 0; i < g.colVisib.length; i++) {
550 if (!g.colVisib[i]) {
558 * Show edit cell, if it can be shown
560 * @param cell <td> element to be edited
562 showEditCell: function(cell) {
563 if ($(cell).is('.grid_edit') &&
564 !g.colRsz && !g.colReorder)
566 if (!g.isCellEditActive) {
568 // remove all edit area and hide it
569 $(g.cEdit).find('.edit_area').empty().hide();
570 // reposition the cEdit element
572 top: $cell.position().top,
573 left: $cell.position().left
578 width: $cell.outerWidth(),
579 height: $cell.outerHeight()
581 // fill the cell edit with text from <td>
582 var value = PMA_getCellValue(cell);
583 $(g.cEdit).find('.edit_box').val(value);
585 g.currentEditCell = cell;
586 $(g.cEdit).find('.edit_box').focus();
587 $(g.cEdit).find('*').removeAttr('disabled');
593 * Remove edit cell and the edit area, if it is shown.
595 * @param force Optional, force to hide edit cell without saving edited field.
596 * @param data Optional, data from the POST AJAX request to save the edited field
597 * or just specify "true", if we want to replace the edited field with the new value.
598 * @param field Optional, the edited <td>. If not specified, the function will
599 * use currently edited <td> from g.currentEditCell.
601 hideEditCell: function(force, data, field) {
602 if (g.isCellEditActive && !force) {
603 // cell is being edited, save or post the edited data
604 g.saveOrPostEditedCell();
608 // cancel any previous request
609 if (g.lastXHR != null) {
615 if (g.currentEditCell) { // save value of currently edited cell
616 // replace current edited field with the new value
617 var $this_field = $(g.currentEditCell);
618 var is_null = $this_field.data('value') == null;
620 $this_field.find('span').html('NULL');
621 $this_field.addClass('null');
623 $this_field.removeClass('null');
624 var new_html = $this_field.data('value');
625 if ($this_field.is('.truncated')) {
626 if (new_html.length > g.maxTruncatedLen) {
627 new_html = new_html.substring(0, g.maxTruncatedLen) + '...';
630 $this_field.find('span').text(new_html);
633 if (data.transformations != undefined) {
634 $.each(data.transformations, function(cell_index, value) {
635 var $this_field = $(g.t).find('.to_be_saved:eq(' + cell_index + ')');
636 $this_field.find('span').html(value);
639 if (data.relations != undefined) {
640 $.each(data.relations, function(cell_index, value) {
641 var $this_field = $(g.t).find('.to_be_saved:eq(' + cell_index + ')');
642 $this_field.find('span').html(value);
651 // hide the cell editing area
653 $(g.cEdit).find('.edit_box').blur();
654 g.isCellEditActive = false;
655 g.currentEditCell = null;
656 // destroy datepicker in edit area, if exist
657 $(g.cEdit).find('.hasDatepicker').datepicker('destroy');
661 * Show drop-down edit area when edit cell is focused.
663 showEditArea: function() {
664 if (!g.isCellEditActive) { // make sure the edit area has not been shown
665 g.isCellEditActive = true;
666 g.isEditCellTextEditable = false;
668 * @var $td current edited cell
670 var $td = $(g.currentEditCell);
672 * @var $editArea the editing area
674 var $editArea = $(g.cEdit).find('.edit_area');
676 * @var where_clause WHERE clause for the edited cell
678 var where_clause = $td.parent('tr').find('.where_clause').val();
680 * @var field_name String containing the name of this field.
681 * @see getFieldName()
683 var field_name = getFieldName($td);
685 * @var relation_curr_value String current value of the field (for fields that are foreign keyed).
687 var relation_curr_value = $td.text();
689 * @var relation_key_or_display_column String relational key if in 'Relational display column' mode,
690 * relational display column if in 'Relational key' mode (for fields that are foreign keyed).
692 var relation_key_or_display_column = $td.find('a').attr('title');
694 * @var curr_value String current value of the field (for fields that are of type enum or set).
696 var curr_value = $td.find('span').text();
698 // empty all edit area, then rebuild it based on $td classes
701 // add goto link, if this cell contains a link
702 if ($td.find('a').length > 0) {
703 var gotoLink = document.createElement('div');
704 gotoLink.className = 'goto_link';
705 $(gotoLink).append(g.gotoLinkText + ': ')
706 .append($td.find('a').clone());
707 $editArea.append(gotoLink);
710 g.wasEditedCellNull = false;
711 if ($td.is(':not(.not_null)')) {
712 // append a null checkbox
713 $editArea.append('<div class="null_div">Null :<input type="checkbox"></div>');
714 var $checkbox = $editArea.find('.null_div input');
715 // check if current <td> is NULL
716 if ($td.is('.null')) {
717 $checkbox.attr('checked', true);
718 g.wasEditedCellNull = true;
721 // if the select/editor is changed un-check the 'checkbox_null_<field_name>_<row_index>'.
722 if ($td.is('.enum, .set')) {
723 $editArea.find('select').live('change', function(e) {
724 $checkbox.attr('checked', false);
726 } else if ($td.is('.relation')) {
727 $editArea.find('select').live('change', function(e) {
728 $checkbox.attr('checked', false);
730 $editArea.find('.browse_foreign').live('click', function(e) {
731 $checkbox.attr('checked', false);
734 $(g.cEdit).find('.edit_box').live('keypress change', function(e) {
735 $checkbox.attr('checked', false);
737 $editArea.find('textarea').live('keydown', function(e) {
738 $checkbox.attr('checked', false);
742 // if null checkbox is clicked empty the corresponding select/editor.
743 $checkbox.click(function(e) {
744 if ($td.is('.enum')) {
745 $editArea.find('select').attr('value', '');
746 } else if ($td.is('.set')) {
747 $editArea.find('select').find('option').each(function() {
748 var $option = $(this);
749 $option.attr('selected', false);
751 } else if ($td.is('.relation')) {
752 // if the dropdown is there to select the foreign value
753 if ($editArea.find('select').length > 0) {
754 $editArea.find('select').attr('value', '');
757 $editArea.find('textarea').val('');
759 $(g.cEdit).find('.edit_box').val('');
763 if ($td.is('.relation')) {
765 $editArea.addClass('edit_area_loading');
767 // initialize the original data
768 $td.data('original_data', null);
771 * @var post_params Object containing parameters for the POST request
774 'ajax_request' : true,
775 'get_relational_values' : true,
779 'column' : field_name,
781 'curr_value' : relation_curr_value,
782 'relation_key_or_display_column' : relation_key_or_display_column
785 g.lastXHR = $.post('sql.php', post_params, function(data) {
787 $editArea.removeClass('edit_area_loading');
788 // save original_data
789 var value = $(data.dropdown).val();
790 $td.data('original_data', value);
791 // update the text input field, in case where the "Relational display column" is checked
792 $(g.cEdit).find('.edit_box').val(value);
794 $editArea.append(data.dropdown);
795 $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
798 $editArea.find('select').live('change', function(e) {
799 $(g.cEdit).find('.edit_box').val($(this).val());
803 else if($td.is('.enum')) {
805 $editArea.addClass('edit_area_loading');
808 * @var post_params Object containing parameters for the POST request
811 'ajax_request' : true,
812 'get_enum_values' : true,
816 'column' : field_name,
818 'curr_value' : curr_value
820 g.lastXHR = $.post('sql.php', post_params, function(data) {
822 $editArea.removeClass('edit_area_loading');
823 $editArea.append(data.dropdown);
824 $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
827 $editArea.find('select').live('change', function(e) {
828 $(g.cEdit).find('.edit_box').val($(this).val());
832 else if($td.is('.set')) {
834 $editArea.addClass('edit_area_loading');
837 * @var post_params Object containing parameters for the POST request
840 'ajax_request' : true,
841 'get_set_values' : true,
845 'column' : field_name,
847 'curr_value' : curr_value
850 g.lastXHR = $.post('sql.php', post_params, function(data) {
852 $editArea.removeClass('edit_area_loading');
853 $editArea.append(data.select);
854 $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
857 $editArea.find('select').live('change', function(e) {
858 $(g.cEdit).find('.edit_box').val($(this).val());
862 else if($td.is('.truncated, .transformed')) {
863 if ($td.is('.to_be_saved')) { // cell has been edited
864 var value = $td.data('value');
865 $(g.cEdit).find('.edit_box').val(value);
866 $editArea.append('<textarea></textarea>');
867 $editArea.find('textarea')
869 .live('keyup', function(e) {
870 $(g.cEdit).find('.edit_box').val($(this).val());
872 $(g.cEdit).find('.edit_box').live('keyup', function(e) {
873 $editArea.find('textarea').val($(this).val());
875 $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
877 //handle truncated/transformed values values
878 $editArea.addClass('edit_area_loading');
880 // initialize the original data
881 $td.data('original_data', null);
884 * @var sql_query String containing the SQL query used to retrieve value of truncated/transformed data
886 var sql_query = 'SELECT `' + field_name + '` FROM `' + g.table + '` WHERE ' + PMA_urldecode(where_clause);
888 // Make the Ajax call and get the data, wrap it and insert it
889 g.lastXHR = $.post('sql.php', {
893 'ajax_request' : true,
894 'sql_query' : sql_query,
898 $editArea.removeClass('edit_area_loading');
899 if(data.success == true) {
900 if ($td.is('.truncated')) {
901 // get the truncated data length
902 g.maxTruncatedLen = $(g.currentEditCell).text().length - 3;
905 $td.data('original_data', data.value);
906 $(g.cEdit).find('.edit_box').val(data.value);
907 $editArea.append('<textarea></textarea>');
908 $editArea.find('textarea')
910 .live('keyup', function(e) {
911 $(g.cEdit).find('.edit_box').val($(this).val());
913 $(g.cEdit).find('.edit_box').live('keyup', function(e) {
914 $editArea.find('textarea').val($(this).val());
916 $editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
919 PMA_ajaxShowMessage(data.error);
923 g.isEditCellTextEditable = true;
925 } else if ($td.is('.datefield, .datetimefield, .timestampfield')) {
926 var $input_field = $(g.cEdit).find('.edit_box');
928 // remember current datetime value in $input_field, if it is not null
929 var is_null = $td.is('.null');
930 var current_datetime_value = !is_null ? $input_field.val() : '';
932 var showTimeOption = true;
933 if ($td.is('.datefield')) {
934 showTimeOption = false;
936 PMA_addDatepicker($editArea, {
937 altField: $input_field,
938 showTimepicker: showTimeOption,
939 onSelect: function(dateText, inst) {
940 // remove null checkbox if it exists
941 $(g.cEdit).find('.null_div input[type=checkbox]').attr('checked', false);
945 // force to restore modified $input_field value after adding datepicker
946 // (after adding a datepicker, the input field doesn't display the time anymore, only the date)
948 $editArea.datetimepicker('setDate', current_datetime_value);
950 $input_field.val('');
954 g.isEditCellTextEditable = true;
960 * Post the content of edited cell.
962 postEditedCell: function() {
969 * @var relation_fields Array containing the name/value pairs of relational fields
971 var relation_fields = {};
973 * @var relational_display string 'K' if relational key, 'D' if relational display column
975 var relational_display = $("#relational_display_K").attr('checked') ? 'K' : 'D';
977 * @var transform_fields Array containing the name/value pairs for transformed fields
979 var transform_fields = {};
981 * @var transformation_fields Boolean, if there are any transformed fields in the edited cells
983 var transformation_fields = false;
985 * @var full_sql_query String containing the complete SQL query to update this table
987 var full_sql_query = '';
989 * @var rel_fields_list String, url encoded representation of {@link relations_fields}
991 var rel_fields_list = '';
993 * @var transform_fields_list String, url encoded representation of {@link transform_fields}
995 var transform_fields_list = '';
997 * @var where_clause Array containing where clause for updated fields
999 var full_where_clause = Array();
1001 * @var is_unique Boolean, whether the rows in this table is unique or not
1003 var is_unique = $('.edit_row_anchor').is('.nonunique') ? 0 : 1;
1005 * multi edit variables
1007 var me_fields_name = Array();
1008 var me_fields = Array();
1009 var me_fields_null = Array();
1011 // alert user if edited table is not unique
1013 alert(g.alertNonUnique);
1016 // loop each edited row
1017 $('.to_be_saved').parents('tr').each(function() {
1019 var where_clause = $tr.find('.where_clause').val();
1020 full_where_clause.push(PMA_urldecode(where_clause));
1021 var condition_array = jQuery.parseJSON($tr.find('.condition_array').val());
1024 * multi edit variables, for current row
1025 * @TODO array indices are still not correct, they should be md5 of field's name
1027 var fields_name = Array();
1028 var fields = Array();
1029 var fields_null = Array();
1031 // loop each edited cell in a row
1032 $tr.find('.to_be_saved').each(function() {
1034 * @var $this_field Object referring to the td that is being edited
1036 var $this_field = $(this);
1039 * @var field_name String containing the name of this field.
1040 * @see getFieldName()
1042 var field_name = getFieldName($this_field);
1045 * @var this_field_params Array temporary storage for the name/value of current field
1047 var this_field_params = {};
1049 if($this_field.is('.transformed')) {
1050 transformation_fields = true;
1052 this_field_params[field_name] = $this_field.data('value');
1055 * @var is_null String capturing whether 'checkbox_null_<field_name>_<row_index>' is checked.
1057 var is_null = this_field_params[field_name] === null;
1059 fields_name.push(field_name);
1062 fields_null.push('on');
1065 fields_null.push('');
1066 fields.push($this_field.data('value'));
1068 var cell_index = $this_field.index('.to_be_saved');
1069 if($this_field.is(":not(.relation, .enum, .set, .bit)")) {
1070 if($this_field.is('.transformed')) {
1071 transform_fields[cell_index] = {};
1072 $.extend(transform_fields[cell_index], this_field_params);
1074 } else if($this_field.is('.relation')) {
1075 relation_fields[cell_index] = {};
1076 $.extend(relation_fields[cell_index], this_field_params);
1079 // check if edited field appears in WHERE clause
1080 if (where_clause.indexOf(PMA_urlencode(field_name)) > -1) {
1081 var field_str = '`' + g.table + '`.' + '`' + field_name + '`';
1082 for (var field in condition_array) {
1083 if (field.indexOf(field_str) > -1) {
1084 condition_array[field] = is_null ? 'IS NULL' : "= '" + this_field_params[field_name].replace(/'/g,"''") + "'";
1090 }); // end of loop for every edited cells in a row
1093 var new_clause = '';
1094 for (var field in condition_array) {
1095 new_clause += field + ' ' + condition_array[field] + ' AND ';
1097 new_clause = new_clause.substring(0, new_clause.length - 5); // remove the last AND
1098 new_clause = PMA_urlencode(new_clause);
1099 $tr.data('new_clause', new_clause);
1100 // save condition_array
1101 $tr.find('.condition_array').val(JSON.stringify(condition_array));
1103 me_fields_name.push(fields_name);
1104 me_fields.push(fields);
1105 me_fields_null.push(fields_null);
1107 }); // end of loop for every edited rows
1109 rel_fields_list = $.param(relation_fields);
1110 transform_fields_list = $.param(transform_fields);
1112 // Make the Ajax post after setting all parameters
1114 * @var post_params Object containing parameters for the POST request
1116 var post_params = {'ajax_request' : true,
1117 'sql_query' : full_sql_query,
1119 'server' : g.server,
1122 'clause_is_unique' : is_unique,
1123 'where_clause' : full_where_clause,
1124 'fields[multi_edit]' : me_fields,
1125 'fields_name[multi_edit]' : me_fields_name,
1126 'fields_null[multi_edit]' : me_fields_null,
1127 'rel_fields_list' : rel_fields_list,
1128 'do_transformations' : transformation_fields,
1129 'transform_fields_list' : transform_fields_list,
1130 'relational_display' : relational_display,
1132 'submit_type' : 'save'
1135 if (!g.saveCellsAtOnce) {
1136 $(g.cEdit).find('*').attr('disabled', 'disabled');
1137 var $editArea = $(g.cEdit).find('.edit_area');
1138 $(g.cEdit).find('.edit_box').addClass('edit_box_posting');
1140 $('.save_edited').addClass('saving_edited_data')
1141 .find('input').attr('disabled', 'disabled'); // disable the save button
1146 url: 'tbl_replace.php',
1151 if (!g.saveCellsAtOnce) {
1152 $(g.cEdit).find('*').removeAttr('disabled');
1153 $(g.cEdit).find('.edit_box').removeClass('edit_box_posting');
1155 $('.save_edited').removeClass('saving_edited_data')
1156 .find('input').removeAttr('disabled'); // enable the save button back
1158 if(data.success == true) {
1159 PMA_ajaxShowMessage(data.message);
1160 // update where_clause related data in each edited row
1161 $('.to_be_saved').parents('tr').each(function() {
1162 var new_clause = $(this).data('new_clause');
1163 var $where_clause = $(this).find('.where_clause');
1164 var old_clause = $where_clause.attr('value');
1165 var decoded_old_clause = PMA_urldecode(old_clause);
1166 var decoded_new_clause = PMA_urldecode(new_clause);
1168 $where_clause.attr('value', new_clause);
1169 // update Edit, Copy, and Delete links also
1170 $(this).find('a').each(function() {
1171 $(this).attr('href', $(this).attr('href').replace(old_clause, new_clause));
1172 // update delete confirmation in Delete link
1173 if ($(this).attr('href').indexOf('DELETE') > -1) {
1174 $(this).removeAttr('onclick')
1176 .bind('click', function() {
1177 return confirmLink(this, 'DELETE FROM `' + g.db + '`.`' + g.table + '` WHERE ' +
1178 decoded_new_clause + (is_unique ? '' : ' LIMIT 1'));
1182 // update the multi edit checkboxes
1183 $(this).find('input[type=checkbox]').each(function() {
1184 var $checkbox = $(this);
1185 var checkbox_name = $checkbox.attr('name');
1186 var checkbox_value = $checkbox.attr('value');
1188 $checkbox.attr('name', checkbox_name.replace(old_clause, new_clause));
1189 $checkbox.attr('value', checkbox_value.replace(decoded_old_clause, decoded_new_clause));
1192 // update the display of executed SQL query command
1193 $('#result_query').remove();
1194 if (typeof data.sql_query != 'undefined') {
1196 $('#sqlqueryresults').prepend(data.sql_query);
1198 // hide and/or update the successfully saved cells
1199 g.hideEditCell(true, data);
1201 // remove the "Save edited cells" button
1202 $('.save_edited').hide();
1203 // update saved fields
1204 $(g.t).find('.to_be_saved')
1205 .removeClass('to_be_saved')
1206 .data('value', null)
1207 .data('original_data', null);
1209 g.isCellEdited = false;
1211 PMA_ajaxShowMessage(data.error);
1218 * Save edited cell, so it can be posted later.
1220 saveEditedCell: function() {
1222 * @var $this_field Object referring to the td that is being edited
1224 var $this_field = $(g.currentEditCell);
1225 var $test_element = ''; // to test the presence of a element
1227 var need_to_post = false;
1230 * @var field_name String containing the name of this field.
1231 * @see getFieldName()
1233 var field_name = getFieldName($this_field);
1236 * @var this_field_params Array temporary storage for the name/value of current field
1238 var this_field_params = {};
1241 * @var is_null String capturing whether 'checkbox_null_<field_name>_<row_index>' is checked.
1243 var is_null = $(g.cEdit).find('input:checkbox').is(':checked');
1246 if ($(g.cEdit).find('.edit_area').is('.edit_area_loading')) {
1247 // the edit area is still loading (retrieving cell data), no need to post
1248 need_to_post = false;
1249 } else if (is_null) {
1250 if (!g.wasEditedCellNull) {
1251 this_field_params[field_name] = null;
1252 need_to_post = true;
1255 if ($this_field.is('.bit')) {
1256 this_field_params[field_name] = '0b' + $(g.cEdit).find('.edit_box').val();
1257 } else if ($this_field.is('.set')) {
1258 $test_element = $(g.cEdit).find('select');
1259 this_field_params[field_name] = $test_element.map(function(){
1260 return $(this).val();
1262 } else if ($this_field.is('.relation, .enum')) {
1263 // results from a drop-down
1264 $test_element = $(g.cEdit).find('select');
1265 if ($test_element.length != 0) {
1266 this_field_params[field_name] = $test_element.val();
1269 // results from Browse foreign value
1270 $test_element = $(g.cEdit).find('span.curr_value');
1271 if ($test_element.length != 0) {
1272 this_field_params[field_name] = $test_element.text();
1275 this_field_params[field_name] = $(g.cEdit).find('.edit_box').val();
1277 if (g.wasEditedCellNull || this_field_params[field_name] != PMA_getCellValue(g.currentEditCell)) {
1278 need_to_post = true;
1283 $(g.currentEditCell).addClass('to_be_saved')
1284 .data('value', this_field_params[field_name]);
1285 if (g.saveCellsAtOnce) {
1286 $('.save_edited').show();
1288 g.isCellEdited = true;
1291 return need_to_post;
1295 * Save or post currently edited cell, depending on the "saveCellsAtOnce" configuration.
1297 saveOrPostEditedCell: function() {
1298 var saved = g.saveEditedCell();
1299 if (!g.saveCellsAtOnce) {
1303 g.hideEditCell(true);
1307 g.hideEditCell(true, true);
1309 g.hideEditCell(true);
1315 * Initialize column resize feature.
1317 initColResize: function() {
1318 // create column resizer div
1319 g.cRsz = document.createElement('div');
1320 g.cRsz.className = 'cRsz';
1322 // get data columns in the first row of the table
1323 var $firstRowCols = $(g.t).find('tr:first th.draggable');
1325 // create column borders
1326 $firstRowCols.each(function() {
1327 var cb = document.createElement('div'); // column border
1328 $(cb).addClass('colborder')
1329 .mousedown(function(e) {
1330 g.dragStartRsz(e, this);
1332 $(g.cRsz).append(cb);
1336 // attach to global div
1337 $(g.gDiv).prepend(g.cRsz);
1341 * Initialize column reordering feature.
1343 initColReorder: function() {
1344 g.cCpy = document.createElement('div'); // column copy, to store copy of dragged column header
1345 g.cPointer = document.createElement('div'); // column pointer, used when reordering column
1348 g.cCpy.className = 'cCpy';
1351 // adjust g.cPointer
1352 g.cPointer.className = 'cPointer';
1353 $(g.cPointer).css('visibility', 'hidden'); // set visibility to hidden instead of calling hide() to force browsers to cache the image in cPointer class
1355 // assign column reordering hint
1356 g.reorderHint = PMA_messages['strColOrderHint'];
1358 // get data columns in the first row of the table
1359 var $firstRowCols = $(g.t).find('tr:first th.draggable');
1361 // initialize column order
1362 $col_order = $('#col_order'); // check if column order is passed from PHP
1363 if ($col_order.length > 0) {
1364 g.colOrder = $col_order.val().split(',');
1365 for (var i = 0; i < g.colOrder.length; i++) {
1366 g.colOrder[i] = parseInt(g.colOrder[i]);
1369 g.colOrder = new Array();
1370 for (var i = 0; i < $firstRowCols.length; i++) {
1376 $(t).find('th.draggable')
1377 .mousedown(function(e) {
1378 if (g.visibleHeadersCount > 1) {
1379 g.dragStartReorder(e, this);
1382 .mouseenter(function(e) {
1383 if (g.visibleHeadersCount > 1) {
1384 g.showReorderHint = true;
1385 $(this).css('cursor', 'move');
1387 $(this).css('cursor', 'inherit');
1390 .mouseleave(function(e) {
1391 g.showReorderHint = false;
1393 // restore column order when the restore button is clicked
1394 $('.restore_column').click(function() {
1395 g.restoreColOrder();
1398 // attach to global div
1399 $(g.gDiv).append(g.cPointer);
1400 $(g.gDiv).append(g.cCpy);
1402 // prevent default "dragstart" event when dragging a link
1403 $(t).find('th a').bind('dragstart', function() {
1407 // refresh the restore column button state
1408 g.refreshRestoreButton();
1412 * Initialize column visibility feature.
1414 initColVisib: function() {
1415 g.cDrop = document.createElement('div'); // column drop-down arrows
1416 g.cList = document.createElement('div'); // column visibility list
1419 g.cDrop.className = 'cDrop';
1422 g.cList.className = 'cList';
1425 // assign column visibility related hints
1426 g.colVisibHint = PMA_messages['strColVisibHint'];
1427 g.showAllColText = PMA_messages['strShowAllCol'];
1429 // get data columns in the first row of the table
1430 var $firstRowCols = $(g.t).find('tr:first th.draggable');
1432 // initialize column visibility
1433 $col_visib = $('#col_visib'); // check if column visibility is passed from PHP
1434 if ($col_visib.length > 0) {
1435 g.colVisib = $col_visib.val().split(',');
1436 for (var i = 0; i < g.colVisib.length; i++) {
1437 g.colVisib[i] = parseInt(g.colVisib[i]);
1440 g.colVisib = new Array();
1441 for (var i = 0; i < $firstRowCols.length; i++) {
1446 // get data columns in the first row of the table
1447 var $firstRowCols = $(t).find('tr:first th.draggable');
1449 // make sure we have more than one column
1450 if ($firstRowCols.length > 1) {
1451 var $colVisibTh = $(g.t).find('th:not(.draggable)');
1452 PMA_createqTip($colVisibTh);
1454 // create column visibility drop-down arrow(s)
1455 $colVisibTh.each(function() {
1457 var cd = document.createElement('div'); // column drop-down arrow
1458 var pos = $th.position();
1459 $(cd).addClass('coldrop')
1461 if (g.cList.style.display == 'none') {
1462 g.showColList(this);
1467 $(g.cDrop).append(cd);
1469 .mouseenter(function(e) {
1470 g.showColVisibHint = true;
1472 .mouseleave(function(e) {
1473 g.showColVisibHint = false;
1476 // add column visibility control
1477 g.cList.innerHTML = '<div class="lDiv"></div>';
1478 var $listDiv = $(g.cList).find('div');
1479 for (var i = 0; i < $firstRowCols.length; i++) {
1480 var currHeader = $firstRowCols[i];
1481 var listElmt = document.createElement('div');
1482 $(listElmt).text($(currHeader).text())
1483 .prepend('<input type="checkbox" ' + (g.colVisib[i] ? 'checked="checked" ' : '') + '/>');
1484 $listDiv.append(listElmt);
1485 // add event on click
1486 $(listElmt).click(function() {
1487 if ( g.toggleCol($(this).index()) ) {
1492 // add "show all column" button
1493 var showAll = document.createElement('div');
1494 $(showAll).addClass('showAllColBtn')
1495 .text(g.showAllColText);
1496 $(g.cList).append(showAll);
1497 $(showAll).click(function() {
1500 // prepend "show all column" button at top if the list is too long
1501 if ($firstRowCols.length > 10) {
1502 var clone = showAll.cloneNode(true);
1503 $(g.cList).prepend(clone);
1504 $(clone).click(function() {
1510 // hide column visibility list if we move outside the list
1511 $(t).find('td, th.draggable').mouseenter(function() {
1515 // attach to global div
1516 $(g.gDiv).append(g.cDrop);
1517 $(g.gDiv).append(g.cList);
1524 * Initialize grid editing feature.
1526 initGridEdit: function() {
1527 // create cell edit wrapper element
1528 g.cEdit = document.createElement('div');
1531 g.cEdit.className = 'cEdit';
1532 $(g.cEdit).html('<textarea class="edit_box" rows="1" ></textarea><div class="edit_area" />');
1535 // assign cell editing hint
1536 g.cellEditHint = PMA_messages['strCellEditHint'];
1537 g.saveCellWarning = PMA_messages['strSaveCellWarning'];
1538 g.alertNonUnique = PMA_messages['strAlertNonUnique'];
1539 g.gotoLinkText = PMA_messages['strGoToLink'];
1541 // initialize cell editing configuration
1542 g.saveCellsAtOnce = $('#save_cells_at_once').val();
1545 $(t).find('td.data')
1546 .click(function(e) {
1547 if (g.isCellEditActive) {
1548 g.saveOrPostEditedCell();
1549 e.stopPropagation();
1551 g.showEditCell(this);
1552 e.stopPropagation();
1554 // prevent default action when clicking on "link" in a table
1555 if ($(e.target).is('a')) {
1559 $(g.cEdit).find('.edit_box').focus(function(e) {
1562 $(g.cEdit).find('.edit_box, select').live('keydown', function(e) {
1563 if (e.which == 13) {
1564 // post on pressing "Enter"
1566 g.saveOrPostEditedCell();
1569 $(g.cEdit).keydown(function(e) {
1570 if (!g.isEditCellTextEditable) {
1571 // prevent text editing
1575 $(g.cEdit).find('.edit_area').click(function(e) {
1576 e.stopPropagation();
1578 $('html').click(function(e) {
1579 // hide edit cell if the click is not from g.cEdit
1580 if ($(e.target).parents().index(g.cEdit) == -1) {
1584 $('html').keydown(function(e) {
1585 if (e.which == 27 && g.isCellEditActive) {
1587 // cancel on pressing "Esc"
1588 g.hideEditCell(true);
1591 $('.save_edited').click(function() {
1595 $(window).bind('beforeunload', function(e) {
1596 if (g.isCellEdited) {
1597 return g.saveCellWarning;
1601 // attach to global div
1602 $(g.gDiv).append(g.cEdit);
1604 // add hint for grid editing feature when hovering "Edit" link in each table row
1605 PMA_createqTip($(g.t).find('.edit_row_anchor a'), PMA_messages['strGridEditFeatureHint']);
1613 // wrap all data cells, except actions cell, with span
1614 $(t).find('th, td:not(:has(span))')
1615 .wrapInner('<span />');
1617 // create grid elements
1618 g.gDiv = document.createElement('div'); // create global div
1620 // initialize the table variable
1623 // get data columns in the first row of the table
1624 var $firstRowCols = $(t).find('tr:first th.draggable');
1626 // initialize visible headers count
1627 g.visibleHeadersCount = $firstRowCols.filter(':visible').length;
1629 // assign first column (actions) span
1630 if (! $(t).find('tr:first th:first').hasClass('draggable')) { // action header exist
1631 g.actionSpan = $(t).find('tr:first th:first').prop('colspan');
1636 // assign table create time
1637 // #table_create_time will only available if we are in "Browse" tab
1638 g.tableCreateTime = $('#table_create_time').val();
1641 g.sortHint = PMA_messages['strSortHint'];
1642 g.markHint = PMA_messages['strColMarkHint'];
1644 // assign common hidden inputs
1645 var $common_hidden_inputs = $('.common_hidden_inputs');
1646 g.token = $common_hidden_inputs.find('input[name=token]').val();
1647 g.server = $common_hidden_inputs.find('input[name=server]').val();
1648 g.db = $common_hidden_inputs.find('input[name=db]').val();
1649 g.table = $common_hidden_inputs.find('input[name=table]').val();
1652 $(t).addClass('pma_table');
1654 // add relative position to global div so that resize handlers are correctly positioned
1655 $(g.gDiv).css('position', 'relative');
1657 // link the global div
1658 $(t).before(g.gDiv);
1659 $(g.gDiv).append(t);
1662 enableResize = enableResize == undefined ? true : enableResize;
1663 enableReorder = enableReorder == undefined ? true : enableReorder;
1664 enableVisib = enableVisib == undefined ? true : enableVisib;
1665 enableGridEdit = enableGridEdit == undefined ? true : enableGridEdit;
1669 if (enableReorder &&
1670 $('.navigation').length > 0) // disable reordering for result from EXPLAIN or SHOW syntax, which do not have a table navigation panel
1677 if (enableGridEdit &&
1678 $(t).is('.ajax')) // make sure AjaxEnable is enabled in Settings
1683 // create qtip for each <th> with draggable class
1684 PMA_createqTip($(t).find('th.draggable'));
1686 // register events for hint tooltip
1687 $(t).find('th.draggable a')
1688 .attr('title', '') // hide default tooltip for sorting
1689 .mouseenter(function(e) {
1690 g.showSortHint = true;
1693 .mouseleave(function(e) {
1694 g.showSortHint = false;
1697 $(t).find('th.marker')
1698 .mouseenter(function(e) {
1699 g.showMarkHint = true;
1701 .mouseleave(function(e) {
1702 g.showMarkHint = false;
1704 // register events for dragging-related feature
1705 if (enableResize || enableReorder) {
1706 $(document).mousemove(function(e) {
1709 $(document).mouseup(function(e) {
1714 // bind event to update currently hovered qtip API
1716 .mouseenter(function(e) {
1717 g.qtip = $(this).qtip('api');
1720 .mouseleave(function(e) {
1725 $(t).removeClass('data');
1726 $(g.gDiv).addClass('data');