How to Extend a Form MVC Widget with Custom Properties
There are many use cases or situations where you might need to customize the appearance of an existing MVC widgets. You may want to add new custom properties like background color or change the output HTML of a widget.
One of the possible solutions is to nest the widget you need to adjust within another custom widget. In Portal Engine we used to call this feature Web Part Containers.
First, you need to create a custom widget. If you are not sure about this step, please take a look at the article called "Build a Portal Engine widget in MVC".
Once you have your custom widget, you need to adjust its implementation to reflect your requirements. Let's add a light/dark theme switch.
View
In the View of your custom widget use following code to render the original widget:
@{ Html.RenderAction("Index", "KenticoFormWidget"); }
So the complete partial View would look like this:
@model MyCustom.Models.Widgets.AdjustableFormViewModel
@{
var wrapperStyle = @Model.Theme == "light" ? "#eee" : "#bbb";
}
<div style="background-color: @wrapperStyle">
@{ Html.RenderAction("Index", "KenticoFormWidget"); }
</div>
Note: In the production-ready implementation, we suggest you use class names instead of styles.
Model
Your custom widget's properties (that is model) must inherit the original widget's properties. In this case, it's FormWidgetProperties class.
public class MyProperties : FormWidgetProperties
{
...
}
Let's add a theme switch property and use a dropdown to allow editors to choose between the light and dark variants. The properties model would look like this:
public class AdjustableFormProperties : FormWidgetProperties
{
const string THEME_OPTIONS = @"
light;Light
dark;Dark";
[EditingComponent(DropDownComponent.IDENTIFIER, Label = "Theme", Order = 2)]
[EditingComponentProperty(nameof(DropDownProperties.DataSource), THEME_OPTIONS)]
public string Theme { get; set; } = "light";
}
Controller
As your custom widget is only displaying the respective View, which then renders the original widget using RenderAction, there is no need for adjusting the logic of the Controller action.
Result
When you add your custom widget to a page, you will see the original widget rendered inside. If you open a configuration dialog of your widget, you will be able to select the theme.
As soon as you save your selection, you can see the changed HTML output directly. It is now rendered based on the value of the widget properties:
This way you can add wrappers around any MVC widgets that are available in your project.
If you are looking for more advanced ways to adjust MVC widgets like changing the actual widget markup, check out our extensive documentation.