This post shows two ways of using relative lookup field queries in a multisite environment.
The issue
Imagine you want to let your users pick sub Pages of the current site in a multilist. You can set something like the following as source in the template builder:
DataSource=/sitecore/content/home&IncludeTemplatesForSelection=Sub Page&IncludeTemplatesForDisplay=Main Page, Sub Page
Notice that the site root /sitecore/content/home is hard coded. This will not work if you have multiple site roots in your content folder:
- sitecore
- content
- Site A [Template: Site Root]
- Home
- Site B [Template: Site Root]
- Home
- Site A [Template: Site Root]
- content
Solution 1: Relative queries
Of course you can just set /sitecore/content as root in the query but that is not very user friendly. To automatically restrict the items to the current site, there is a solution out of the box using relative queries:
query:./ancestor-or-self::*[@@templatename='Site Root']
This works fine but you loose the ability to use the IncludeTemplatesForSelection and IncludeTemplatesForDisplay parameters.
Solution 2: Replace SiteRoot token through custom getLookupSourceItems processor
Fortunately, it is possible to hook in to the getLookupSourceItems pipeline and modify the DataSource query at runtime. I wrote a simple processor that replaces a $siteRoot token with the path of the parent site root item. Once included in your solution, you can then rewrite your query to something like
DataSource=$siteRoot/home&IncludeTemplatesForSelection=Sub Page&IncludeTemplatesForDisplay=Main Page, Sub Page
Only downside here is that Droptree fields for some reason bypass the getLookupSourceItems pipeline, so you’ll have to use solution 1 for those fields.
Check out the source code and config here:
2 responses to “Allow lookup field queries to respect site root”
I am trying to do this same thing but am attempting to get the root path using Sitecore.Context.Site.RootPath but I am finding that in the content editor it is returning /sitecore/content instead of the full path to my site root which has a tenant and a site below /sitecore/content.
Is there a way to do this without passing in variables?
Hi Michael, Sitecore.Context.Site will be “shell” in content editor context hence pointing at a different RootPath than you would expect it to. You will need to determine the correct site based on the item you’re editing (args.Item).