All Articles

Sitecore Powershell Extensions - Use Script as Field Source

This feature is one of my most favourite things that Sitecore Powershell Extensions has to offer. We can use Sitecore Powershell scripts as the field source for our template fields, when Sitecore queries do not help.

In this article, I explain how you can use a Sitecore Powershell script as the field source for your template fields.

When to use Sitecore Powershell for field souce queries?

Sitecore queries are often enough for templates used to build simple components. But, there are times when we need some logic to be performed to show the field source. We can use Sitecore queries to filter out the datasources based on the template name, template id etc. But, what if the logic is more complicated? You can also build something custom, as mentioned in this article: Sitecore Source Field Code: query that implements IDataSource.

We can use Sitecore Powershell Scripts instead for the following reasons:

  1. Maintaining and updating the script is easy, and can be done without a deployment.
  2. Can be extended to use for different scenarios as needed.
  3. The scripts can be serialized and be part of your source control.
  4. The most important thing is however, we should be able to build the logic with Powershell. And in most cases, it is possible.
  5. Powershell is fun. :P

How to build a field source query with Sitecore Powershell?

For this article, I will use an example where I needed a list of the root items of SXA Sites for a droplink field.

  1. First, we will need to build a script for the needed logic. Use the Powershell ISE as your playground and build your logic. In the end, make sure to return the object that you want to be the datasource.
    $database = [Sitecore.Configuration.Factory]::GetDatabase("master")
    $SiteResolver = [System.Type]([Sitecore.XA.Foundation.Multisite.ISiteInfoResolver])
    $sites = [Sitecore.DependencyInjection.ServiceLocator]::get_ServiceProvider().GetService($SiteResolver).Sites | ForEach-Object { $database.GetItem($_.RootPath) } | `
        Where-Object { $_ -ne $null -and $_.ID -ne $null} | Sort-Object -Unique
    return $sites
  2. Save the script as part of your Script Library. This script item should be a part of your serialization.
  3. Go to your template field and add your script as the source by adding the path to your script following script: . index1697730327767
  4. Voila! You can test it by just creating the Standard Values item, or by creating an item from the template. index1697730469460

Happy Sitecoring!

References

  1. Sitecore Source Field Code: query that implements IDataSource
  2. Data Sources - Sitecore Powershell Extensions

Published Oct 19, 2023

Sitecore MVP Technology 2024-23. Web Developer with rich experience in Sitecore and ASP.NET MVC.