I recently had a request from the business to implement a unique 8-digit (auto-incrementing) Reference number for one of their Forms. Doing a quick scan in the available Field types, I found that there wasn't any type available that fits my requirement.
I had two options to consider:- Override the Save to DB action: by overriding the Execute method and replacing the AdaptedResultList with my own which queries the WFM DB and looks for the Max Reference value and returns the incremented value at that instance; this worked well but I quickly ran into an issue wherein other Save Actions (like Send Email) were still using the original AdaptedResultList and thus the experience was inconsistent. If I were to go this route, I would have to override every possible Save action which is not very good. So I concentrated with my next option:
- Create my own Custom Field Type: I created my own type, did the necessary changes in the WFFM module settings like (add a new Field Type referencing my new custom class). The key here is to override the ControlResult property of the SingleLineText field class so that instead of taking whatever was passed from the UI, it will instead get the value from the custom method, in my case to get the 8-digit Max Value from the Reference Field in the WFFM DB. See sample code below: You may notice that I used ADO and specifically looking for a Numeric 8-digit value starting with the number 1. e.g. 10000000.
[Designer("System.Windows.Forms.Design.ParentControlDesigner, System.Design", typeof(IDesigner))]
public class ReferenceNumberText : SingleLineText
{
public override ControlResult Result
{
get
{
return CreateNewControlResultWithValue(Title, GetMaxValue());
}
}
private static ControlResult CreateNewControlResultWithValue(string name, string value)
{
return new ControlResult(name, value,"");
}
/// <summary>
/// Note: FieldName should always have the term "Reference Number" appended
/// </summary>
/// <returns></returns>
private static string GetMaxValue()
{
var builder = new StringBuilder();
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["wfm"].ConnectionString))
{
connection.Open();
using (var command = connection.CreateCommand())
{
command.Connection = connection;
builder.Append(
"SELECT MAX(CAST(Value AS INT)) FROM [Field] WHERE FieldName LIKE '%Reference Number' AND Value LIKE '1[0-9][0-9][0-9][0-9][0-9][0-9][0-9]' AND ISNUMERIC(Value) = 1");
command.CommandText = builder.ToString();
command.CommandType = CommandType.Text;
var value = command.ExecuteScalar();
return DBNull.Value == value ? "10000000" : ((int)value + 1).ToString(CultureInfo.InvariantCulture);
}
}
}
}
Comments
Post a Comment