From 0e12b9410773056ab2e9ea6df8f1b0dfa5ee398d Mon Sep 17 00:00:00 2001 From: Kenn Jacobsen Date: Mon, 29 Apr 2024 10:23:07 +0200 Subject: [PATCH] Translate member picker property editor value to V14 compatible format (and back again) (#16149) * Translate member picker property editor value to V14 compatible format (and back again) * Fix typo --------- Co-authored-by: Elitsa --- .../MemberPickerPropertyEditor.cs | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/src/Umbraco.Core/PropertyEditors/MemberPickerPropertyEditor.cs b/src/Umbraco.Core/PropertyEditors/MemberPickerPropertyEditor.cs index e7cc3970d1..88e1594200 100644 --- a/src/Umbraco.Core/PropertyEditors/MemberPickerPropertyEditor.cs +++ b/src/Umbraco.Core/PropertyEditors/MemberPickerPropertyEditor.cs @@ -1,3 +1,11 @@ +using Umbraco.Cms.Core.IO; +using Umbraco.Cms.Core.Models; +using Umbraco.Cms.Core.Models.Editors; +using Umbraco.Cms.Core.Serialization; +using Umbraco.Cms.Core.Services; +using Umbraco.Cms.Core.Strings; +using Umbraco.Extensions; + namespace Umbraco.Cms.Core.PropertyEditors; [DataEditor( @@ -9,4 +17,49 @@ public class MemberPickerPropertyEditor : DataEditor public MemberPickerPropertyEditor(IDataValueEditorFactory dataValueEditorFactory) : base(dataValueEditorFactory) => SupportsReadOnly = true; + + protected override IDataValueEditor CreateValueEditor() => + DataValueEditorFactory.Create(Attribute!); + + private class MemberPickerPropertyValueEditor : DataValueEditor + { + private readonly IMemberService _memberService; + + public MemberPickerPropertyValueEditor( + IShortStringHelper shortStringHelper, + IJsonSerializer jsonSerializer, + IIOHelper ioHelper, + DataEditorAttribute attribute, + IMemberService memberService) + : base(shortStringHelper, jsonSerializer, ioHelper, attribute) + => _memberService = memberService; + + public override object? ToEditor(IProperty property, string? culture = null, string? segment = null) + { + // the stored value is either an UDI or an integer ID - need to transform this into the corresponding member key + var value = base.ToEditor(property, culture, segment); + if (value is not string stringValue || stringValue.IsNullOrWhiteSpace()) + { + return value; + } + + if (UdiParser.TryParse(stringValue, out GuidUdi? guidUdi)) + { + return guidUdi.Guid; + } + + if (int.TryParse(stringValue, out int memberId)) + { + return _memberService.GetById(memberId)?.Key; + } + + return null; + } + + // the editor value is expected to be the member key - store it as the member UDI + public override object? FromEditor(ContentPropertyData editorValue, object? currentValue) + => editorValue.Value is string stringValue && Guid.TryParse(stringValue, out Guid memberKey) + ? new GuidUdi(Constants.UdiEntityType.Member, memberKey) + : null; + } }