I personally don't like using Init modules, personally I like to wrap around the use of Migration Steps. It's something I've presented in the Optimizely Masterclasses I present with Opti
https://world.optimizely.com/blogs/scott-reed/dates/2021/11/run-once-migration-step/
This follows the same approach that one of the inbuild IMigrationStep follows and I feel it fits better. But the code approach looks good, all meta fields need to be done programatically now in Commerce 14
you might want to write your code like this
var friendlyNames = MetaEnum.GetFriendlyNames("AddressType");
//check for redundancy, then
MetaEnum.AddItem("AddressType", 1, "Test 1", 1);
MetaEnum.AddItem("AddressType", 2, "Test 2", 2);
MetaEnum.AddItem("AddressType", 3, "Test 3", 3);
You can put it in an initialization module as you thought. technically you should put it in a IInitializationPlugin but it does not really matter. as long as you have a way to run it, (and fast) I would not worry
Thanks for the guidance, it is working now. Full solution below:
// InitializationModule
[ModuleDependency(typeof(EPiServer.Commerce.Initialization.InitializationModule))]
internal class AddressTypeInitialization : IInitializableModule
{
public void Initialize(InitializationEngine context)
{
// Create Enum values for AddressType
DatabaseInitializationHelpers.CreateEnumField("AddressType", "PostAddress");
DatabaseInitializationHelpers.CreateEnumField("AddressType", "PostOfficeBox");
DatabaseInitializationHelpers.CreateEnumField("AddressType", "DHLPickup");
}
public void Uninitialize(InitializationEngine context)
{
//
}
}
// Static helper class
public static class DatabaseInitializationHelpers
{
public static void CreateEnumField(string enumName, string enumValue)
{
var enumMetaField = DataContext.Current.GetMetaFieldType(enumName);
var enumFriendlyNames = MetaEnum.GetFriendlyNames(enumMetaField);
if (enumValue == null)
{
return;
}
if (enumFriendlyNames.Contains(enumValue))
{
return;
};
var orderId = IncrementEnumCountByOneToGetOrderId(enumFriendlyNames);
MetaEnum.AddItem(enumMetaField, enumValue, orderId);
}
private static int IncrementEnumCountByOneToGetOrderId(string[] friendlyNames)
{
return friendlyNames.Length + 1;
}
}
By default the mcmd_MetaEnum table in Commerce has three values for AddressType: Public, Shipping & Billing:
In my project we want to add some additional Address types. We are looking to do this in an InitializationModule and, at present, have the following code. Is this the best way to go about it?