A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://docs.umbraco.com/umbraco-cms/customizing/property-editors/full-examples-value-converters below:

Content Picker Value Converter Example

Content Picker Value Converter Example | Umbraco CMS
  1. Customizing Backoffice
  2. Property Editors
Content Picker Value Converter Example

The following example uses Umbraco.Cms.Core.PublishedCache and IPublishedSnapshotAccessor which are obsolete in Umbraco 15 and will be removed in a future version. For more information, see the Version specific upgrades article.

ContentPickerPropertyConverter.cs
using Umbraco.Cms.Core;
using Umbraco.Cms.Core.Models.PublishedContent;
using Umbraco.Cms.Core.PropertyEditors;
using Umbraco.Cms.Core.PublishedCache;

namespace UmbracoDocs.Samples;

public class ContentPickerPropertyConverter : IPropertyValueConverter
{
    private readonly IPublishedSnapshotAccessor _publishedSnapshotAccessor;

    // Injecting the PublishedSnapshotAccessor for fetching content
    public ContentPickerPropertyConverter(IPublishedSnapshotAccessor publishedSnapshotAccessor)
        => _publishedSnapshotAccessor = publishedSnapshotAccessor;

    public bool IsConverter(IPublishedPropertyType propertyType)
        => propertyType.EditorAlias.Equals("Umbraco.ContentPicker");

    public bool? IsValue(object? value, PropertyValueLevel level)
    {
        return level switch
        {
            PropertyValueLevel.Source => value is string stringValue && string.IsNullOrWhiteSpace(stringValue) is false,
            _ => throw new NotSupportedException($"Invalid level: {level}.")
        };
    }

    public Type GetPropertyValueType(IPublishedPropertyType propertyType)
        => typeof(IPublishedContent);

    public PropertyCacheLevel GetPropertyCacheLevel(IPublishedPropertyType propertyType)
        => PropertyCacheLevel.Elements;

    public object? ConvertSourceToIntermediate(IPublishedElement owner, IPublishedPropertyType propertyType, object? source, bool preview)
        // parse the source string to a GuidUdi intermediate value
        => source is string stringValue && UdiParser.TryParse(stringValue, out GuidUdi? guidUdi)
            ? guidUdi
            : null;

    public object? ConvertIntermediateToObject(IPublishedElement owner, IPublishedPropertyType propertyType, PropertyCacheLevel referenceCacheLevel, object? inter, bool preview)
        // inter is expected to be a GuidUdi at this point (see ConvertSourceToIntermediate)
        => inter is GuidUdi guidUdi
            ? _publishedSnapshotAccessor.GetRequiredPublishedSnapshot().Content?.GetById(guidUdi.Guid)
            : null;
}

Last updated 4 months ago


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4