Tony Oswald
Tony Oswald

Reputation: 1

How do I programmatically add records to an Umbraco v8 form?

I'm looking to add records to an Umbraco v8 form. I know I need the form guid. Is this how I'd do it? Something like this?

public void PostFormData()
{
Guid FormGuid = new Guid("8494a8f0-94da-490e-bd61-7e658c226142");

var form = _formService.Get(FormGuid);

 //place for field data into fieldDic
var fieldDic = new Dictionary<Guid, RecordField>();

var firstName = form.AllFields.First(f => f.Alias == "firstName");
var firstNameRecord = new RecordField(firstName);
firstNameRecord.Values = new List<object>() { "Mad Max" };
fieldDic.Add(firstName.Id, firstNameRecord);

var record = new Record()
{
Created = DateTime.Now,
Form = form.Id,
RecordFields = fieldDic,
State = FormState.Submitted,
};
record.RecordData = record.GenerateRecordDataAsJson();
_recordStorage.InsertRecord(record, form);
}

Upvotes: 0

Views: 1080

Answers (1)

Chester Campbell
Chester Campbell

Reputation: 21

Here's how I do it. Note, I'm hard-coding the Record.UmbracoPageId to -1 while you might want to actually pass in the correct page ID.

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using Umbraco.Core;
using Umbraco.Core.Composing;
using Umbraco.Core.Logging;
using Umbraco.Forms.Core.Data.Storage;
using Umbraco.Forms.Core.Models;
using Umbraco.Forms.Core.Persistence.Dtos;
using Umbraco.Forms.Core.Services;

namespace myProject.Services
{
    public class FormServiceComposer : IUserComposer
    {
        public void Compose(Composition composition)
        {
            composition.Register<IFormService, FormService>(Lifetime.Request);
        }
    }

    public interface IFormService
    {
        void InsertFormData(Guid formGuid, object formModel, string ipAddress);
    }

    public class FormService : IFormService
    {
        private readonly ILogger _logger;
        private readonly Umbraco.Forms.Core.Services.IFormService _formService;
        private readonly IRecordStorage _recordStorage;
        private readonly IRecordFieldStorage _recordFieldStorage;
        private readonly IWorkflowService _workflowService;

        public FormService(ILogger logger, Umbraco.Forms.Core.Services.IFormService formService, IRecordStorage recordStorage, IRecordFieldStorage recordFieldStorage, IWorkflowService workflowService)
        {
            _logger = logger;
            _formService = formService;
            _recordStorage = recordStorage;
            _recordFieldStorage = recordFieldStorage;
            _workflowService = workflowService;
        }

        #region IFormService

        public void InsertFormData(Guid formGuid, object formModel, string ipAddress)
        {
            try
            {
                Form form = _formService.GetForm(formGuid);

                Record record = new Record();

                foreach (Field field in form.AllFields)
                {
                    string caption = CleanCaption(field.Caption);

                    if (formModel.GetType().GetProperty(caption) == null) continue;

                    var propertyValue = formModel.GetType().GetProperty(caption).GetValue(formModel, null);

                    if (propertyValue != null)
                    {
                        List<object> values = ExtractValues(propertyValue);

                        RecordField recordField = new RecordField
                        {
                            Alias = field.Alias,
                            FieldId = field.Id,
                            Field = field,
                            Key = Guid.NewGuid(),
                            Record = record.Id,
                            Values = values
                        };

                        _recordFieldStorage.InsertRecordField(recordField);

                        record.RecordFields.Add(recordField.Key, recordField);
                    }
                }

                record.Form = formGuid;
                record.IP = ipAddress;
                record.UmbracoPageId = -1;
                record.State = Umbraco.Forms.Core.Enums.FormState.Approved;
                record.RecordData = record.GenerateRecordDataAsJson();

                _recordStorage.InsertRecord(record, form);

                _recordStorage.DisposeIfDisposable();
            }
            catch (Exception ex)
            {
                _logger.Error<FormService>(ex, "Failed inserting Umbraco Forms data for {formGuid}");
            }
        }

        #endregion IFormService

        #region Private

        private string CleanCaption(string caption)
        {
            Regex rgx = new Regex("[^a-zA-Z0-9 -]");

            return rgx.Replace(caption.Trim().Replace(" ", ""), "");
        }

        private List<object> ExtractValues(object propertyValue)
        {
            List<object> result = new List<object>();

            if (propertyValue is string == false && propertyValue.GetType().GetGenericTypeDefinition() == typeof(List<>))
            {
                IEnumerable<object> _propertyValue = (IEnumerable<object>)propertyValue;

                if (_propertyValue.Any())
                {
                    if (_propertyValue.First().GetType().GetProperties().Count() > 1)
                    {
                        JArray _properties = JArray.Parse(JsonConvert.SerializeObject(propertyValue));

                        foreach (JToken item in _properties)
                        {
                            string _value = string.Empty;

                            foreach (var _property in _propertyValue.First().GetType().GetProperties())
                            {
                                string _key = _property.Name;

                                _value = _value + (_value == "" ? "" : " - ") + item[_key].ToString();
                            }

                            result.Add(_value);
                        }
                    }
                    else
                    {
                        string _key = _propertyValue.First().GetType().GetProperties().First().Name;

                        JArray _properties = JArray.Parse(JsonConvert.SerializeObject(propertyValue));

                        foreach (JToken item in _properties)
                        {
                            result.Add(item[_key].ToString());
                        }
                    }
                }
            }
            else
            {
                result.Add(propertyValue);
            }

            return result;
        }

        #endregion Private
    }
}

Upvotes: 2

Related Questions