Adding records to Umbraco Contour programmatically
I just had to programmatically add records to an Umbraco Contour Form. Since I couldn’t find any documentation on how to do this, I thought I would post how I did this.
I have an input box (tbEmail) and a button (btnSubmit). On the click event of btnSubmit I got the following code, that adds a record to the form.
btnSubmit_Click
-
protected void btnSubmit_Click(object sender, EventArgs e)
-
{
-
var recordStorage = new RecordStorage();
-
var formStorage = new FormStorage();
-
var form = formStorage.GetForm(new Guid("my form guid"));
-
-
var recordService = new RecordService(form);
-
recordService.Open();
-
-
var record = recordService.Record;
-
record.IP = Request.UserHostAddress;
-
record.UmbracoPageId = umbraco.presentation.nodeFactory.Node.GetCurrent().Id;
-
recordStorage.InsertRecord(record, form);
-
foreach (var field in recordService.Form.AllFields)
-
{
-
if (field.Caption == "#Email")
-
{
-
var key = Guid.NewGuid();
-
var recordField = new RecordField()
-
{
-
Field = field,
-
Key = key,
-
Record = record.Id,
-
Values = new List<object>() { tbEmail.Text }
-
};
-
var recordFieldStorage = new RecordFieldStorage();
-
recordFieldStorage.InsertRecordField(recordField);
-
record.RecordFields.Add(key, recordField);
-
}
-
}
-
recordService.Submit();
-
recordService.SaveRecord();
-
recordService.Dispose();
-
}</object>
Nice post. I guess this should be in the API documentation.
There’s a possible issue with not creating all the fields to begin with, as it will be a source of possible problems if you open the form later on and try to access a field which does not exists.
Question is if it’s better to create all the fields and leave values as a new empty List.
Second that Harald
Third that. Thanks for the blog on this.