Given the sample code using ag-grid with Vue 3
<script setup lang="ts">
import "ag-grid-community/dist/styles/ag-grid.css";
import "ag-grid-community/dist/styles/ag-theme-alpine.css";
import { AgGridVue } from "ag-grid-vue3";
import { ref } from "vue";
const columnDefs = ref([
{
field: "person",
},
{
field: "car",
},
]);
const rowData = ref([
{
person: "person-1",
car: "car-1",
},
{
person: "person-1",
car: "car-2",
},
{
person: "person-1",
car: "car-3",
},
{
person: "person-2",
car: "car-4",
},
{
person: "person-3",
car: "car-5",
},
{
person: "person-3",
car: "car-6",
},
]);
</script>
<template>
<ag-grid-vue
style="width: 500px; height: 500px"
class="ag-theme-alpine"
:columnDefs="columnDefs"
:rowData="rowData"
>
</ag-grid-vue>
</template>
You will get the following output
I could group the table based on person but is there a way to merge cells in a single column?
I think I can't use row-spanning for a single column definition because inside the rowSpan function it is not possible to tell ag-grid to combine multiple cells of a single column.
Any ideas?
After spending a few hours on this requirement, I came up with the solution.
Here are the steps which I performed :
To implement rowSpan, You have to manipulate the rowData so that it will contain the person property only in the first occurance object. As a result, When we will apply the rowSpan based on the length it will not take that length for each same person name. This is how I manipulated the rowData :
const uniq = {};
const rowData = [{
person: "person-1",
car: "car-1",
}, {
person: "person-1",
car: "car-2",
}, {
person: "person-1",
car: "car-3",
}, {
person: "person-2",
car: "car-4",
}, {
person: "person-3",
car: "car-5",
}, {
person: "person-3",
car: "car-6",
}];
rowData.forEach(obj => {
!uniq[obj.person] ? uniq[obj.person] = true : delete obj.person;
});
console.log(rowData);
Now, Created a rowSpan function which is basically used to return the length of the objects contains occurrence of same person names.
function rowSpan(params) {
const person = params.data.person;
const gridData = getData(); // getData() with return the original rowData array.
return gridData.filter((e) => e.person === person).length;
}
At the end, for styling the rowSpan columns. I used these styles (refer from here)
.show-cell {
background: white;
border-left: 1px solid lightgrey !important;
border-right: 1px solid lightgrey !important;
border-bottom: 1px solid lightgrey !important;
}
This is how the columnDefs for person object looks like :
{
field: "person",
rowSpan: rowSpan,
cellClassRules: { 'show-cell': 'value !== undefined' }
}
Live Demo : Row Spanning Demo
Are you sure row-spanning will not work? Can you try to implement this?
function rowSpan(params) {
const person = params.data.person;
return rowData.value.filter((e) => e.person === person).length;
}
const columnDefs = ref([
{
field: "person",
rowSpan: rowSpan,
},
{
field: "car",
},
]);
Related
I have a triple-nested JSON object where initially all of the data displays in one Tabulator table. For example, this hospital data is a list of diagnosis codes for each patient visit per each patient's medical record. I want to filter by a diagnosis code and display only those patient medical records/ accounts that contain the diagnosis code and redisplay in the same table. Is this possible to do with Tabulator functions?
Basically, how can I display a list of only those 'medical records > patient accounts > diagnosis codes' that contain the 'D55.0' dx_code. If I where to search by a diagnosis code that is not attached to any account, like A01.00, then nothing would display.
var patient_data = [{
med_rec_num:123,
patient_name:"Mickey Mouse",
phone:"123456789",
age:91,
visit_list: [{
account_num: "A0001",
doctor: "Dr. Pepper",
location: "Cardiology",
diagnosis_list: [{
num: 1,
dx_code: "V95.43XA",
visit_type: "Outpatient",
poa: 'Y'
},
{
num: 2,
dx_code: "V95.00A",
visit_type: "Outpatient",
poa: 'N'
},
{
num: 3,
dx_code: "D55.0",
visit_type: "Outpatient",
poa: 'Y'
}
]
},
{
account_num: "A0002",
doctor: "Dr. Dre",
location: "Radiology",
diagnosis_list: [{
num: 1,
dx_code: "K56.60",
visit_type: "Inpatient",
poa: 'Y'
},
{
num: 2,
dx_code: "Z71.89",
visit_type: "Inpatient",
poa: 'Y'
}
]
}
]
},
{
med_rec_num:456,
patient_name:"Jane Smith",
phone:"987654321",
age:50,
visit_list: [{
account_num: "B0001",
doctor: "Dr. Happy",
location: "Pharmacology",
diagnosis_list: [{
num: 1,
dx_code: "Z71.89",
visit_type: "Inpatient",
poa: 'Y'
},
{
num: 2,
dx_code: "D55.0",
visit_type: "Outpatient",
poa: 'N'
}
]
}
]
}
]
const table = new Tabulator("#example-table", {
data: patient_data,
//height: "311px",
layout: "fitColumns",
resizableColumns: false,
index: "med_rec_num",
columns: [
{formatter: plusIcon, width: 55, hozAlign:"center", tooltip: "Click to expand for Visits info", title:"Visits", headerSort:false, cellClick:function(e, row, formatterParams){
const id = row.getData().med_rec_num;
$(".visitTable" + id + "").toggle();}
},
{title:"Medical Record Num", field:"med_rec_num"},
{title:"Patient Name", field:"patient_name"},
{title:"Phone", field:"phone"},
{title:"Age", field:"age"}
],
rowFormatter: function(row, e) {
//create and style holder elements
var holderEl = document.createElement("div");
var tableEl = document.createElement("div");
const id = row.getData().med_rec_num;
holderEl.style.boxSizing = "border-box";
holderEl.style.padding = "10px 10px 10px 10px";
holderEl.style.borderTop = "1px solid #333";
holderEl.style.borderBotom = "1px solid #333";
holderEl.style.background = "#ddd";
//holderEl.style.display = "none";
holderEl.setAttribute('class', "visitTable" + id + "");
tableEl.style.border = "1px solid #333";
//tableEl.style.display = "none";
tableEl.setAttribute('class', "visitTable" + id + "");
holderEl.appendChild(tableEl);
row.getElement().appendChild(holderEl);
var visitTable = new Tabulator(tableEl, {
layout: "fitColumns",
data: row.getData().visit_list,
index: "account_num",
columns: [
{formatter: plusIcon, width: 55, hozAlign:"center", tooltip: "Click to expand for Dx Codes info", title:"Dx Codes", headerSort:false, cellClick:function(e, row, formatterParams){
const id = row.getData().account_num;
$(".diagnosisTable" + id + "").toggle();}
},
{title: "Account#",field: "account_num"},
{title: "Doctor",field: "doctor"},
{title: "Location", field: "location"},
],
rowFormatter: function(row, e) {
//create and style holder elements
var holderEl = document.createElement("div");
var tableEl = document.createElement("div");
const id = row.getData().account_num;
holderEl.style.boxSizing = "border-box";
holderEl.style.padding = "10px 10px 10px 10px";
holderEl.style.borderTop = "1px solid #333";
holderEl.style.borderBotom = "1px solid #333";
holderEl.style.background = "#ddd";
//holderEl.style.display = "none";
holderEl.setAttribute('class', "diagnosisTable" + id + "");
tableEl.style.border = "1px solid #333";
//tableEl.style.display = "none";
tableEl.setAttribute('class', "diagnosisTable" + id + "");
holderEl.appendChild(tableEl);
row.getElement().appendChild(holderEl);
//--------------------------------------------------------------- filter here?
let filterField = document.getElementById("filter-field");
document.getElementById("filter-trigger").addEventListener("click", function() {
console.log(filterField.value); // why is this not working?
diagnosisTable.setFilter("dx_code", "=", filterField.value);
table.redraw();
});
document.getElementById("clear-trigger").addEventListener("click", function() {
console.log(filterField.value); // why is this not working?
diagnosisTable.removeFilter("dx_code", "=", filterField.value);
table.redraw();
});
//--------------------------------------------------------------- filter ^here^?
var diagnosisTable = new Tabulator(tableEl, {
layout: "fitColumns",
data: row.getData().diagnosis_list,
index: "id",
columns: [
{title: "Num",field: "num"},
{title: "Dx Code",field: "dx_code"},
{title: "Type",field: "visit_type"},
{title: "P.O.A",field: "poa"}
]
}) // end of diagnosisTable tabulator
} // end of row formatter that hold diagnosisTable
}) // end of visitTable tabulator
} // end of row formatter that holds visitTable
}); // end of table tabulator
Please see my https://jsfiddle.net/zippyzuzka/zo3f5eqs/2/
Ideally, the table would initially display with every tier collapsed instead of each tier expanded (which I have coded), and still be able to filter via a 3rd tier property (which I do not have coded).
Also note that the entire data set - patient_data - is created after a form submit and sent to the table via AJAX, if that helps anything. (not in JSFiddle code however).
Also, I am extremely new to anything JavaScript, so my understanding is pretty little. I would imagine this would require maybe a custom filter of sorts? I've tried to add an event-click-listener to be able to table.setFilter("dx_code", "=", filterField.value); but it's not working. I don't know how to recursively retrieve the parent properties.
THANK YOU! THANK YOU!
I currently have some code which takes an array of javascript objects and generates an html list based on it, I want to display the corresponding image with the text in the list. But currently I can only get it to display the address if the image of text. Any help would be appreciated thanks!
HTML
<form>
<p>Please insert the items</p>
<input type="text" id="box" />
</form>
<div id="root"></div>
CSS
ul {
border: 2px solid grey;
border-radius: 5px;
padding: 1em;
}
li {
display: inline-block;
padding: 0.5em;
}
JS
const catalog = {
GalaxyTablet: {
name: "GalaxyTablet",
key: "galaxytablet",
keywords: ["galaxy", "tablet", "samsung"],
price: 800,
image: "https://www.jbhifi.co.nz/FileLibrary/ProductResources/Images/150044-M-HI.jpg"
},
GalaxyPhone: {
name: "GalaxyPhone",
key: "galaxyphone",
keywords: ["galaxy", "phone", "samsung"],
price: 1000,
image: "https://assets.kogan.com/files/product/etail/Samsung-/S10WHT_03.jpg?auto=webp&canvas=753%2C502&fit=bounds&height=502&quality=75&width=753"
},
HTCPhone: {
name: "HTCPhone",
key: "htcphone",
keywords: ["htc", "phone"],
price: 650,
image: "https://cdn.mos.cms.futurecdn.net/ca063713e185be46e62ec2eb3762a540.jpg"
},
};
const form = document.querySelector("form");
form.addEventListener("submit", submitHandler);
function submitHandler(event) {
event.preventDefault();
const searchTerm = form.box.value;
const results = search(searchTerm);
render(results);
}
function search(searchTerm) {
return Object.keys(catalog)
.filter((key) => catalog[key].keywords.includes(searchTerm.toLowerCase()))
.map((key) => catalog[key]);
}
function render(results) {
const root = document.querySelector("#root");
const list = results.map(itemToLi).join("");
root.innerHTML = `<ul>
${list}
</ul>`;
}
function itemToLi(item) {
return `<li>${item.name}</li>$ ${item.price}<li> <li>${item.image}<li>`;
}
You're only getting the URI text because that is what you are outputting:
<li>${item.image}<li>
You need to create an img tag:
<li><img src="${item.image}"></li>
Here's a small demo with the contents of your catalog:
const catalog = {
GalaxyTablet: {
name: "GalaxyTablet",
key: "galaxytablet",
keywords: ["galaxy", "tablet", "samsung"],
price: 800,
image: "https://www.jbhifi.co.nz/FileLibrary/ProductResources/Images/150044-M-HI.jpg"
},
GalaxyPhone: {
name: "GalaxyPhone",
key: "galaxyphone",
keywords: ["galaxy", "phone", "samsung"],
price: 1000,
image: "https://assets.kogan.com/files/product/etail/Samsung-/S10WHT_03.jpg?auto=webp&canvas=753%2C502&fit=bounds&height=502&quality=75&width=753"
},
HTCPhone: {
name: "HTCPhone",
key: "htcphone",
keywords: ["htc", "phone"],
price: 650,
image: "https://cdn.mos.cms.futurecdn.net/ca063713e185be46e62ec2eb3762a540.jpg"
}
};
const root = document.querySelector("#root");
const list = Object.values(catalog).map(itemToLi).join("");
root.innerHTML = `<ul>
${list}
</ul>`;
function itemToLi(item) {
return `<li>${item.name}</li>$ <li>${item.price}</li> <li><img src="${item.image}"></li>`;
}
<div id="root"></div>
You need to use img tag to render image. Also do not forget to use alt attribute inside that.
You can update your existing JavaScript method itemToLi as :
function itemToLi(item) {
return `<li>${item.name}</li>$ <li>${item.price}</li> <li><img src="${item.image}" alt=">${item.name}"></li>`;
}
How do I create a dynamical filter using a computed property from vue when the dataset is from a graphql-query?
I've looked at several articles that all use the array.filter()-method, but I can't get it to work on my dataset (dummy data below):
books: [{
node: {
title: 'Elon Musk',
by:'Ashlee Vance',
},
node: {
title: 'Steve Jobs',
by:'George Llian',
},
node: {
title: 'Face of Facebook',
by: 'Sandip Paul',
},
node: {
title: 'Tim Cook',
by:'Andy Atkins',
url:'http://www.voidcanvas.com/'
},
node: {
title: 'Abdul Kalam',
by:'Arun Tiwari',
},
node: {
title: 'Story of Elon Musk',
by:'BP John',
},
node: {
title: 'Story of Bill Gates',
by:'Russel Crook',
},
node: {
title: 'Becoming Steve Jobs',
by:'Andrew Russel',
}
}]
Method:
computed: {
filteredBooks: function () {
var books_array = this.books,
searchString = this.searchString;
if(!searchString) {
return books_array;
}
searchString = searchString.trim().toLowerCase();
books_array = books_array.filter(function(item) {
if(item.node.title.toLowerCase().indexOf(searchString) !== -1) {
return item;
}
});
return books_array;
}
HTML:
<div id="app">
<input type="text" v-model="searchString" placeholder="search" />
<ul style="list-style: none;">
<li v-for="book in filteredBooks">
<p>{{book.title}} -by- {{book.by}}</p>
</li>
</ul>
</div>
This is my first coding project since early 2000, so please feel free to point me in the right direction if this is the wrong forum for this question.
I set up a jsfiddle to play with the case.
Here is the code with some modifications:
var app = new Vue({
el: '#app',
data: {
searchString: '',
books: [{
title: 'Elon Musk',
by: 'Ashlee Vance'
},
{
title: 'Steve Jobs',
by: 'George Llian'
},
{
title: 'Face of Facebook',
by: 'Sandip Paul'
},
{
title: 'Tim Cook',
by: 'Andy Atkins',
url: 'http://www.voidcanvas.com/'
},
{
title: 'Abdul Kalam',
by: 'Arun Tiwari'
},
{
title: 'Story of Elon Musk',
by: 'BP John'
},
{
title: 'Story of Bill Gates',
by: 'Russel Crook'
},
{
title: 'Becoming Steve Jobs',
by: 'Andrew Russel'
}
]
},
computed: {
filteredBooks: function() {
return this.books.filter(e => this.searchString === '' ? false : e.title.toLowerCase().indexOf(this.searchString.toLowerCase()) !== -1 ? true : false);
}
}
});
body {
background-color: #dbd8d8;
padding: 20px;
}
input {
width: 300px;
height: 30px;
padding: 0.2rem;
}
.design {}
p {
position: relative;
display: block;
padding: .4em .4em .4em 2em;
margin: .5em 0;
border: 3px solid white;
background: #FC756F;
color: #444;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<input type="text" v-model="searchString" placeholder="search" />
<ul style="list-style: none;">
<li v-for="book in filteredBooks">
<p>{{book.title}} -by- {{book.by}}</p>
</li>
</ul>
</div>
Remove the node: from before the objects in the books data array - books array should contain a bunch of plain objects. If you put node: before each object, then you "say" that the every node is the key of key-value pair of an object (so the keynames will be identical - node!!!)
Simplify filteredBooks computed - no need to store all the variables. This function (filteredBooks) doesn't change the inputs, so you can use this here. The filter() functions doesn't change the array it filters - rather it returns a new array, containing only values that the iteratee function "saw" as true
You check for !searchString and that's never the case - searchString is always going to be true as you initialize it with searchString: '' (an empty value - but a value), so I changed it checking for the empty value in the filteredBooks computed.
I modified the code so that it compares lowercase to lowercase. With your code if someone typed a search string in uppercase, then there'd have been no match.
[![Firefox Console][1]][1]In my Vue app I am trying to use mdb-datatable, the table reads data() and sets the rows accordingly. I am setting the row data programmatically after my data is loaded with Ajax. In one column I need to add a button and it needs to call a function. I am trying to add onclick function to all buttons with "status-button" class but something weird happens.
When I print HtmlCollection it has a button inside, which is expected but I can't reach proceedButtons[0], it is undefined. proceedButtons.length also prints 0 length but I see the button in console.
I also tried to add onclick function but probably "this" reference changes and I get errors like "proceedStatus is not a function" it does not see anything from outer scope.
<mdb-datatable
:data="tableData"
:searching="false"
:pagination="false"
:responsive="true"
striped
bordered/>
export default {
name: "Applications",
mixins: [ServicesMixin, CommonsMixin],
components: {
Navbar,
Multiselect,
mdbDatatable
},
data () {
return {
statusFilter: null,
searchedWord: '',
jobRequirements: [],
applications: [],
options: ['Awaiting', 'Under review', 'Interview', 'Job Offer', 'Accepted'],
tableData: {
columns: [
{
label: 'Name',
field: 'name',
sort: 'asc',
},
{
label: 'Date',
field: 'date',
sort: 'asc'
},
{
label: 'Compatibility',
field: 'compatibility',
sort: 'asc'
},
{
label: 'Status',
field: 'status',
sort: 'asc'
},
{
label: 'Proceed Application Status',
field: 'changeStatus',
}
],
rows: []
}
}
}
fillTable(applications) {
let statusButtonId = 0;
applications.forEach(application => {
this.tableData.rows.push({
name: application.candidateLinkedIn.fullName,
date: this.parseDateFromDateObject(application.applicationDate),
compatibility: this.calculateJobCompatibility(application.candidateLinkedIn.linkedInSkillSet),
status: application.applicationStatus,
changeStatus: '<button type="button" class="btn-indigo btn-sm m-0 status-button"' +
' style="margin-left: 1rem">' +
'Proceed Status</button>',
candidateSkillSet: application.candidateLinkedIn.linkedInSkillSet
});
statusButtonId++;
});
},
addEventListenersToButtons() {
let proceedButtons = document.getElementsByClassName("status-button")
console.log(proceedButtons);
console.log(proceedButtons[0])
console.log(proceedButtons.item(0))
/*
proceedButtons.forEach(button => {
button.addEventListener("click",this.proceedStatus);
});
*/
},
[1]: https://i.stack.imgur.com/zUplv.png
From MDN:
Get the first element with a class of 'test', or undefined if there is no matching element:
document.getElementsByClassName('test')[0]
So undefined means no match, even if length is 0...
Since this is not an array, you do not get out-of-bounds exceptions.
https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName
Regarding Arrays
You can't index the list returned from getElementsByClassName.
You can turn it into an array though, and then index it.
ES6
let proceedButtons = document.getElementsByClassName("status-button")
const arr = Array.from(proceedButtons);
console.log(arr[0]);
Old School
const arr = []
Array.prototype.forEach.call(proceedButtons, function(el) {
arr.push(el);
});
console.log(arr[0]);
I'm wondering how can I pass an array in ListModel?
ok, In QML I have a ListView and I set it's ListModel like so:
model: ListModel
{
id: myList
ListElement
{
name: ""
card: 0
books: []
}
}
I can append to it by using:
myList.append({name:"terry", card:00100, books:["024589","865976","879582","215645"]});
but when I try to output it on screen I get this.
{
"card": 00100
"books": {
"objectName": "",
"count": 4,
"dynamicRoles": false
},
"name": "terry",
"name": "terry"
}
I'm not sure why I'm getting 2 names though! and how can I get the value of books?
I look up the QML documentation of ListModel and ListElement couldn't find anything related to passing an array, all the examples are integer or string.
Any idea how I can get the date?
I did work around it by calling the array in Delegate with Component.onCompleted:{} but I believe that's not a good/correct way since Delegate is not responsible for holding the data and should be done in Model, please do correct me if I'm wrong.
Thanks for your time.
Edit01: Thanks for the reply, here is the reason I need array:
I have a ComboBox in Delegate like so:
delegate: Rectangle
{
id: rowID
width: 50
height: 40
color: "#323232"
Row
{
anchors.fill: parent
anchors.leftMargin: 10
anchors.rightMargin: 10
Label{
id: nameID
text: name
font.pixelSize: 12
width: 200
wrapMode: Text.WrapAnywhere
anchors.verticalCenter: parent.verticalCenter
color: "#999"
}
Label{
anchors.verticalCenter: parent.verticalCenter
text: "out:"
font.pixelSize: 12
color: "#999"
}
ComboBox{
id: booksID
height: 20
width: 50
model: books
anchors.verticalCenter: parent.verticalCenter
}
}
}
as you can see I'm feeding the name to Label (id: nameID) and I want to feed the books to ComboBox (id: booksID) that has model, if I make books key as ListElement how can I feed all the values?
in QML ListModel or ListElement documentation didn't mention anything about getting all the key's value right? it only supports get(int index) which is based on an index number.
You did that wrong. Array members must be ListElement:
ListModel {
id: mod
ListElement {
name: "ali"
dic: [ ListElement{text:"asad-o-llah"; code: 14}, ListElement{text:"aboo torab"; code: 72}, ListElement{text:"amir al-momenin"; code: 110}]
}
}
ListView {
model: mod
anchors.fill: parent
delegate: Component {
Rectangle {
width: parent.width; height: 50
Row {
Text {
text: name
}
ComboBox {
width: 100; height: 30
model: dic //<-- set dic as model for combo box
textRole: "text" //<-- important!
onCurrentIndexChanged: {
console.log("current code is "+model.get(currentIndex).code); //<-- get code value
}
}
}
}
}
}
Component.onCompleted: {
var v = mod.get(0).dic.get(0).value; //<-- sample usage
console.log(v);
}
Do you want some thing similar to this:
Rectangle {
id: root
visible: true
width: 360
height: 360
ListModel
{
id: myList
ListElement {
name: "Story"
card: 3
books: [
ListElement { bookName: "Story 1" },
ListElement { bookName: "Story 2" },
ListElement { bookName: "Story 3" }
]
}
ListElement {
name: "Novel"
card: 3
books: [
ListElement { bookName: "Novel 1" },
ListElement { bookName: "Novel 2" },
ListElement { bookName: "Novel 3" }
]
}
}
Component {
id: displayDelegate
Rectangle
{
id: rowID
width: 300 //50
height: 40
color: "#323232"
border.color: "white"
Row
{
anchors.fill: parent
anchors.leftMargin: 10
anchors.rightMargin: 10
Text{
id: nameID
text: name
font.pixelSize: 12
width: 50 //200
wrapMode: Text.WrapAnywhere
/*anchors.verticalCenter: parent.verticalCenter*/
color: "white"//"#999"
}
Text{
/*anchors.verticalCenter: parent.verticalCenter*/
text: "out:"
font.pixelSize: 12
color: "white"//"#999"
}
/*ComboBox{
id: booksID
height: 20
width: 50
model: books
anchors.verticalCenter: parent.verticalCenter
}*/
Repeater {
model: books
Text { text: bookName + "\t"; color: "white" }
}
}
}
}
ListView {
id: disp
anchors.fill: parent
model: myList
delegate: displayDelegate
}
}
I have modified few line of the code which you have shared. I am not sure about your ComboBox implementation. Therefore, I have used my own implementation of Repeater. You can try to execute and check the result.
As an alternative to working with ListModel and ListElement, you can also have a look at the QSyncable JsonListModel QML type. (It is an open-source component by Ben Lau, you can find it on GitHub here: https://github.com/benlau/qsyncable)
The JsonListModel is a specialized ListModel type, that can handle JSON Arrays that you e.g. create in your QML or fetch from a REST service. It automatically synchronizes the JSON to a QML ListModel, so its very convenient to use:
ListView {
id: listView
anchors.fill: parent
// property for json data, used as source for JsonListModel
property var jsonData: []
// use JsonListModel as model
model: JsonListModel {
source: listView.jsonData
keyField: "id"
}
// delegate
delegate: DelegateItem { /* ... */ }
}
You can also find a comprehensive guide how it works here: JsonListModel guide