How to customise the ghost-text (drag item name) with AgGrid - drag-and-drop

As per title, is there a way to customise the "ghost text" with the (unmanaged) row-dragging implementation in AgGrid via the API?

I found workaround using valueGetter property to change this text.
Example configuration of column:
private dragDropColumn= {
rowDrag: true,
...
valueGetter: (params) => {
return params.data.myVariableFromRow;
}
}
Hope this helps

You can now use colDef.rowDragText to set a callback function to set the dragged text.
https://www.ag-grid.com/javascript-grid-row-dragging/#custom-row-drag-text

onRowDragEnter event,
you could search for the ghost element
and then append your custom class to it.
document.querySelectorAll('.ag-dnd-ghost')[0]
.classlist.add('my-custom-ghost-element');
Dont forget to follow the hierarchy of classes, otherwise you would end up using !important in the custom class :-)
// For updating text
search for the element with className ag-dnd-ghost-label
document.querySelectorAll('.ag-dnd-ghost-label')[0]
.innerHTML = 'your_custom_text';
Ghost element is added only during drag, once drag is ended, its removed from dom by Ag-Grid.
Hope this helps

I've researched this and there is nothing built in to ag-grid. I accomplished this by attaching to the onRowDragMove and onRowDragMove events.
I set a class variable 'isRowDragging' to only do this once while dragging.
I use the Angular Renderer2 class (this.ui) to find and update the Element of the ghost label.
All of this is available with vanilla javascript or other supported ag-grid frameworks.
this.gridOptions.onRowDragMove = (params: RowDragMoveEvent) => {
const overNode = params.overNode;
const movingNode = params.node;
if (!this.isRowDragging) {
this.isRowDragging = true;
if (!movingNode.isSelected()) {
if (params.event && params.event.ctrlKey) {
movingNode.setSelected(true);
}
if (params.event && !params.event.ctrlKey) {
movingNode.setSelected(true, true);
}
}
let labelText: string = '';
const selectedNodes = this.gridOptions.api.getSelectedNodes();
if (selectedNodes.length === 1) {
labelText = selectedNodes[0].data.Name;
}
else {
const guids: string[] = [];
let folderCount: number = 0;
let docCount: number = 0;
selectedNodes.forEach((node: RowNode) => {
guids.push((node.data.FolderGuid || node.data.DocumentGuid).toLowerCase());
if (node.data.FolderGuid !== undefined) {
folderCount++;
}
else {
docCount++;
}
});
if (folderCount === 1) {
labelText = '1 folder';
}
else if (folderCount > 1) {
labelText = folderCount + ' folders';
}
if (docCount === 1) {
labelText += (labelText !== '' ? ', ' : '') + '1 document';
}
else if (docCount > 1) {
labelText += (labelText !== '' ? ', ' : '') + docCount + ' documents';
}
}
console.log(this.ui.find(document.body, '.ag-dnd-ghost').outerHTML);
this.ui.find(document.body, '.ag-dnd-ghost-label').innerHTML = labelText;
}
}
this.gridOptions.onRowDragEnd = (event: RowDragEndEvent) => {
this.isRowDragging = false;
}

I am using ag-grid with react and using cellRendererFramework property of ColDef to use custom react component, my value getter returns object, so when I start dragging I am getting [object object], I added toString method to returning object and did the trick, below is my sample code
const col1 = {
rowDrag: true,
...
valueGetter: (params) => {
const {id, name} = params.data;
return {id, name, toString: () => name}; // so when dragging it will display name property
}
}

Related

How do I iterate through selected cells in AgGrid?

I would like to delete the values in all selected cells when the user presses backspace or delete, how do I iterate through the selected cells?
I'm using React and Typescript
The docs are out of date, this worked for me, in react / typescript
(
// The type of this is shown below, but is impossible to work with
event: any
// | CellKeyPressEvent<CountryLineProductRow>
// | FullWidthCellKeyPressEvent<CountryLineProductRow>
) => {
if (event.event.key === 'Backspace' || event.event.key === 'Delete') {
event.api.getCellRanges().forEach((cellRange: CellRange) => {
if (cellRange.startRow && cellRange.endRow) {
const startRow = Math.min(
cellRange.endRow.rowIndex,
cellRange.startRow.rowIndex
);
const endRow = Math.min(
cellRange.endRow.rowIndex,
cellRange.startRow.rowIndex
);
cellRange.columns.forEach((column: Column) => {
if (column.getColDef().editable) {
for (
let rowNumber = startRow;
rowNumber <= endRow;
rowNumber++
) {
const model = event.api.getModel();
const rowNode = model.rowsToDisplay[rowNumber];
rowNode.setDataValue(column.getColDef().field, null);
}
}
});
}
});
}
}

Problem inserting checkbox in select using DataTables

I'm looking for a way to insert a checkbox into a select and fetch each column individually, all using DataTables. I found an excellent example in https://jsfiddle.net/Lxytynm3/2/ but for some reason, when selecting all records, filtering does not display the data as expected. Would anyone have a solution to work properly?
Thanks in advance.
The link application code is as follows:
$(document).ready(function() {
function cbDropdown(column) {
return $('<ul>', {
'class': 'cb-dropdown'
}).appendTo($('<div>', {
'class': 'cb-dropdown-wrap'
}).appendTo(column));
}
$('#example').DataTable({
initComplete: function() {
this.api().columns().every(function() {
var column = this;
var ddmenu = cbDropdown($(column.header()))
// -------------------------------------------------------
.on('change', ':checkbox', function() {
var active;
var vals = $(':checked', ddmenu).map(function(index, element) {
active = true;
return $.fn.dataTable.util.escapeRegex($(element).val());
}).toArray().join('|');
column
.search(vals.length > 0 ? '^(' + vals + ')$' : '', true, false)
.draw();
// -------------------------------------------------------
// Highlight the current item if selected.
if (this.checked) {
$(this).closest('li').addClass('active');
// If 'Select all / none' clicked ON
if ($(this).val() === "1") {
$(ddmenu).find('input[type="checkbox"]').prop('checked', this.checked)
//$(".cb-dropdown li").prop('checked', true);
//$('.cb-dropdown').closest('li').find('input[type="checkbox"]').prop('checked', true);
// $('this input[type="checkbox"]').prop('checked', true); works!
// $( 'input[type="checkbox"]' ).prop('checked', this.checked);
// $(this).find('input[type="checkbox"]').prop('checked', this.checked)
//$('div.cb-dropdown-wrap.active').children().find('input[type="checkbox"]').prop('checked', this.checked)
}
} else // 'Select all / none' clicked OFF
{
$(this).closest('li').removeClass('active');
// test if select none
if ($(this).val() === "1") {
// code to untick all
$(ddmenu).find('input[type="checkbox"]').prop('checked', false)
}
}
// Highlight the current filter if selected.
var active2 = ddmenu.parent().is('.active');
if (active && !active2) {
ddmenu.parent().addClass('active');
// Change Container title to "Filter on" and green
//$(this).parent().find('.cb-dropdown li:nth-child(n+1)').css('color','red');
$('active2 li label:contains("Filter OFF")').text('Yeees');
} else if (!active && active2) {
ddmenu.parent().removeClass('active');
}
});
// -------------------------------------------------------
var mytopcount = '0'; // Counter that ensures only 1 entry per container
// loop to assign all options in container filter
column.data().unique().sort().each(function(d, j) {
// Label
var $label = $('<label>'),
$text = $('<span>', {
text: d
}),
// Checkbox
$cb = $('<input>', {
type: 'checkbox',
value: d
});
$text.appendTo($label);
$cb.appendTo($label);
ddmenu.append($('<li>').append($label));
// -----------------
// Add 'Select all / none' to each dropdown container
if (mytopcount == '0') // Counter that ensures only 1 entry per container
{
$label = $('<label>'), $text = $('<span>', {
text: "Select all / none"
}),
$cb = $('<input>', {
type: 'checkbox',
value: 1
});
$text.prependTo($label).css('margin-bottom', '6px');
$cb.prependTo($label);
ddmenu.prepend($('<li>').prepend($label).css({
'border-bottom': '1px solid grey',
'margin-bottom': '6px'
}));
mytopcount = '1' // This stops this section running again in cotainer
}
});
});
}
});
});
It seems as though the issue was with the select all checkbox. One solution would be to check for "1" within the vals initialisation, this seems to work:
var vals = $(':checked', ddmenu).map(function(index, element) {
if($(element).val() !== "1"){
return $.fn.dataTable.util.escapeRegex($(element).val());
}
}).toArray().join('|');
That should see you with some results upon the top checkbox being checked. Hope that helps.

algolia/instantsearch: connectMenu refine() remove current refined value

Is there any way to REMOVE a refined value with connectMenu’s connector?
These are the things I tried that did not work:
passing an empty string refine('')
passing a null value refine(null)
passing a false value refine(false)
passing no parameter refine()
The reason why I’d like to do this is because otherwise currentRefinedValues widget shows an attribute as refined even if it’s not.
var customMenuRenderFn = function (renderParams, isFirstRendering) {
var container = renderParams.widgetParams.containerNode;
var title = renderParams.widgetParams.title || 'dropdownMenu';
var templates = renderParams.widgetParams.templates;
var hideIfIsUnselected = renderParams.widgetParams.hideIfIsUnselected || false;
var cssClasses = renderParams.widgetParams.cssClasses || "";
if (isFirstRendering)
{
$(container).append(
(templates.header || '<h1>' + renderParams.widgetParams.attributeName + '</h1>') +
'<select class="' + cssClasses.select + '">' +
'<option value="__EMPTY__">Tutto</option>' +
'</select>'
).hide();
var refine = renderParams.refine;
if (! hideIfIsUnselected)
{
$(container).show();
}
else
{
$(hideIfIsUnselected).find('select').on('items:loaded', function () {
if (isFirstRendering) {
var valueToCheck = $(hideIfIsUnselected).find('select').val();
$(container).toggle(valueToCheck !== '__EMPTY__');
$(container).find('select').off('items:loaded');
}
});
$(hideIfIsUnselected).find('select').on('change', function (event) {
var value = event.target.value === '__EMPTY__' ? '' : event.target.value;
if (value === '') {
refine();
}
$(container).toggle(value !== '');
});
}
$(container).find('select').on('change', function (event) {
var value = event.target.value === '__EMPTY__' ? '' : event.target.value;
refine(value);
});
}
function updateHits (hits)
{
var items = renderParams.items;
optionsHtml = ['<option class="' + cssClasses.item + '" value="__EMPTY__" selected>Tutto</option>']
.concat(
items.map(function (item) {
return `<option class="${cssClasses.item}" value="${item.value}" ${item.isRefined ? 'selected' : ''}>
${item.label} (${item.count})
</option>`;
})
);
$(container).find('select').html(optionsHtml);
$(container).find('select').trigger('items:loaded');
}
if (hideIfIsUnselected && $(hideIfIsUnselected).val() !== '__EMPTY__') {
updateHits(renderParams.items);
} else if (! hideIfIsUnselected) {
updateHits(renderParams.items);
}
}
var dropdownMenu = instantsearch.connectors.connectMenu(customMenuRenderFn);
The refine function actually toggles the value (setting it if not set, or unsetting if set). If you want to unselect any item in the menu, you need to find the currently selected value and use refine on it.
connectMenu(function render(params, isFirstRendering) {
var items = params.items;
var currentlySelectedItem = items.find(function isSelected(i) {
return i.isRefined;
});
params.refine(currentlySelectedItem);
});
This example won't solve your code completely, but it shows how to find the currently selected item and unselect it.

How can I customize the 'home' and 'end' key navigation on ag-Grid?

I've customized the arrow navigation keys using the callback 'navigateToNextCell'.
But now I want to customize 'Home' and 'End' key.
There is any way to do it?
It's not super easy at the moment... here are some relevant "enhancements" that have been requested on the github page:
support page up/ down, home and end keys
allow overriding of keyboard events
Suggestion: Allow any key for navigation (not just tab)
That last link has something useful. There is a comment on how to disable any propagation of the 'home' and 'end' keys:
// note, this is angular 2 code, `this.el.nativeElement` is just the grid component
document.documentElement.addEventListener(
'keydown',
(e: KeyboardEvent) => {
// this runs on the document element, so check that we're in the grid
if (this.el.nativeElement.contains(e.target)) {
if (e.key === 'Tab' || e.key === 'Home' || e.key === 'End') {
e.stopImmediatePropagation();
e.stopPropagation();
}
if (e.key === 'Home' || e.key === 'End') {
// we don't want to prevent the default tab behaviour
e.preventDefault();
}
}
},
true
);
AFTER you have done that, you could add new event listeners to the grid, or depending on what you are trying to do, you could add listeners to specific cells as it mentions in the Keyboard Navigation section of the Ag-Grid docs under Custom Actions:
Custom Actions
Custom cell renderers can listen to key presses on the focused div.
The grid element that receives the focus is provided to the cell
renderers via the eGridCell parameter. You can add your own listeners
to this cell. Via this method you can listen to any key press and do
your own action on the cell eg hitting 'x' may execute a command in
your application for that cell.
I initially wrote this code for navigating home/end with command+arrow key, but have put comments where logic differs since 98% will be the same. Comments are untested but should work
I will divide this into 4 parts:
suppress the event so ag-grid does nothing by default
find a way for us to place a event listener on the right keys
compute which cell should be navigated to next
tell ag grid which cell should be selected
For #1, we can use suppressKeyboardEvent and either set it on defaultColDef(in `GridOptions´) or on every col def.
Mine looks like this:
const suppressKeyboardEventFn: ColDef["suppressKeyboardEvent"] = (
params: SuppressKeyboardEventParams
) => {
const key = params.event.key;
const isControl = isControlKey(params.event);
// For end/home, test for key === "Home" || key === "End" instead
const isNavigation =
key === "ArrowUp" ||
key === "ArrowDown" ||
key === "ArrowRight" ||
key === "ArrowLeft";
if (isNavigation && isControl) {
return true;
}
return false;
};
isControlKey is so it works on both mac&windows, and is written as recommended by MDN (not relevant if using home/end key):
const isMac = navigator.platform.startsWith("Mac");
export const isControlKey = (event: KeyboardEvent) => {
return isMac ? event.metaKey : event.ctrlKey;
};
For #2 where we want to handle the event ourselves, we can use onCellKeyDown:
const onCellKeyDownFn: GridOptions["onCellKeyDown"] = (cellKeyDown) => {
if (cellKeyDown.event == null) {
return;
}
const event = cellKeyDown.event as KeyboardEvent;
const key = event.key;
const isControl = isControlKey(event);
// Instead write cases here for case "Home": and case "End":
switch (key) {
case "ArrowUp": {
if (isControl) {
dispatch(navigateCell({ direction: "up", end: true }));
}
break;
}
case "ArrowDown": {
if (isControl) {
dispatch(navigateCell({ direction: "down", end: true }));
}
break;
}
case "ArrowRight": {
if (isControl) {
dispatch(navigateCell({ direction: "right", end: true }));
}
break;
}
case "ArrowLeft": {
if (isControl) {
dispatch(navigateCell({ direction: "left", end: true }));
}
break;
}
}
};
Using the same isControlKey function. I have implemented redux navigation actions that handles navigating to home and end.
For #3, we can implement this in different ways. Here is how I FIND the correct cell to navigate to. Either one step to a direction, or to the end/home (which is our scenario, since I pass end: true)
// For using Home/End, add a case for each and mix logic from
// below to find the correct cell. Last column logic is in
// right when end===true and last row is in down when end===true etc
switch (params.direction) {
case "up": {
let newRowIndex;
if (params.end === true) {
newRowIndex = 0;
} else {
newRowIndex = selectedCell.lastKnownRowIndex - 1;
if (newRowIndex < 0) {
return;
}
}
const node = gridApi.getDisplayedRowAtIndex(newRowIndex);
if (node?.id == null) {
log.warn("Could not find Node ID");
return;
}
dispatch(
selectCell({
nodeId: node.id,
colKey: selectedCell.colKey,
})
);
break;
}
case "down": {
let newRowIndex;
if (params.end === true) {
newRowIndex = maxRowIndex;
} else {
newRowIndex = selectedCell.lastKnownRowIndex + 1;
if (newRowIndex > maxRowIndex) {
return;
}
}
const node = gridApi.getDisplayedRowAtIndex(newRowIndex);
if (node?.id == null) {
log.warn("Could not find Node ID");
return;
}
dispatch(
selectCell({
nodeId: node.id,
colKey: selectedCell.colKey,
})
);
break;
}
case "right": {
let nextColumn;
if (params.end === true) {
const columns = columnApi.getAllGridColumns();
nextColumn = columns[columns.length - 1];
} else {
const column = columnApi.getColumn(selectedCell.colKey);
if (column == null) {
log.warn("Could not find column");
return;
}
nextColumn = columnApi.getDisplayedColAfter(column);
}
if (nextColumn == null) {
return;
}
dispatch(
selectCell({
nodeId: selectedCell.nodeId,
colKey: nextColumn.getColId(),
})
);
break;
}
case "left": {
let nextColumn;
if (params.end === true) {
const columns = columnApi.getAllGridColumns();
nextColumn = columns[1];
} else {
const column = columnApi.getColumn(selectedCell.colKey);
if (column == null) {
log.warn("Could not find column");
return;
}
nextColumn = columnApi.getDisplayedColBefore(column);
}
if (nextColumn == null) {
return;
}
dispatch(
selectCell({
nodeId: selectedCell.nodeId,
colKey: nextColumn.getColId(),
})
);
break;
}
default: {
assertNever(params.direction);
}
}
Lastly #4, here is parts of my selectCell implementation that can give you some idea of how to make sure ag-grid focuses the right cell.
This code will focus the cell, add a range highlight, add a row selection, and make sure that it is visible if the viewport needs to jump:
// no difference in logic when using Home/End!
// just make sure correct cell is passed
gridApi.ensureNodeVisible(node);
gridApi.ensureColumnVisible(params.colKey);
gridApi.clearRangeSelection();
gridApi.addCellRange({
rowStartIndex: rowIndex,
rowEndIndex: rowIndex,
columns: [params.colKey],
});
gridApi.setFocusedCell(rowIndex, params.colKey);
node.setSelected(true, true)

Do not submit empty form fields in ExtJS

I have an extjs form with fields. The user isn't required to enter data into each field so I do not want to submit the fields with no data. I want it to post only fields that actually have data. Is this possible?
I recommend using form's beforeaction event. While handling this event you can check all fields. If all values are empty just return false;. The following example works in ExtJS4 and has to work in ExtJS3:
myform.on('beforeaction', function(form, action) {
if (action.type == 'submit') {
var doSubmit = false, vals = form.getValues();
for (var i in vals)
if (vals[i] !== '') {
doSubmit = true;
break;
}
return doSubmit;
}
});
Actualy, the right way to not submit empty fields is to use action's submitEmptyText config. But it's not working in current version (ExtJS4.0.2a).
Another options is to override component's getSubmitValue() method and return null if this field is empty, this way it won't be included into submit fields.
{
xtype: 'combo',
getSubmitValue: function(){
var value = this.getValue();
if(Ext.isEmpty(value)) {
return null;
}
return value;
}
}
Instead of using form's submit, directly call Ext.Ajax.request(...) with the url, method type (GET/POST) and params (and any other options as explained in the call documentation).
To generate params, iterate over the form fields and check for null value before adding to params.
This bug is present in ExtJS 4.0.7 too.
As Molecule Man pointed:
Actualy, the right way to not submit empty fields is to use action's submitEmptyText config. But it's not working in current version (ExtJS4.0.2a).
A possible solution to fix this bug is by overriding 2 functions, getValues in "Ext.form.Basic" (where the bug is) and createForm (to create our basic form) in "Ext.form.Panel" by extension in the following way:
Ext.define("My.form.Basic", {
alias: "form.mybasic",
extend: "Ext.form.Basic",
getValues: function(asString, dirtyOnly, includeEmptyText, useDataValues) {
var values = {};
this.getFields().each(function(field) {
if (!dirtyOnly || field.isDirty()) {
var data = field[useDataValues ? "getModelData" : "getSubmitData"](includeEmptyText);
if (Ext.isObject(data)) {
var isArray = Ext.isArray;
Ext.iterate(data, function(name, val) {
if (includeEmptyText && val === "") {
val = field.emptyText || "";
}
if (includeEmptyText || ((!isArray(val) && val !== "") || (isArray(val) && val.length !== 0))) {
if (name in values) {
var bucket = values[name];
if (!isArray(bucket)) {
bucket = values[name] = [bucket];
}
if (isArray(val)) {
values[name] = bucket.concat(val);
}
else {
bucket.push(val);
}
}
else {
values[name] = val;
}
}
});
}
}
});
if (asString) {
values = Ext.Object.toQueryString(values);
}
return values;
}
});
Ext.define("My.form.Panel", {
alias: "form.mypanel",
extend: "Ext.form.Panel",
createForm: function() {
return Ext.create("My.form.Basic", this, Ext.applyIf({listeners: {}}, this.initialConfig));
}
});
The code is copied from the ext source code. The only change is inside the iteration of each field: introduced the following wrapping "if":
if (includeEmptyText || ((!isArray(val) && val !== "") || (isArray(val) && val.length !== 0)))
I am a bit late but, better later than never...