June 18, 2012

Datasources queryable

[EDIT] I have release a new module on trac to do that so it will be easier to use this module. For more information take a look at this post: http://sitecoreblog.blogspot.be/2012/06/sublayout-queryable-datasource-module.html[/EDIT]


In the video from Nick Wesselman at the sitecore virtual user group, he show how to use a subitem as a datasource for a sublayout.

The datasource is used when you insert a sublayout in webedit mode to display a popup to select an create if needed the datasource of this sublayout.


The problem happend when you have a multisite solution for example because with the system from sitecore you cannot set a relative datasource. The idea was to enable the possbility to set this datasource using a query as in the fields.

To code for this is very simple:
public class SublayoutQueryableDatasource
{
    public void Process(GetRenderingDatasourceArgs args) 
    {
        Assert.IsNotNull(args, "args");

        string text = args.RenderingItem["Datasource Location"]; //Get the value from the field
        if (!string.IsNullOrEmpty(text))
        {
            if (text.StartsWith("query:") && !string.IsNullOrEmpty(args.ContextItemPath))
            {
                var contextItem = args.ContentDatabase.GetItem(args.ContextItemPath);

                if (contextItem != null)
                {
                    text = text.Remove(0, 6); //remove the query:
                    var item = contextItem.Axes.SelectSingleItem(text); //Execute the query

                    if (item != null)
                    {
                        args.DatasourceRoots.Add(item);
                    }
                }
            }
        }
    }
}

After that you just have to included this pipeline in the correct place by adding this into a file in your /app_Config/Include folder:
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
  <sitecore>
    <pipelines>
      <getRenderingDatasource>
        <processor type="YOURNAMESPACE.SublayoutQueryableDatasource, YOURNAMESPACE"
                   patch:before="processor[@type='Sitecore.Pipelines.GetRenderingDatasource.GetDatasourceLocation, Sitecore.Kernel']"/>
      </getRenderingDatasource>
    </pipelines>
  </sitecore>
</configuration>

After that you are able to set the datasource like this:

No comments:

Post a Comment