Sitecore Basics - item.Children
Lets get down to the basics!
To get child items in Sitecore, there are 2 ways to retrieve them:
- item.Children
- item.GetChildren()
Both will retrieve ALL children of an item. The difference is that with GetChildren you have the ability to modify the result a little bit since you have the following ChildListOptions to choose from:
ChildListOptions.None
ChildListOptions.IgnoreSecurity
ChildListOptions.AllowReuse
ChildListOptions.SkipSorting
The problem
The biggest caveat is that these methods will retrieve child items even if they don't have a version for the current context language in Sitecore.
This can be ok for the code you are writing. But can result in unexpected behaviour ! One of the examples is when building a Sitemap.
Another example - which was the inspiration for this blog post - was an implementation of a custom contents resolver for a JSON rendering.
We don't want to return Sitecore items that don't have a version in the language that the request is in. The current behaviour was that we were rendering items with info from Shared fields and with all other fields empty.
The fix
Check what the versions count is! That's it, pretty straightforward and an easy way to make sure that you have an Item that actually has a version in Sitecore as well.
Some examples:
item.Versions.Count
item.Children.Where(m => m.Versions.Count > 0)
Relevant Sitecore Links:
- Link to the Sitecore docs for a custom contents resolver: https://doc.sitecore.com/xp/en/developers/hd/latest/sitecore-headless-development/customizing-the-layout-service-rendering-output.html#choosing-or-configuring-a-built-in-rendering-contents-resolver
- Accessing alternate versions of an item:
https://doc.sitecore.com/xp/en/developers/latest/sitecore-experience-manager/access-alternate-versions-of-an-item.html