UmbracoVault icon indicating copy to clipboard operation
UmbracoVault copied to clipboard

Multi-Site Get By Document Type

Open technicallyerik opened this issue 8 years ago • 0 comments

On multi-site instances you might want to get all documents by type, within the site you are currently in. We ended up writing an extension method like this. Worth adding into the core code?

/// <summary>
///     Gets all documents of type T within the current internationalized site
/// </summary>
/// <param name="context">Umbraco context</param>
public static IEnumerable<T> GetByDocumentTypeWithinSite<T>(this IUmbracoContext context)
{
    int rootNode = ResolveRootNodeId(context);

    // Get all documents under the home node with the specified document type
    // Document paths in the Umbraco cache are defined as "-1,<root node>,..."
    var documents = Vault.Context.QueryRelative<T>(
        XpathHelper.GetXpathForDocumentTypeUnderHomeNode(GetUmbracoEntityAliasFromType(typeof(T)), rootNode));

    return documents;
}
/// <summary>
///     Gets the Xpath query for a document type underneith a home node id
/// </summary>
/// <param name="documentTypeId">The document type</param>
/// <param name="homeNodeId">The home node id</param>
public static string GetXpathForDocumentTypeUnderHomeNode(string documentTypeId, int homeNodeId)
{
    return string.Format("//{0}[starts-with(@path, '-1,{1},')]", documentTypeId, homeNodeId);
}

technicallyerik avatar Mar 31 '16 20:03 technicallyerik