Using A Field For A Data Source
Data Sources allow us to see which values or locations a content author will have access to when using a field. Sitecore fields use paths, guids or xpath queries as the Data Source.
With a bit of code we can add one more option - Setting a field (within the same item) to be a Data Source. When we change the value of the field, the Data Source becomes updated.
In this example let’s look at a TreeList field. It natively supports a complex query string to configure how it functions. We are going to add a DataSourceField parameter that query string while supporting all of it’s existing functionality.
TreeList Extended: The Code
Here we inherit the TreeList field and override a few properties. The OnLoad is overridden to determine the DataSource with our own logic. The value of the field specified by DataSourceField parameter is returned and swapped in as the properDataSource.
TreeList Extended: Sitecore Setup
Switch to your core database (bottom right icon in the content editor). Create a new field underneath /Sitecore/System/Field Types (also consider creating a folder to categorize the custom fields). Then set the Data and Assembly fields to use the appropriate assemby & class.
Create a template with a Droplink field to provide the Data Source and a TreeList Extended field to consume the Data Source with the custom DataSourceField parameter.
TreeList Extended: Finished Product
First we see that with no value selected, the TreeList Extended renders a message prompting the users.
Note the Makes and Models of cars found in the Sitecore tree. Now with Toyota selected as a Make and the item saved the TreeList Extended is populated with Toyota Models.
The Make is changed to Honda,the item is saved and the TreeList Extended is populated with Honda Models.
Here is a recap of how it all works:
- DataSourceField parameter takes field name as a string. (e.g. DataSourceField=Make)
- A save is required to refresh the Data Source.
- The query string will ignore the DataSourceField parameter if the DataSource parameter is found.
- When needed, this code displays the field name as entered in the query string.
- Any currently selected values will be removed when the field value acting as a data source changes.
- All existing query string parameters for the TreeLists source are supported. There are a lot.
Closing Thoughts
The primary use of this technique is to provide clarity to content authors. It’s certainly not necessary for every Sitecore installation, but when you need it, you need it.
It also recommended to add a help message to the field indicating that the TreeList Extended will refresh on save.
We've used this technique to extend the Multilist and Droplink fields as well. I hope to share that code with you soon!