Advertisement
Guest User

Umbraco Default Property Value

a guest
Feb 21st, 2020
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.02 KB | None | 0 0
  1. using System;
  2. using System.Linq;
  3. using System.Web.Http.Filters;
  4. using Umbraco.Core;
  5. using Umbraco.Core.Composing;
  6. using Umbraco.Core.Logging;
  7. using Umbraco.Web.Editors;
  8. using Umbraco.Web.Models.ContentEditing;
  9. //If using Models Builder generated models from the default namespace
  10. using Umbraco.Web.PublishedModels;
  11.  
  12. public class EditorModelComponent : IComponent
  13. {
  14.     private readonly ILogger logService;
  15.  
  16.     public EditorModelComponent(ILogger logService) {
  17.         this.logService = logService;
  18.     }
  19.  
  20.     public void Initialize() {
  21.         EditorModelEventManager.SendingContentModel += EditorModelEventManager_SendingContentModel;
  22.     }
  23.  
  24.     public void Terminate() { return; }
  25.  
  26.     private void EditorModelEventManager_SendingContentModel(HttpActionExecutedContext sender, EditorModelEventArgs<ContentItemDisplay> e) {
  27.         SetDefaultValue(e, new string[] { "news" }, "date", DateTime.Now.Date);
  28.     }
  29.  
  30.     private void SetDefaultValue(EditorModelEventArgs<ContentItemDisplay> e,  string[] docTypeAliases, string propertyAlias, object newValue) {
  31.         try {
  32.             if(docTypeAliases.Contains(e.Model.ContentTypeAlias))
  33.             {
  34.                 //Here we need to consider variants
  35.                 foreach(var variant in e.Model.Variants)
  36.                 {
  37.                     var props = variant.Tabs.SelectMany( t =>
  38.                             t.Properties.Where(p =>
  39.                                 p.Alias.Equals(propertyAlias) &&
  40.                                 (p.Value == null || string.IsNullOrWhiteSpace(p.Value.ToString()))));
  41.  
  42.                     foreach(var prop in props)
  43.                         prop.Value = newValue;
  44.                 }
  45.             }
  46.         }
  47.         catch (Exception ex)
  48.         {
  49.             logService.Error(GetType(), ex, "Error occurred setting default value");
  50.         }
  51.     }
  52. }
  53.  
  54. public class EditorModelComposer : IUserComposer
  55. {
  56.     public void Compose(Composition composition) {
  57.         composition.Components().Append<EditorModelComponent>();
  58.     }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement