Skip to content

Instantly share code, notes, and snippets.

@alindgren
Last active October 11, 2017 17:30
Show Gist options
  • Save alindgren/bc670f2e0d938d1b788d38a70720e102 to your computer and use it in GitHub Desktop.
Save alindgren/bc670f2e0d938d1b788d38a70720e102 to your computer and use it in GitHub Desktop.
Umbraco Content SetValueByPreValue and SetValuesByPreValues extension methods
using System.Linq;
using Umbraco.Core;
using Umbraco.Core.Models;
namespace My.Umbraco.Extensions
{
public static class ContentExtensions
{
/// <summary>
/// Sets the value of a property to the PreValue ID for a given preValue.
/// </summary>
/// <param name="content"></param>
/// <param name="propertyTypeAlias"></param>
/// <param name="preValue"></param>
public static void SetValueByPreValue(this IContentBase content, string propertyTypeAlias, string preValue)
{
var dataTypeId = content.Properties[propertyTypeAlias].PropertyType.DataTypeDefinitionId;
var prevalues = ApplicationContext.Current.Services.DataTypeService.GetPreValuesCollectionByDataTypeId(dataTypeId);
int preValueId = prevalues.PreValuesAsDictionary.Values.FirstOrDefault(x => x.Value == preValue).Id;
content.SetValue(propertyTypeAlias, preValueId);
}
/// <summary>
/// Sets the value of a property to the list of PreValue IDs for a given list of PreValues
/// </summary>
/// <param name="content"></param>
/// <param name="propertyTypeAlias"></param>
/// <param name="preValues"></param>
public static void SetValuesByPreValues(this IContentBase content, string propertyTypeAlias, string[] preValues)
{
var csv = new System.Text.StringBuilder();
var dataTypeId = content.Properties[propertyTypeAlias].PropertyType.DataTypeDefinitionId;
var prevalues = ApplicationContext.Current.Services.DataTypeService.GetPreValuesCollectionByDataTypeId(dataTypeId);
foreach (var preValue in preValues)
{
int preValueId = prevalues.PreValuesAsDictionary.Values.FirstOrDefault(x => x.Value == preValue).Id;
if (csv.Length > 0) csv.Append(",");
csv.Append(preValueId);
}
content.SetValue(propertyTypeAlias, csv.ToString());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment