Pages

Thursday, September 30, 2021

Hide FormContainerBlock in Optimizely

It's easy to customize a FormContainerBlock by creating a new one inheriting from the out-of-box FormContainerBlock model. When doing this you gain the option of using the OOB container, or your new custom one. However, I have encountered numerous times when the OOB form container was no longer necessary for the project. Furthermore, attempting to use the OOB FormContainerBlock in certain areas created issues I had to account for. In several instances for me, the easiest approach was to hide the Optimizely FormContainerBlock from editors, and this is how I did it.

All it takes is an InitializationModule, and a little bit of code.

The trick is to modify the out-of-box FormContainerBlock content type and set IsAvailable to false. This does the same thing that setting AvailableInEditMode to true does when defining new ContentTypes. This InitializationModule is set to run after the FormContainerBlock is initialized by the Forms EditView InitializationModule by using the ModuleDependency attribute.
[pre class="brush:csharp;"]
using EPiServer.DataAbstraction;
using EPiServer.Forms.Implementation.Elements;
using EPiServer.Framework;
using EPiServer.Framework.Initialization;
using EPiServer.ServiceLocation;

namespace EpiSandbox.Initialization
{
    [ModuleDependency(typeof(EPiServer.Forms.EditView.InitializationModule))]
    public class FormsInitializationModule : IInitializableModule
    {
        private Injected<IContentTypeRepository> _contentRepo;

        public void Initialize(InitializationEngine context)
        {
            var formContainerBlock = _contentRepo.Service.Load(typeof(FormContainerBlock));
            if (formContainerBlock == null || !formContainerBlock.IsAvailable) { return; }
            // make the type editable, then change and save
            formContainerBlock = formContainerBlock.CreateWritableClone() as ContentType;
            formContainerBlock.IsAvailable = false;
            _contentRepo.Service.Save(formContainerBlock);
        }

        public void Uninitialize(InitializationEngine context)
        {
            // do nothing
        }
    }
}
[/pre]
 
This only needs to happen once, which is why I have a check to see if IsAvailable is already false. If you want to make it come back, just flip it back to true. Also, make sure you create a new FormContainerBlock to replace it. If you don't, you won't be able to create any forms; the menu on the Forms tab won't give you a New Form option. However, because the type still exists, it won't break existing forms.


 

No comments:

Post a Comment

Share your thoughts or ask questions...