Are you looking for a generic method to read the values from any type of Sitecore Form fields? Here is the solution.
private static Dictionary<Guid, string> FormFieldsToDictionary(IList<IViewModel> fields)
{
Dictionary<Guid, string> fielDictionary = new Dictionary<Guid, string>();
foreach (var field in fields)
{
fielDictionary.Add(Guid.Parse(field.ItemId), field.GetType().GetProperty("Value")?.GetValue(field, null)?.ToString() ?? string.Empty);
}
return fielDictionary;
}
private static string GetValue(IViewModel field)
{
if (field == null)
{ return default(string); }
if ((field as StringInputViewModel) != null)
{
return (string)(object)(field as StringInputViewModel).Value;
}
if (field is ListViewModel)
{
var listField = (ListViewModel)field;
var array = listField?.Value?.ToArray();
if (array == null)
{
return string.Empty;
}
return String.Join(",", array);
}
if (field is DateViewModel)
{
var dateField = (DateViewModel)field;
return dateField.Value.HasValue ? dateField.Value.Value.ToShortDateString() : string.Empty;
}
if (field is NumberViewModel)
{
var numberField = (NumberViewModel)field;
return numberField.Value.HasValue ? numberField.Value.ToString() : string.Empty;
}
if (field is TextViewModel)
{
var textField = (TextViewModel)field;
return (string)(object)textField.Text;
}
if (field is CheckBoxViewModel)
{
var checkbox = (CheckBoxListViewModel)field;
return (string)(object)checkbox.Value;
}
return default(string);
}
Utilization:
protected override bool Execute(UpdateContactData data, FormSubmitContext formSubmitContext)
{
var fieldsDictionary = FormFieldsToDictionary(formSubmitContext.Fields);
// From here you can create a model from fieldsDictionary, call any API and return call status
}
Hope this helps someone. Any questions, leave a comment.
Happy Sitecoring!