Thursday, September 10, 2015

Glass Casting


To cast a list of Guilds (Treelist or Multilist field value):

if (Model.LogbookEntries != null && Model.LogbookEntries.Any())
{
     List<Guid> manuallySelectedEntires = Model.LogbookEntries.ToList();
     LogbookItems = manuallySelectedEntires.Select(x => SitecoreContext.GetItem<BaseLogbookEntry>(x)).ToList();

}
--------------------------------------------------------------------------------------------------------

To cast a SC item:

Item tracksFolder = Sitecore.Context.Database.GetItem("{A248A5F4-87CD-4BDD-9A6E-AA82986F7E2C}");


var glassItem = tracksFolder.GlassCast<IGlassBase>(false, true);

-------------------------------------------------------------------------------



To cast children of a SC Item:

using Glass.Mapper.Sc;



List<LogbookTrack> Tracks = tracksFolder.GetChildren().Select(item => item.GlassCast<LogbookTrack>()).ToList();

-------------------------------------------------------------------------------


To cast results of a SC content search:

ISearchIndex index = ContentSearchManager.GetIndex(SearchUtil.Settings.IndexName);
             using (var context = index.CreateSearchContext())
             {
                 List<ID> templatesIdsToFind = new List<ID>
                    {
                        ILogbookArticleEntryConstants.TemplateId,
                        ILogbookPhotoEntryConstants.TemplateId,
                        ILogbookVideoEntryConstants.TemplateId
                    };

                 // Build an "or" predicate for each type
                 var typePredicate = PredicateBuilder.True<LogbookSearchResultItem>();
                 typePredicate = templatesIdsToFind.Aggregate(typePredicate, (current, id) => current.Or(l => l.TemplateId == id));


                 var results = context.GetQueryable<LogbookSearchResultItem>()
                     .Where(typePredicate)
                     .Where(item => item.Language == Sitecore.Context.Language.Name);
                     //.Where(item => item.Content.Contains(searchTerm));

                 int count = results.Count();

                 foreach (var hit in results)
                 {
                     BaseLogbookEntry entry = hit.GetItem().GlassCast<BaseLogbookEntry>();
                     if (entry != null)
                     {
                         LogbookItems.Add(entry);
                     }
                 }

No comments:

Post a Comment