I recently needed a custom workflow for an Umbraco Cloud project. My Custom Workflow needed to send some form details using a third-party API. I achieved this using the rest client on submission.
Here are the 3 steps to make this possible on an Umbraco 12+ project!
1- Install Umbraco Forms for your Umbraco 12+ project
dotnet add package Umbraco.Forms
You'll need to buy your license for your domain when you go live!
2- Add a new class for your custom workflow and inherit WorkflowType
namespace MySite.FormExtensions
{
public class CustomWorkflow : WorkflowType
{
//We need to read our API keys from secrets/appconfig.json
private readonly IConfiguration _configuration;
public CustomWorkflow (IConfiguration configuration)
{
_configuration = configuration;
Id = new Guid("D6A2C01-CF50-11DE-B075-55B055D75689");
Name = "Custom workflow name";
Description = "Custom workflow description";
Icon = "icon-terminal";
Group = "Services";
}
public override WorkflowExecutionStatus Execute(WorkflowExecutionContext context)
{
//Get your form information from here
foreach (RecordField rf in context.Record.RecordFields.Values)
{
// and we can then do something with the collection of values on each field
List<object> vals = rf.Values;
// or get it as a string
rf.ValuesAsString(false);
}
//or get them one by one
var fieldName = context.Record.GetRecordFieldByAlias("fieldAlias")?.Values;
var options = new RestClientOptions(_configuration["Rest:Api:BaseUrl"]);
options.Authenticator = new HttpBasicAuthenticator(_configuration["Rest:Api:Username"], _configuration["Rest:Api:Password"]);
var client = new RestClient(options);
var request = new RestRequest("", Method.Post);
request.AddHeader("accept", "application/json");
request.AddHeader("content-type", "application/json");
request.AddHeader("authorization", "Basic " + options.Authenticator);
request.AddJsonBody(vals.ToJson(), false);
var response = client.PostAsync(request);
context.Record.State = FormState.Approved;
return WorkflowExecutionStatus.Completed;
}
public override List<Exception> ValidateSettings()
{
return new List<Exception>();
}
}
}
3- Register your custom workflow class
public class CustomWorkflowComposer : IComposer
{
public void Compose(IUmbracoBuilder builder)
{
builder.AddFormsWorkflow<CustomWorkflow>();
}
}
Add your custom workflow to your form's workflow now, either on the submission step or on approval.
The only thing to be aware of here is how your third party wants your data. Mine asked for JSON format hence the line
request.AddJsonBody(vals.ToJson(), false);
That's it :)
Hope this will be useful for you!
B
Top comments (0)