Welkom bij WerfNet..

2024-05-03 14:39:30

Extended MultiRoot Treelist

With Sitecore XA came the Multiroot Treelist. A very handy fieldtype where you can select items that can come from multiple datasources. But what if you have to look or edit the source item for a specific selected item that was selected? With multiple datasources only the name of a specific selected item is not enough to find where the source item is stored in the tree. To find out where it is, you would have to go to raw view, select the ID and then search it.
To make it a little more easy I created an "Extended MultiRoot Treelist". It basically inherrits from Sitecore.XA.Foundation.SitecoreExtensions.CustomFields.FieldTypes.MultiRootTreeList and adds the path of the selected item to the help-line underneath the box. From there you can select the path and simply search it.

 

Here is the code:

using System;
using System.Reflection;
using Sitecore.Web.UI.HtmlControls;
using conentEditor = Sitecore.Shell.Applications.ContentEditor;
using sitecoreExtentions = Sitecore.XA.Foundation.SitecoreExtensions.CustomFields.FieldTypes;

namespace MyProject.Foundation.JavaScriptServices.Fields
{
    public class ExtendedMultiRootTreeview : sitecoreExtentions.MultiRootTreeList
    {
        protected Listbox PrivateListbox
        {
            get
            {
                return typeof(conentEditor.TreeList)
                        .GetField("_listBox", BindingFlags.Instance | BindingFlags.NonPublic)
                        .GetValue(this) as Listbox;
            }
        }

        protected override void OnLoad(EventArgs args)
        {
            var db = Sitecore.Context.ContentDatabase;
            base.OnLoad(args);

            if (!Sitecore.Context.ClientPage.IsEvent)
            {
                var listbox = this.PrivateListbox;
                foreach (var li in listbox.Items)
                {
                    var id = li.Value.Split('|')[1];
                    var item = db.GetItem(id);
                    if (item != null)
                    {
                        li.Value += "|" + item.Paths.Path;
                    }
                }

                var js = "this.options[this.selectedIndex].value.split('|').length == 3?this.options[this.selectedIndex].value.split('|')[2]:this.options[this.selectedIndex].innerHTML";
                listbox.Attributes["onchange"] = "javascript:document.getElementById('" + this.ID + "_help').innerHTML=this.selectedIndex>=0?(" + js + "):''";
            }
        }
    }
}