Skip to content

Instantly share code, notes, and snippets.

@naepalm
Created August 31, 2018 15:30
Show Gist options
  • Save naepalm/9c5d93231a79e1f9bc6a7ff0e6b7992d to your computer and use it in GitHub Desktop.
Save naepalm/9c5d93231a79e1f9bc6a7ff0e6b7992d to your computer and use it in GitHub Desktop.
Converts the core radio button automagically with ModelsBuilder from the value Id to the prevalue string. This does not use Dependency Injection, but it does work, so feel free to use it if you'd like!
using System;
using Umbraco.Core;
using Umbraco.Core.Models.PublishedContent;
using Umbraco.Core.PropertyEditors;
using Umbraco.Web;
namespace Offroadcode.Web.PropertyConverters
{
class RadioButtonValueConverter : PropertyValueConverterBase, IPropertyValueConverterMeta
{
private readonly UmbracoHelper _umbracoHelper = new UmbracoHelper(UmbracoContext.Current);
public RadioButtonValueConverter()
{
}
public override bool IsConverter(PublishedPropertyType propertyType)
{
return "Umbraco.RadioButtonList".InvariantEquals(propertyType.PropertyEditorAlias);
}
public override object ConvertSourceToObject(PublishedPropertyType propertyType, object source, bool preview)
{
return source != null ? _umbracoHelper.GetPreValueAsString((int)source) : string.Empty;
}
public Type GetPropertyValueType(PublishedPropertyType propertyType)
{
return typeof(string);
}
public PropertyCacheLevel GetPropertyCacheLevel(PublishedPropertyType propertyType, PropertyCacheValue cacheValue)
{
return PropertyCacheLevel.Content;
}
}
}
@leekelleher
Copy link

@naepalm - Nice! 🎉

To save on creating the UmbracoHelper instance, you could call DataTypeService.GetPreValueAsString directly.
The UmbracoHelper.GetPreValueAsString method is a wrapper: https://github.com/umbraco/Umbraco-CMS/blob/dev-v7/src/Umbraco.Web/UmbracoHelper.cs#L1573

@naepalm
Copy link
Author

naepalm commented Aug 31, 2018

@leekelleher Ah-hah, brilliant! Thanks for the link to the code, I hadn't actually looked 😅 So it isn't as if calling the helper is somehow saving a database hit anyway. Might as well just use the service then 😉

@leekelleher
Copy link

Saves on an extra allocation too.
(When you become obsessed with allocations, you see them everywhere)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment