Pre-Populate A Field On Save In Umbraco v7

|

This is very common task that I used to do using the previous Umbraco events system. The Events have changed and it took me a little while to get my head around how to do this in v7.

Scenario

when a Member is saved, I want to create a custom ‘slug’ (bit of text) that is then saved to a textstring property on the member.

Code

Although this is a Member, it’s exactly the same process for doing it for a piece of content. In the code snippet below I have a couple of constants which are the property alias’s to save writing out the same string multiple times.

Create a class called UmbracoEvents and inherit from IApplicationEventHandler

    public class UmbracoEvents : IApplicationEventHandler
    {
    }

Now in the OnApplicationStarted method, add the following line

MemberService.Saved += MemberServiceSaved;

Now add the following method underneath the OnApplicationStarted method

private static void MemberServiceSaved(IMemberService sender, SaveEventArgs e)
{
    var mService = new Services.MemberService();
    foreach (var entity in e.SavedEntities)
    {

            string previousSlug = null;
            if (entity.Properties[AppConstants.PropMemberSlug].Value != null)
            {
                previousSlug = entity.Properties[AppConstants.PropMemberSlug].Value.ToString();
            }
            entity.SetValue(AppConstants.PropMemberSlug, AppHelpers.GenerateSlug(entity.Username,
                                                                                  mService.GetMembersWithSameSlug(AppHelpers.CreateUrl(entity.Username)),
                                                                                  previousSlug));
            sender.Save(entity, false);
    }
}

What we are doing here is looping through each entity (Member) in this save event and and setting a propertyvalue, once set we save it using the sender.Save() method.  Now if a user clicks save and publish in the backoffice, this save event fires first and our event kicks in and saves the property. Then the publish event fires after, and because our property is in there is gets published.

Hopefully this helps someone else having a similar issue.

from the blog Album Covers - The Bigger Picture

Full Article