Sometimes when building a custom HTML form to embed in a CRM form it is a requirement to get one or more sets of optionset values to use in a drop down list.
Probably the simplest way to do it is to create a small workflow plugin that will read the values and return them as a JSON string that can be consumed by the Javascript. Once you have a workflow plugin it is a simple matter to add it to an Action and then call that from the HTML page. I will show how to do this in the next post.
Below is the simple code for a plugin, this will take 2 parameters, the EntityName and the FieldName, and it will return the formatted JSON string. For a plugin this small it wasn’t worth linking any external libraries in to handle the JSON encoding as per my previous post, I create the JSON string myself in lines 22-25 using a simple string.format command.
public class GetOptionSetValues : CodeActivity
{
protected override void Execute(CodeActivityContext executionContext)
{
IWorkflowContext context = executionContext.GetExtension<IWorkflowContext>();
IOrganizationServiceFactory serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>();
IOrganizationService service = serviceFactory.CreateOrganizationService(context.InitiatingUserId);
var entityName = ENTITY.Get(executionContext);
var fieldName = FIELD.Get(executionContext);
var attReq = new RetrieveAttributeRequest();
attReq.EntityLogicalName = entityName;
attReq.LogicalName = fieldName;
attReq.RetrieveAsIfPublished = true;
var attResponse = (RetrieveAttributeResponse)service.Execute(attReq);
var attMetadata = (EnumAttributeMetadata)attResponse.AttributeMetadata;
var optionList = (from o in attMetadata.OptionSet.Options
select (string.Format("{{\"text\":\"{0}\",\"value\":\"{1}\"}}", o.Label.UserLocalizedLabel.Label, o.Value.ToString()))).ToList();
string result = "{\"options\": [" + string.Join(",", optionList) + "]}";
JSON.Set(executionContext, result);
}
[Input("EntityName")]
[RequiredArgument]
public InArgument<string> ENTITY { get; set; }
[Input("FieldName")]
[RequiredArgument]
public InArgument<string> FIELD { get; set; }
[Output("Output")]
public OutArgument<string> JSON { get; set; }
}
This will return a JSON string like this
{"options": [{ "text": "Level 1","value":"863600002"},{ "text": "Level 2","value":"863600000"},{ "text": "Another level","value":"863600001"},{ "text": "Final Value","value":"863600003"}]}
This consists of an array of values, the text value to display and the actual optionset value used in CRM.
My next post will show how to include this in an Action and use it in a HTML page with JavaScript.