Filter in Sitecore Children in Sitecore

1.6k Views Asked by At

I have this tree structure:

Page1
  PageA
    PageX
    PageY
  PageB
Page2

I want Page1 and Page2 as well as all child pages. I have created two classes. In one class using sitecore query

[SitecoreQuery("../*[@@templateid={GUID}]", IsRelative = true)]
public virtual IEnumerable<ItemModel> Links { get; set; }

In other ItemModel class getting child pages

public class ItemModel
{
    [SitecoreId]
    public Guid Id { get; set; }

    [SitecoreChildren]
    public IEnumerable<SideMenuModel> Children { get; set; }
}

This is working fine but now I want to get only those child pages who have some specific template. Please provide me some solution.

1

There are 1 best solutions below

0
jammykam On BEST ANSWER

It looks like you have most of the code correct but you need to also apply restrictions to the Children property on the ItemModel class.

You can use a SitecoreQuery on the like you have on the parent model:

public class ItemModel
{
    [SitecoreId]
    public Guid Id { get; set; }

    [SitecoreQuery("./*[@@templateid={SideMenuModel-GUID}]", IsRelative = true)]
    public virtual IEnumerable<SideMenuModel> ChildItems { get; set; }
}

Or you can use the EnforceTemplate attribute on your SideMenuModel class:

[SitecoreType(TemplateId = "GUID", EnforceTemplate = SitecoreEnforceTemplate.Template)]
public class SideMenuModel
{
    [SitecoreId]
    public Guid Id { get; set; }
}

public class ItemModel
{
    [SitecoreId]
    public Guid Id { get; set; }

    [SitecoreChildren]
    public virtual IEnumerable<SideMenuModel> ChildItems { get; set; }
}

Since you have set EnforceTemplate then using the [SitecoreChildren] attribute means that only items matching the template id will be returned, otherwise they will be skipped.

If you need children of children mapped then you should add [SitecoreChildren] property on your SideMenuModel class as well (or refactor your code so the class references itself) or you could use a "get all descendants query (.//*[@@templateid={SideMenuModel-GUID}]) although I would recommend that you ur he Content Search API at this point instead.

You can read more in the blog post about Getting child items with Glass.