Before Save Plugin (IBeforeEntitySave)

If you want to make changes to an entity (i.e. Content, Media etc...) before it's saved, or when something new is added or deleted. You can use the IBeforeEntitySave plugin.

Just implement the Interface

/// <summary>
/// Defines a contract for handling operations that need to occur before saving an entity to the database.
/// </summary>
public interface IBeforeEntitySave
{
    /// <summary>
    /// Gets the type of the entity that the implementor of this interface is concerned with during the save operation.
    /// </summary>
    Type EntityType { get; }

    /// <summary>
    /// Executes operations needed before saving an entity to the database.
    /// </summary>
    /// <typeparam name="T">The type of the entity being saved.</typeparam>
    /// <param name="entity">The entity instance that is about to be saved.</param>
    /// <param name="entityState">The state of the entity within the context (e.g., Added, Modified, Deleted).</param>
    /// <returns>Returns false if the save operation should be canceled; otherwise, true.</returns>
    bool BeforeSave<T>(T entity, EntityState entityState);
}

And then you can check the entity state or just just update the entity before it's saved. Very simple example below showing the save being abandoned

public class StopSaveIfBadWord : IBeforeEntitySave
{
    public Type EntityType => typeof(Content);
    public bool BeforeSave<T>(T entity, EntityState entityState)
    {
        if (entity is Content content)
        {
            if (content.Name != null && content.Name.Contains("Arsenal"))
            {
                // Horrible word so don't let them save
                return false;
            }
        }

        return true;
    }
}

Or an example showing some content being replaced

public class StopSaveIfBadWord : IBeforeEntitySave
{
    public Type EntityType => typeof(Content);
    public bool BeforeSave<T>(T entity, EntityState entityState)
    {
        if (entity is Content content)
        {
            if (content.Name != null && content.Name.Contains("Arsenal"))
            {
                content.Name = content.Name.Replace("Arsenal", "Up The Spurs #COYS");
            }
        }

        return true;
    }
}

Last updated