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.
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’