Friday, March 23, 2012

Retrieving Related Content in the CD side

The example below shows how to retrieve the latest 5 news of type sport, then these are sorted descending. These news are classified using taxonomies.

        protected override void Render(HtmlTextWriter writer)


            string[] sportNews;

            Query query = null;            
            Criteria criteria = new ItemTypeCriteria(16);
            ComponentPresentationFactory _cpf = new ComponentPresentationFactory(PublicationId); 

            CustomMetaKeyCriteria keyCriteria = new CustomMetaKeyCriteria("news");
            CustomMetaValueCriteria valueCriteria = new CustomMetaValueCriteria(keyCriteria, "Sport");

            List<Criteria> queryItems = new List<Criteria>();
            query = new Query(new AndCriteria(queryItems.ToArray()));

            //Set a limit on number of items                        
            query.SetResultFilter(new LimitFilter(5));

            //Add sorting
            SortParameter sort = new SortParameter(SortParameter.ItemLastPublishedDate, SortParameter.Descending);

            sportNews = query.ExecuteQuery();

            foreach (string news in sportNews)
                ComponentPresentation cp = _cpf.GetComponentPresentationWithOutputFormat(news, "XML Fragment");
                if (cp != null)
                    DisplaySportNewsItem(news, cp, writer);

1 comment:

  1. Ah, that's a new one for me: GetComponentPresentationWithOutputFormat (look ma, no template id or name).

    Sorting via the API, I still love it. Back in my (R5.3) days we had to sort that ourselves! (Is the older generation complaining about how hard it was in there time cross-cultural? I've heard it from both in Filipino and American parents at least.)