Is there a way to create a custom column in Tabulator that displays a calculated value for every row?

Can a custom column be added with a calculated value for each row? For example, if col 1 has the value "3" and col 2 has the value "5", then I want a dynamic col 3 with a sum value of 8.

I am utilizing Vue Tabulator. Below is my Table.vue component.

<template>
    <div v-if="tabledata" class="w-full p-3 border border-gray-200 shadow-xl rounded-lg  mt-10">
        <VueTabulator id="usersData" v-model="tabledata" :options="options" />
    </div>
</template>
<script>
export default {
    data(){
        return{
            tabledata: [
                {
                    "name": "Hron",
                    "lvl2": 5,
                    "lvl3": 0,
                    "score": 5
                },
                {
                    "name": "Zhr",
                    "lvl2": 2,
                    "lvl3": 1,
                    "score": null
                },
                {
                    "name": "Mang",
                    "lvl2": 4,
                    "lvl3": 1,
                    "score": null
                }
            ],
            options: {
                layout:"fitColumns",
                columns: [
                    {title:"S#", formatter:"rownum", width:70, align:"center", responsive:3},
                    {title:"Name", field:"name", minWidth:150},
                    {title:"Lvl 2", field:"lvl2", sorter:"number", align:"center", formatter:"money", formatterParams:{precision:false}, bottomCalc:"sum", minWidth:80},
                    {title:"Lvl 3", field:"lvl3", sorter:"number", align:"center", formatter:"money", formatterParams:{precision:false}, bottomCalc:"sum", minWidth:80},
                    {title:"Score", field:"score", sorter:"number", align:"center", formatterParams:{precision:true}, bottomCalc:"avg"}
                ]
            }
        }
    }
}
</script>

The desired output inside the table should look like this:

[
  {
    "name": "Hron",
    "lvl2": 5,
    "lvl3": 0,
    "score": 5
  },
  {
    "name": "Zhr",
    "lvl2": 2,
    "lvl3": 1,
    "score": 3
  },
  {
    "name": "Mang",
    "lvl2": 4,
    "lvl3": 1,
    "score": 5
  }
]

I have checked the documentation but couldn't find any relevant information.

Thank you

Answer №1

To achieve this, it is recommended to utilize a mutator function.

Consider starting with sample data that includes two columns and their respective values:

var data = [
    {col1:27, col2:55}
];

Create a custom mutator function to calculate the sum of these two columns:

var customMutator = function(value, data, type, params, component){
    //value - original value of the cell
    //data - row's data
    //type - type of mutation (data|edit)
    //params - mutatorParams object from column definition
    //component - contains cell component if type is "edit", otherwise column component

    return data.col1 + data.col2; //sum of the two columns
}

In the column definition, add a third column with a unique field name and assign the custom mutator function to the mutator property:

columns:[
    {title:"Column 1", field:"col1"},
    {title:"Column 2", field:"col2"},
    {title:"Sum Column", field:"sumCol", mutator:customMutator}, //calculate sum of two columns
]

For more information, refer to the Mutator Documentation

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to implement an AppBar that fades in and out when scrolling within a div?

I'm trying to implement a Scrollable AppBar that hides on scroll down and reappears when scrolling up. Check out this image for reference To achieve this functionality, I am following the guidelines provided by Material-UI documentation export defa ...

issues with the handler not functioning properly in html and javascript

<form method="post" action="."> <label class="input-label">Enter Your First Name</label><input field="first_name" class="input-edit" maxlength="30" type="text" value="{{ user.first_name }}" /> <label class="i ...

Tips for creating a Vuex mutation without using asynchronous promises

I have a project underway that involves building an app using Vue.js, Vuex, and Firebase to update data from Firestore database to the state in mutations. Even though mutations are synchronous and promises (.then) are asynchronous, my current implementat ...

The disappearance of the "Event" Twitter Widget in the HTML inspector occurs when customized styles are applied

Currently, I am customizing the default Twitter widget that can be embedded on a website. While successfully injecting styles and making it work perfectly, I recently discovered that after injecting my styles, clicking on a Tweet no longer opens it in a ne ...

Personalized JQuery popup before leaving the page

Looking to display a unique jQuery dialog box with options for Yes, No, and Cancel when a user attempts to navigate away from the current page or close the window. The default browser dialog confirmation is displayed on the beforeload event, but we are tr ...

JavaScript promise will return a value that is undefined

Trying to pass a jQuery ajax request through a promise like this: var foo; foo = bar().then(function(response) { console.log("Success!", response); console.log(foo[0].bool); }, function(error) { console.error("Failed!", error); }); console.lo ...

Bringing in a feature within the Vue 3 setup

At the moment, I am attempting to utilize a throttle/debounce function within my Vue component. However, each time it is invoked, an error of Uncaught TypeError: functionTD is not a function is thrown. Below is the code snippet: useThrottleDebounce.ts imp ...

Preserving form data using JavaScript exclusively upon submission

Hey there! I'm facing a little issue with a Form that has multiple checkboxes and a piece of JavaScript code designed to save the state of each checkbox when the user hits submit. My problem is that, currently, the checkbox state is being saved even i ...

I am eager to create a Material-UI textfield using an array

My current task involves utilizing TextField based on an Array, but I am facing an issue with dynamically changing all the values. I understand that I can employ ternary conditions to accomplish this task effectively. const TextField = () => { r ...

Encountering TS2344 error when referring to the Component Ref in Vue.js during typing operations

I received a component reference on my FormCheckbox component from a patternlib. When I tried to incorporate the component into my own TestComp component, I encountered this TypeScript error that left me puzzled: TS2344: Type '{ name: string; mixins: ...

Prevent duplicate key errors when performing bulk insert operations with MongoDB

Is there a way to perform a bulk insert and proceed even if a duplicate key error occurs? I have a collection with a unique index on the id field (not _id) and some existing data. I need to add new data to the collection while skipping any documents that ...

Determining if a method's timeout has been triggered while running on a periodic basis in JavaScript

Within my JavaScript code, I have implemented a method that runs every 5 minutes. However, after 15 minutes, I want to stop this method from executing. var tChk ; tChk = setInterval("test()", 5*60*1000); setTimeout("timeOut(tChk)", 15*60*1000); // 15 mins ...

Converting an MVC form into JSON using Jquery

I am encountering an issue with serializing my MVC form to JSON using JQuery and then deserializing some values, like the input field value, on the backend in C#. I have tried to serialize it in JSON without success. Can someone please assist me with this ...

What is the best way to generate a new div element when the content exceeds the preset height of the current div?

CSS .page{ width: 275px; hight: 380px; overflow: auto; } HTML <div class="page">dynamic text</div> Is there a way to automatically create new div elements when dynamic text overflows past the fixed height of the init ...

What is the best way to retrieve the file name from the current document's URL using JavaScript?

I need help with a Javascript function that can extract the current file name without any parameters. $(location).attr('href').match(/([a-zA-Z\-\_0-9]+\.\w+)$/); var current_path = RegExp.$1; if ((current_path == 'index. ...

Learning to transform EST time data into local time within JavaScript utilizing moment.js and Date objects

The recorded date and time is "03/19/2020 13:15:00" in Eastern Standard Time (EST). When attempting to convert it to the local timezone, I have tried various methods, such as using moment.js to change the format from 'MM/DD/YYYY HH:mm:ss' to UT ...

Search through a JSON array to find a specific element and retrieve the entire array linked to that element

Recently, I've been working with a json array that dynamically increases based on user input. Here's a snippet of the json code I'm dealing with: [{"scheduleid":"randomid","datestart":"2020-06-30",&quo ...

Tips for updating a JSON object value in Node.js

Storing a JSON object in a JSON file is important for passing data during an API call. To update the object, replace "it-goes-here" with the following {} block. Newly updated data: { "parenturl":"xxx.com", "user ...

Tips for incorporating a spinner during content loading within AngularJS

When the user clicks on the "Search" button, content will load and the button label will change to "Searching" with a spinner shown while the content is loading. Once the content has loaded (Promise resolved), the button label will revert back to "Search" ...

Manipulate paths in JS/JQuery by dynamically adding parameters with an indefinite number of values

My JavaScript script relies on an AJAX call that adds a parameter to an HTML request, but I've encountered two issues. I'm struggling to find a straightforward method to retrieve the pathname with parameters. With pure JavaScript, location.path ...