Skip to content

Instantly share code, notes, and snippets.

@AndyButland
Created June 9, 2023 10:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AndyButland/87d3b30daf4bb9b266ec276a06c811fc to your computer and use it in GitHub Desktop.
Save AndyButland/87d3b30daf4bb9b266ec276a06c811fc to your computer and use it in GitHub Desktop.
using Umbraco.Cms.Core.Models.PublishedContent;
using Umbraco.Cms.Core.PropertyEditors;
using Umbraco.Cms.Core.PropertyEditors.DeliveryApi;
using Umbraco.Forms.Core.Models;
using Umbraco.Forms.Core.Models.Api;
using Umbraco.Forms.Core.Services;
namespace Umbraco.Forms.Core.PropertyEditors.ValueConverters
{
[DefaultPropertyValueConverter]
public class FormPickerValueConverter : PropertyValueConverterBase, IDeliveryApiPropertyValueConverter
{
private readonly IFormService _formService;
private readonly FormDtoFactory _formDtoFactory;
public FormPickerValueConverter(IFormService formService, FormDtoFactory formDtoFactory)
{
_formService = formService;
_formDtoFactory = formDtoFactory;
}
...
public PropertyCacheLevel GetDeliveryApiPropertyCacheLevel(IPublishedPropertyType propertyType) => PropertyCacheLevel.Element;
public Type GetDeliveryApiPropertyValueType(IPublishedPropertyType propertyType) => typeof(DeliveryApiFormDto);
public object? ConvertIntermediateToDeliveryApiObject(IPublishedElement owner, IPublishedPropertyType propertyType, PropertyCacheLevel referenceCacheLevel, object? inter, bool preview, bool expanding)
{
if (inter == null)
{
return null;
}
var formId = (Guid)inter;
// If not expanding, return just the form Id with a null value for the form details.
if (expanding == false)
{
return new DeliveryApiFormDto { Id = formId };
}
// Get the full details of the form.
Form? form = _formService.Get(formId);
if (form == null)
{
return new DeliveryApiFormDto { Id = formId };
}
// Build the same FormDto as would be retrieved directly via the Forms API and associate it with the returned object.
FormDto formDto = _formDtoFactory.BuildFormDefinitionDto(form);
return new DeliveryApiFormDto { Id = formId, Form = formDto };
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment