Skip to content

Instantly share code, notes, and snippets.

@sotirisf
Created August 11, 2022 12:04
Show Gist options
  • Save sotirisf/d0472cee6291d91deefe4733db9aa62b to your computer and use it in GitHub Desktop.
Save sotirisf/d0472cee6291d91deefe4733db9aa62b to your computer and use it in GitHub Desktop.
using System.Collections.Generic;
using Umbraco.Cms.Core.Models.PublishedContent;
using Umbraco.Cms.Core.PropertyEditors;
using Umbraco.Cms.Core.Services;
using Umbraco.Cms.Core.Web;
using Umbraco.Cms.Web.Common.PublishedModels;
using Umbraco.Community.Contentment.DataEditors;
using Umbraco.Extensions;
namespace Themelion.Common.DataSources
{
public class SectionsDataSource : IDataListSource
{
private readonly IRequestAccessor _requestAccessor;
private readonly IUmbracoContextAccessor _umbracoContextAccessor;
private readonly IContentTypeService _contentTypeService;
public string Name => "Sections";
public string Description => "A list of sections in the current document";
public string Icon => "icon-globe";
public OverlaySize OverlaySize => OverlaySize.Small;
public Dictionary<string, object> DefaultValues => default;
public IEnumerable<ConfigurationField> Fields => default;
public string Group => default;
IEnumerable<ConfigurationField> IContentmentEditorItem.Fields => default;
public SectionsDataSource(
IUmbracoContextAccessor umbracoContextAccessor
, IRequestAccessor requestAccessor
, IContentTypeService contentTypeService)
{
_requestAccessor = requestAccessor;
_umbracoContextAccessor = umbracoContextAccessor;
_contentTypeService = contentTypeService;
}
public IEnumerable<DataListItem> GetItems(Dictionary<string, object> config)
{
bool gotContext = _umbracoContextAccessor.TryGetUmbracoContext(out var umbracoContext);
if (!gotContext)
{
return null;
}
var gotId = int.TryParse(_requestAccessor.GetQueryStringValue("id"), out int id);
if (!gotId)
{
return null;
}
IPublishedContent p = umbracoContext.Content.GetById(id);
if (!p.IsComposedOf(AbstractPageSections.ModelTypeAlias))
{
return null;
}
var items = new List<DataListItem>();
var sections = (p as IAbstractPageSections).Sections;
foreach (var s in sections)
{
var sContent = s.Content as IAbstractSectionBlock;
var sContentType = _contentTypeService.Get(sContent.ContentType.Key);
var name = string.IsNullOrEmpty(sContent.SectionTitle)
? sContentType.Name
: sContent.SectionTitle;
var icon = sContentType.Icon;
items.Add(new DataListItem
{
Name = name,
Value = s.Content.Key.ToString(),
Icon = icon
});
}
return items;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment