Filter Relationships by a field in dotCMS

So, I love Relationships (well, dotCMS ones, anyway) but one of the pain points is that when people choose the dialog to relate an item, there’s no way to control things…or there wasn’t, anyway.

Here’s code that you can put in a Custom Field that will allow you to ‘hide’ particular relationships based on a field value. For example, if you have a Content type of ‘Vehicles’, but you want a user to only relate ‘Motorcycles’, you can do that. It does require that you make that field ‘show in listing’ in order to see it.

One, it delays, since it has to wait for the DOM to load.
Two, it finds the ‘relateContent’ table, which is something that is displayed when you click on ‘Relate Content’. dotCMS reuses this table each time you click ‘Relate Content’.
It attaches an action to happen if it changes.
If it changes (becomes populated because you chose ‘Relate Content’), it rolls through the table looking for text that matches your field.

function hideItems(element) { // Code to execute when innerHTML is updated

what=element.getElementsByClassName(‘selectMeRowInIframe’);
for (i=0;i<what.length;i++){
whatin=what[i].getElementsByTagName(‘td’);
for (j=0;j<whatin.length;j++){
console.log(whatin[j]);
//Hides any list that has a field called ‘Motorcycle’
if (whatin[j].innerHTML==“Motorcycle”) what[i].style.display=“none”;
}
}

}

window.addEventListener(‘load’, function () {
const elementlist = document.getElementsByClassName(‘relateContent’);
const element=elementlist.item(0);
let oldInnerHTML = element.innerHTML;

const observer = new MutationObserver(mutations => {
mutations.forEach(mutation => {
if (mutation.type === ‘childList’ || mutation.type === ‘characterData’) {
if (element.innerHTML !== oldInnerHTML) {
// innerHTML has been updated
oldInnerHTML = element.innerHTML;
hideItems(element);
}
}
});
});

observer.observe(element, {
childList: true, // to monitor addition/removal of child nodes
subtree: true, // to monitor all descendants
characterData: true // to monitor changes in text content
});

})

Example of the Relate item table showing fields like ‘Image Location’

Thanks for your post @MarkPitely! Your thread is now under Product Discussions, and we’ll get back to you soon!

Hay @MarkPitely this is cleeeeever, so let me see if I understand the whole thing.

Wait for the page to load, find the first relatedContent store and then use MutationObserver to watch the changes and on every change check if it have the text you want to hide and hide it.

Nice!!!