Inhalte aufrufen

Profilbild

Add new token to email template


2 Antworten zu diesem Thema

#1 CompleteCoders

CompleteCoders

    Advanced Member

  • Members
  • 68 Beiträge

Geschrieben: 11 October 2018 - 17:36

I have a special order attribute I want to add to an email template.  How can I add new tokens to the email system?  Is there code sample on how to do this?



#2 Marcus Gesing

Marcus Gesing

    SmartStore AG

  • Administrators
  • 3305 Beiträge

Geschrieben: 11 October 2018 - 21:38

There is a MessageModelPartMappingEvent published to allow to add data through an event consumer. Some pseudo example code:
 
public class MyMessageModelPartMappingEventConsumer : IConsumer<MessageModelPartMappingEvent>
{
	protected readonly ICommonServices _services;

	public MyMessageModelPartMappingEventConsumer(ICommonServices services)
	{
		_services = services;
		
		Logger = NullLogger.Instance;
	}

	public ILogger Logger { get; set; }
	
	protected virtual dynamic CreateModelPart(MyEntityOrSource source)
	{
		// TODO: process source
		
		var modelPart = new Dictionary<string, object>
		{
			{ "Id", 16 },
			{ "OrderId", source.OrderId ?? 0 },
			// More data for templates...
		};

		return modelPart;		
	}

	public void HandleEvent(MessageModelPartMappingEvent message)
	{
		try
		{
			var source = message.Source as MyEntityOrSource;
			if (source != null)
			{
				message.Result = CreateModelPart(source);
				if (message.Result != null)
				{
					message.ModelPartName = "MyModelPartName";

					//_services.EventPublisher.Publish(new MessageModelPartCreatedEvent<MyEntityOrSource>(source, message.Result));//optional
				}
			}
		}
		catch (Exception ex)
		{
			Logger.Error(ex);
		}
	}
}

Schöne Grüße aus Düsseldorf,
Marcus Gesing


#3 Murat Cakir

Murat Cakir

    SmartStore AG

  • Administrators
  • 1078 Beiträge

Geschrieben: 15 October 2018 - 16:56

If you just wish to add a new token/property to an existing entity (e.g. Order), the following approach is sufficient:

public class OrderMessagePartCreatedEventConsumer : IConsumer<MessageModelPartCreatedEvent<Order>>
{
	public void HandleEvent(MessageModelPartCreatedEvent<Order> message)
	{
		// Source is the originating entity. Don't change this one!
		var entity = message.Source;

		// Part is the dynamic target object used in message templates
		dynamic part = message.Part;

		// Part also implements IDictionary<string, object>
		IDictionary<string, object> dict = message.Part;

		// Add custom token this way, ...
		part.MyToken = "Something";

		// ...or this way
		dict["MyToken"] = "Something";
	}
}

Murat Cakir
SmartStore AG




Auf dieses Thema antworten