How to override programmatically specific MVC form field in Sitefinity after form submitting
The case
Sometimes forms contain sensitive information. We need to ensure that forms are submitted via email, but some of the field values must not be stored in the database.
Implementation
First, we need to subscribe to IFormEntryCreatedEvent. Add the following lines to Global.asax file:
private void ApplicationStartHandler(object sender, EventArgs e) { EventHub.Subscribe<IFormEntryCreatedEvent>(evt => FormEntryCreatedEventHandler(evt)); }
private void FormEntryCreatedEventHandler(IFormEntryCreatedEvent eventInfo) { // Get form info. var entryId = eventInfo.EntryId; var formId = eventInfo.FormId; var controls = eventInfo.Controls; }
We have all needed now – formId, entryId(submitted form data id) and all controls in the form.
Let’s debug to see what form property we can use.
Apparently, all forms text field names are in this format – “TextFieldController_....”
This is not useful in our case – we don’t know the field order and we want also to use this in every form we want, no matter what the field is – text, choice and etc.
Let’s check the other properties. We can see that all these form controls inherit this class – “FormEntryEventControl”.
“FieldControlName” seems to be a good candidate.
Let’s try it. Navigate to the selected form and field we want to use and click the edit link. Go to the Advanced mode of the field. Here is the property, we are looking for:
Enter “UniqueFieldName” text for example and click save.
Note: If your site is multilingual, make sure that you are saving the whole form variations by clicking the “Save all translations” button.
Test to see if we are on the right way:
Stop debugging and continue the implementation.
But seems that our field is not here:
Hm, we can see that now all controls implement “IFormEntryEventControl” interface, but this property is not there. Apparently, this is protected property of this “FormEntryEventControl” class.
We have two possible solutions for the problem:
- Make Sitefinity forms assembly “friendly” – by this case we can expand all protected fields to the world – link.
- Get the required field with reflection.
I think the second option is easiest here.
Get related form and submitted data:
// Get forms manager. FormsManager manager = FormsManager.GetManager(); var form = manager.GetForm(formId); // Get current form responce. FormEntry entry = manager.GetFormEntry(form.EntriesTypeName, entryId); // Find internall model field. var fieldName = controls .Where(x => (string)x.GetType() .GetProperty("FieldControlName").GetValue(x) == "UniqueFieldName") .Select(x => x.FieldName) .FirstOrDefault();
Get the field name and if exists in the current form, update his value:
if (!string.IsNullOrEmpty(fieldName)) { // If this field exist. if (entry.DoesFieldExist(fieldName)) { // Set our field value to null. entry.SetValue(fieldName, null); } manager.SaveChanges(); }
Let’s test again.
Seems we solved the issue.