zaterdag 9 juli 2011

Change representation of managed metadata field values separator

Recently I was adding a managed metadata field to some page layouts and noticed that the out of the box representation of a path to a tag was not really that clear.

Out of the box you will get something like tag1:tag1.1:tag1.1.1
When clients see this, I many times get the same question: can you change the representation of the path ?

I searched for this on Google and wasn’t able to find a clear answer. I also didn’t find any property of the managed metadata field class which by which you could change this.

My solution uses rather simple JavaScript/JQuery to replace the ‘:’ to something I want. In this case I’m replacing ‘:’ by ‘—>’. When I placed the managed metadata field on the page layout, I also wrapped it with a div and gave the ID ‘mmFieldDivId’.

// Change the taxonomy field delimiter from ':' to '->'
$("#mmFieldDivId:contains(:)").each(function () {
   replaceText(/\:/ig, ' --> ', this);
});
// Function to replace text
function replaceText(oldText, newText, node) {
   node = node || document.body; // base node
   var childs = node.childNodes, i = 0;
   while (node = childs[i]) {
       if (node.nodeType == 3) { // text node found, do the replacement
     if (node.textContent) {
         node.textContent = node.textContent.replace(oldText, newText);
     } else { // support to IE
         node.nodeValue = node.nodeValue.replace(oldText, newText);
     }
       } else { // not a text mode, look forward
     replaceText(oldText, newText, node);
       }
       i++;
   }
}