Orchard CMS 1.5.1 – Filtering Content by Taxonomies
November 1, 2012 1 Comment
Filtering contents by Taxonomies or categories in Orchard can be a challenge. I’ve found articles talking about cycling through taxonomies in a specific Content Type, but not one to get a list of Content Items for a custom filter. The reason I couldn’t use other methods is that I’m creating a custom search based on several other criteria, including a text field entered by the user.
Taxonomy terms are of type System.Linq.Enumerable.WhereSelectEnumerableIterator<Contrib.Taxonomies.Models.TermContentItem,Contrib.Taxonomies.Models.TermPart>
which is difficult to work with. So after some trial and error, I found a way to do this.
In this example, I have a Content Type named Product. Inside the Product Content Type, I have a Product Part which contains the Brand taxonomy.
The method below takes in a brand name, and returns a IEnumerable<dynamic>
list of Product Content Type with the brand name specified by the argument
private readonly IOrchardServices _orchardServices; private IEnumerable<dynamic> GetFilteredItemsByTaxonomy(string taxonomyTerm) { // Filtering for only product Content Type // Using the dynamic type to access the taxonomy data directy IEnumerable<dynamic> products = _contentManager.Query(VersionOptions.Published , new string[] { "Product" }).List(); // Filtering the products by brand where it contains the taxonomyTerm return products.Where(x => ((IEnumerable<Contrib.Taxonomies.Models.TermPart>)x.ProductPart.Brand.Terms.Value) .Select(y => y.Name).Contains(taxonomyTerm)); }
I would like to mention that PluralSight has a great Orchard Tutorial on Orchard modules.
How do you solve problem with performance? When you call List() you will get all items from database.