Tabulator: How to get a column of a column group? - tabulator

If you take a look at the first example at http://tabulator.info/examples/4.4#column-groups, how do I get a reference to the column "Personal Info", so I can toggle/show/hide it?
I tried it with var col = table.getColumn("Personal Info") but that did not work (as expected).
I would prefer a vanilla JS solution which uses the built-in tabulator API. But jQuery is also ok as an alternative.
Here is a jsfiddle https://jsfiddle.net/jmartsch/g7xewtf6/17/
I found out, that I can use console.log(table.getColumn('gender').getParentColumn());
This does work, but it is not very elegant. It would be nice to have a solution that directly selects the column group header.

const tabledatasimple=[{id:1,name:"Oli Bob",location:"United Kingdom",gender:"male",rating:1,col:"red",dob:"14/04/1984"},{id:2,name:"Mary May",location:"Germany",gender:"female",rating:2,col:"blue",dob:"14/05/1982"},{id:3,name:"Christine Lobowski",location:"France",gender:"female",rating:0,col:"green",dob:"22/05/1982"},{id:4,name:"Brendon Philips",location:"USA",gender:"male",rating:1,col:"orange",dob:"01/08/1980"},{id:5,name:"Margret Marmajuke",location:"Canada",gender:"female",rating:5,col:"yellow",dob:"31/01/1999"},{id:6,name:"Frank Harbours",location:"Russia",gender:"male",rating:4,col:"red",dob:"12/05/1966"},{id:7,name:"Jamie Newhart",location:"India",gender:"male",rating:3,col:"green",dob:"14/05/1985"},{id:8,name:"Gemma Jane",location:"China",gender:"female",rating:0,col:"red",dob:"22/05/1982"},{id:9,name:"Emily Sykes",location:"South Korea",gender:"female",rating:1,col:"maroon",dob:"11/11/1970"},{id:10,name:"James Newman",location:"Japan",gender:"male",rating:5,col:"red",dob:"22/03/1998"}];
const table = new Tabulator("#example-table", {
height: "311px",
data: tabledatasimple,
columnVertAlign: "bottom", //align header contents to bottom of cell
columns: [{
title: "Name",
field: "name",
width: 160
},
{ //create column group
title: "Work Info",
columns: [{
title: "Progress",
field: "progress",
align: "right",
sorter: "number",
width: 100
},
{
title: "Rating",
field: "rating",
align: "center",
width: 80
},
{
title: "Driver",
field: "car",
align: "center",
width: 80
},
],
},
{ //create column group
title: "Personal Info",
field: "pInfo",
columns: [{
title: "Gender",
field: "gender",
width: 90
},
{
title: "Favourite Color",
field: "col",
width: 140
},
{
title: "Date Of Birth",
field: "dob",
align: "center",
sorter: "date",
width: 130
},
],
},
],
});
const columns = table.getColumns(true);
doSomething = (colName) => {
columns.forEach((col) => {
if (col.getDefinition().field === colName) {
col.hide();
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/tabulator/4.4.3/js/tabulator.min.js"></script>
<link href="https://unpkg.com/tabulator-tables#4.4.1/dist/css/tabulator.min.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/tabulator/4.4.3/css/tabulator_modern.css" rel="stylesheet" />
<div id="example-table"></div>
<button id="hidePInfo" onclick="doSomething('pInfo')">Hide Personal Info</button>

Related

Why is the Tabulator getRows() function not working?

This seems like the simplest of requests but I can't seem to retrieve a set of rows from a Tabulator object.
Here's the code which instantiates the Tabulator object.........
function TabulatorInvitees(divId, companyName, userEmail) {
try {
var table = new Tabulator(divId, {
columns: [
{
title: "<div style='width:20%; float:left; text-align:left; color:blue; font-size:14px;'>Vendor Invitees</div>",
columns: [
{ title: "Id", field: "Id", visible: false },
{ title: "Added", field: "Added", visible: false },
{ title: "Changed", field: "Changed", visible: false },
{ title: "MarkedForExclusion", field: "MarkedForExclusion", visible: false },
{ title: "Email Address", field: "Email", widthGrow: 1, responsive: 0, hozAlign: "center", editor: "input", visible: true },
{ title: "First Name", field: "FirstName", widthGrow: 0.5, responsive: 1, hozAlign: "center", editor: "input", visible: true },
{ title: "Last Name", field: "LastName", widthGrow: 0.5, responsive: 1, hozAlign: "center", editor: "input", visible: true }
]
},
{
title: tabulatorAddUser(companyName),
field: "ManageRows",
widthGrow: 0.25,
responsive: 2,
hozAlign: "center",
formatter: "tickCross",
headerClick: function (e, row) {
row.getTable().addRow({ Id: 0, Added: true }, false);
},
cellClick: function (e, cell) {
tabulatorFreezeUnfreezeDelete(cell.getRow());
}
},
],
data: [],
height: "100%",
layout: "fitColumns", // required when using 'widthGrow'
placeholder: tabulatorPlaceholder(companyName), //display message to user on empty table
reactiveData: true, //enable reactive data
responsiveLayout: "collapse",
rowContextMenu: tabulatorContextMenu(),
});
table.on("rowTapHold", function (e, row) {
// from Tabulator documentation: "The rowTapHold event is triggered when a user taps on a row on a touch display and holds their finger down for over 1 second."
//e - the tap event object
//row - row component
tabulatorContextMenu();
});
table.on("tableBuilt", function () {
if (companyName.length > 0) {
table.setData(getDataSync({ caseSelector: "VendorMgmt_EmployeeList", companyCode: companyName, userEmail: userEmail }));
}
else {
table.setData([]);
}
});
}
catch (error) {
console.log(error);
}
}
The setData() function makes a call to a database function which returns three rows, similar to the following:
The following JQuery function is called when a radio button is clicked....
$(".vendorStatus").click(function (e) {
const status = e.target.value;
const tbls = Tabulator.findTable("#divVendorEmployees");
const tbl = tbls[0];
const tblRows = tbl.getRows();
console.log("tbls.length", tbls.length);
console.log("tblRows", tblRows);
});
The browser console indicates a table has been found (tbls.length = 1) but the tblRows array is empty:
I see the three rows in my Tabulator but I am not able to recall them programmatically. It seems like a simple problem which should have a simple answer.
I am using the most recent version of Tabulator (v5.4).
Any assistance is greatly appreciated.
After much searching, I finally came to the realization the DOM element associated with the Tabulator instance must be managed when attempting to refresh or replace data. I've implemented a method which allows me to delete and rebuild the DOM element each time I need to save data to my database and subsequently refresh my Tabulator instance.
Here's the code...
function refreshTabulatorObject(obj) {
let parentId = obj.parentId;
let childId = obj.childId;
//Empty and remove the current version of the [Tabulator] object.
const tables = Tabulator.findTable(childId);
if (tables.length > 0) {
var table = Tabulator.findTable(childId)[0];
table.setData([]);
}
//Remove the existing <div> from the DOM.
$(childId).remove();
//Re-create the <div> element for the [Tabulator] object and append it to the DOM.
var parentDiv = document.getElementById(parentId);
parentDiv.innerHTML = "";
var childDiv = document.createElement("div");
childDiv.setAttribute("id", childId);
parentDiv.appendChild(childDiv);
//Re-create the [Tabulator] object.
TabulatorInvitees("#" + childId, obj.companyName);
}
I'm sure those of you with a more intimate knowledge of Tabulator would likely suggest a more elegant method, however, this one appears to work and I've already spent far more time on this issue that I had anticipated. Unfortunately, elegance is not a luxury I can afford at this point.
I hope this solution might be of help to some other struggling soul.

Tabulator 4.5 get data from api but do not render the table with data

In a modal context , Tabulator get data from api but do not render the table.
If I put a sleep of 500 milliseconds before return json from the api, the data show up.
<div class="form-group">
<div id="tablePersonnages"></div>
</div>
<script type="text/javascript">
var table = new Tabulator("#tablePersonnages",({
pagination: "local",
paginationSize: 10,
history: true,
ajaxURL: '#Url.Action("ObtenirPersonnages", "FicheHistorique")',
ajaxParams: { idFiche: '#Model' },
ajaxConfig: "POST",
layout: "fitColumns",
locale: true,
langs: {
"fr-fr": {
"ajax": {
"loading": "Chargement", //ajax loader text
"error": "Erreur" //ajax error text
},
"pagination": {
"first": "Début", //text for the first page button
"first_title": "Première page", //tooltip text for the first page button
"last": "Fin",
"last_title": "Dernière page",
"prev": "Préc",
"prev_title": "Page précédente",
"next": "Suiv",
"next_title": "Page suivante"
}
}
},
columns: [ //Define Table Columns
{ title: "Id", field: "Id", visible: false },
{ title: "Nom", field: "Nom", headerFilter: "input", headerFilterPlaceholder: " " },
{ title: "Prenom", field: "Prenom", headerFilter: "input", headerFilterPlaceholder: " " },
{ title: "Fonction", field: "Fonction", headerFilter: "input", headerFilterPlaceholder: " " },
{ title: "Naissance", field: "Naissance" },
{ title: "Deces", field: "Deces" },
{ formatter: link, width: 10 }
]
}));
On Modal Open Event
Call table.redraw(true) If still doesn't work put the redraw in a setTimeout()

I have a tabulator table, align

I have a tabulator table, with three columns that are align to the right, but if the "value" in the first column is "xxx", the value in the cell need to be change to be align to the left, is this possible?
var table = new Tabulator("#example_table", {
layout: "fitDataFill",
placeholder: "No Data Set Found",
columns: [{
title: "name",
field: "name",
sorter: "string",
headerFilter: "input",
headerFilterPlaceholder: "Filter Exception Name",
formatter: "label",
width: 70,
},
{
title: "name value",
field: "namevalue",
sorter: "string",
headerFilterPlaceholder: "Filter Exception Policy Data",
headerFilter: "input",
formatter: celldataswith,
align: "right"
},
{
title: "permited value",
field: "permitedvalue",
sorter: "string",
headerFilterPlaceholder: "Filter Exception Criteria",
headerFilter: "input",
formatter: celldataswith,
align: "right"
},
{
title: "breach value",
field: "breachvalue",
sorter: "string",
headerFilterPlaceholder: "Filter Exception Breach",
headerFilter: "input",
formatter: celldataswith,
align: "right"
}
],
rowFormatter: function(row, cell) {
//row - row component
var dataExceptionName = row.getData().Name;
if (dataExceptionName == "xxx") {
row.getElement().style.backgroundColor = "#A6A6DF";
**cell.getData().namevalue.style.align = "left";
cell.getData().permitedvalue.style.align = "left";
cell.getData().breachvalue.style.align = "left";**
}
},
});
You can use a custom cell formatter to achieve this, define the formatter outside the table, then reference it in the column definitions
//define formatter
var alignFormatter = function(cell, formatterParams, onRendered){
var data = cell.getData();
if(data.name === "xxx"){
cell.getElement().style.align = "left";
}else{
cell.getElement().style.align = "right";
}
}
//column definition
{title: "name value", field: "namevalue", formatter:alignFormatter},

Tabulator 4.2: sorter:"date" not working?

Even in the example given # the Tabulator site:
http://tabulator.info/basic/4.2
the date column does not sort, unlike the others. Is there a fix for that?
Date sorting for Tabulator is dependent on MomentJS.
Import Moment Js to your code
{title: "Date Of Birth", field: "dob", sorter:"date", sorterParams:{format:"DD/MM/YY"}},
Please check this Snippet
const tabledata1 = [
{id: 1, name: "Oli ", money: "0", col: "red", dob: "14/05/1982"},
{id: 2, name: "Mary ", money: "0", col: "blue", dob: "14/05/1982"},
{id: 3, name: "Christine ", money: "0", col: "green", dob: "22/05/1982"},
{id: 4, name: "Brendon ", money: "0", col: "orange", dob: "01/08/1980"},
{id: 5, name: "Margret ", money: "0", col: "yellow", dob: "31/01/1999"},
];
const table = new Tabulator("#example-table", {
height: 205, // set height of table (in CSS or here), this enables the Virtual DOM and improves render speed dramatically (can be any valid css height value)
data: tabledata1, //assign data to table
layout: "fitColumns", //fit columns to width of table (optional)
columns: [ //Define Table Columns
{title: "Name", field: "name", width: 150},
{
title: "money",
field: "money",
align: "left",
formatter: "money"
},
{title: "Favourite Color", field: "col"},
{title: "Date Of Birth", field: "dob", sorter:"date", sorterParams:{format:"DD/MM/YY"}},
]
});
function removeData() {
table.clearData();
}
function update() {
table.updateOrAddData(tabledata2);
// table.addData(tabledata2);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://unpkg.com/tabulator-tables#4.2.4/dist/js/tabulator.min.js"></script>
<link href="https://unpkg.com/tabulator-tables#4.2.4/dist/css/tabulator.min.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-3.4.0.min.js"></script>
<div id="example-table"></div>

how to Cancel Edit in tabulator

after editing data in any row how to allow the user to cancel the edited data to go back to original data ,
cannot reload the whole table as this will cancel all edited rows , i only need to cancel one row
the undo function "table.undo();" need to be called many times to undo the whole row ,is there some thing like "row.undo();"
i would like to code to look something like blow
var ivInvGRNDGrid = new Tabulator("#ivInvGRNDGrid", {
ajaxURL: "/abc/abcd/GetData",
layout: "fitColumns",
index: "id",
columns: [
{ title: "Delete", formatter: DeleteIcon, width: 40, align: "center", cellClick: function (e, cell) { ivInvGRNDDelete(cell.getRow().getData().id); }, headerSort: false },
{ title: "Cancel Edit", formatter: UndoIcon, width: 40, align: "center", cellClick: function (e, cell) { row.undo(); }, headerSort: false },
{ id: "ID", title: "#Localizer["ID"]", field: "iD", headerToolTip: "#Localizer["IDtip"]", validator: "required", editor: "number", visible: false, sorter: "number", editable: Editable },
{ id: "ItemID", title: "#Localizer["ItemID"]", field: "itemID", headerToolTip: "#Localizer["ItemIDtip"]", validator: "required", editor: "number", validator: "required", minWidth: 120, editable: Editable },
],
});
There is no row undo function i'm afraid, but you can restore the previous value of a cell by calling the restoreOldValue on the cell component. so in the cellClick function on your cancel edit row you could do something like this:
function(e, cell){
cell.getRow().getCells().forEach(function(cell){
var oldVal = cell.getOldValue();
if(oldVal !== null){
cell.restoreOldValue();
}
})
}

Resources