Multi-Select Option Sets in Dynamics CRM: Part 1(See Part 2 for the Latest Code)

Slalom Consultant Xavier Vargas

Slalom Consultant Xavier Vargas has worked with Enterprise CRM customers in numerous verticals. Based in Dallas, He has also delivered training engagements as an MCT (Microsoft Certified Trainer).

*I’ve recently published an update to this post with a new fix. The code in this post is now obsolete; please visit my latest post for the new workaround.

To start off this blog, I figured I’d show you a new twist on an old trick. Microsoft Dynamics CRM doesn’t support multi-select option sets out of the box. In order to create one of these fields, we have to do a bit of JScript hackery. This is all completely unsupported but gets the job done.

So let’s jump right in. First thing you’ll need to do is create the option set that you want to convert to a multi-select:

Create your option set

`

Define the option set values

`

Next we’ll create a shadow field that will actually hold the values the user selects. This new field is called sc_ServiceInterest_value:

Create a new Multi-line text field with length equal to 2000

`

Now add both of the fields to your form and uncheck the “Visible by default” option of the Value:

Set the value field to not visible

`

Now comes the magic. You’ll need to create a new web resource with the following javascript code.

// var_sc_optionset >>  Provide schema-name for Option Set field
// var_sc_optionsetvalue >> Provide schema-name for field which will store the multi selected values for Option Set
// OS >> Provide Option Set field object
// OSV >> Provide text field object which will store the multi selected values for Option Set

//Method to convert an optionset to multi select Option Set
function ConvertToMultiSelect(var_sc_optionset, var_sc_optionsetvalue, OS, OSV)
{

if( OS != null && OSV != null )
{
  OS.style.display = "none";
  Xrm.Page.getControl(var_sc_optionsetvalue).setVisible(false);

  // Create a DIV container
  var addDiv = document.createElement("<div style='overflow-y:auto; height:80px; border:1px #6699cc solid; background-color:#ffffff;' />");
  OS.parentNode.appendChild(addDiv);

  // Initialise checkbox controls
  for( var i = 1; i < OS.options.length; i++ )
  {
    var pOption = OS.options[i];
    if( !IsChecked( pOption.text , OS, OSV) )
      var addInput = document.createElement("<input type='checkbox' style='border:none; width:25px; align:left;' />" );
    else
      var addInput = document.createElement("<input type='checkbox' checked='checked' style='border:none; width:25px; align:left;' />" );

    var addLabel = document.createElement( "<label />");
    addLabel.innerText = pOption.text;

    var addBr = document.createElement( "<br/>"); //it's a 'br' flag

    OS.nextSibling.appendChild(addInput);
    OS.nextSibling.appendChild(addLabel);
    OS.nextSibling.appendChild(addBr);
  }
}
}

///////Supported functions

  // Check if it is selected
  function IsChecked( pText , OS, OSV)
  {
    if(OSV.value != "")
    {
      var OSVT = OSV.value.split(";");
      for( var i = 0; i < OSVT.length; i++ )
      {
        if( OSVT[i] == pText )
          return true;
      }
    }
    return false;
  }

  // var_sc_optionsetvalue >> Provide schema-name for field which will store the multi selected values for Option Set
  // OS >> Provide Option Set field object
  // Save the selected text, this field can also be used in Advanced Find
  function OnSave(OS, var_sc_optionsetvalue)
  {
    var getInput = OS.nextSibling.getElementsByTagName("input");
    var result = '';

    for( var i = 0; i < getInput.length; i++ )
    {
      if( getInput[i].checked)
      {
        result += getInput[i].nextSibling.innerText + ";";
      }
    }

    //save value
    control = Xrm.Page.getControl(var_sc_optionsetvalue);
    attribute = control.getAttribute();
    attribute.setValue(result);

  }

You’ll now need to add an onLoad and onSave function call to your form, both referencing your new Javascript library.

Add the MultiSelect Library to the form

`

And now the last pieces, add function calls on the OnLoad and OnSave pointing to ConvertToMultiSelect and OnSave, respectively. You’ll need to pass the parameters defined below replacing the field names for the ones you created.

Define the OnLoad Function: ConvertToMultiSelect

`

Define the OnSave Function: OnSave

`

And you’re all done. When you open up the form it should look something like this:

The finalized form

`

One thing you should know is that the selected values are stored as semi-colon delimited values. When you run an advanced find, the results will look as follows:

Results in a listview

Please let me know if you have any comments or questions about this!

Slalom Consulting's Dallas Office Slalom Consulting's Customer focus page
More about Slalom Consulting’s Dallas office. More about Slalom Consulting’s Customer focus.

subscribe by emailSubscribe to be emailed about new CRM posts.

About Xavier Vargas
Slalom Consultant Xavier Vargas has worked with Enterprise CRM customers in numerous verticals. Based in Dallas, He has also delivered training engagements as an MCT (Microsoft Certified Trainer).

70 Responses to Multi-Select Option Sets in Dynamics CRM: Part 1(See Part 2 for the Latest Code)

  1. Patti says:

    Hi,
    I tried this but instead of checkboxes, I get a picklist. Do I have to modify the script provided at all, like adding the Option Set name and Option Set Value name? I appreciate any help you can give me.

    • Xavier Vargas says:

      Patti, I want to apologize. It seems that when I copied and pasted the code into the post, all of the brackets were pasted in incorrectly. Please use the updated code in the post which should now work properly.

      -Xavier

  2. Garrett says:

    Hi,
    This is a great help. I decided I did not want to display the Label of the field name on my form. After I made that change the height paramater on the multi-select is no longer enforced. Instead the box is cut of at about 20px. Does this happen to you? What needs to be done to resolve the issue?
    Thanks

    • Xavier Vargas says:

      Strange. This is what it looks like on my system when I remove the label. I’ve censored the values for my client’s privacy. http://i.imgur.com/TypXa.png

      Is this what you’re seeing?

      • Garrett says:

        I was able to fix the issue. I could not get it to display properly while using an optionset and hiding the label. However, I get the desired result by using a multiline text field and setting the field formatting to auto expand. This way I can still hide the label and get a larger list area.

        So I ended up with two multiline text fields. The first displays the HTML formating of the multi-select option set. The second saves the raw results (Shoe Shining;Suit Cleaning;)

        Thanks again for this great tutorial!

  3. Matt says:

    I tried this and it seems to work great if the field isn’t a required field. For some reason, even if I check one or more boxes, when I try to save, it tells me that I need to supply a value for the field. I have tried adding a default value for the field, but it doesn’t seem to work. Any thoughts?

    • Xavier Vargas says:

      Unfortunately, this is a little more complex than it would seem. Since we’re injecting HTML into the DOM, the field that you’re seeing isn’t actually a CRM control. When you set the checkboxes on this control, no values are actually being written to a CRM field. This only happens on the save. The validation of the required field check happens after you press save but before the OnSave function fires.

      Because of all this, the required field error will always appear. In order to get around this, you’ll need to modify the script that is being injected and have it call the onSave function by adding an onclick event registration to each checkbox.

      I’ll update the post as soon as I can to reflect this workaround.

  4. Valerie says:

    Hello,
    I’m not an IT person but I have been asked to help with prepping CRM for data transfer. Your instructions were very easy to follow but unfortunately when I open the form I get the following message:

    There was an error with this field’s customized event.
    Field: window
    Event: onload
    Error: Object expected

    If you have any ideas or suggestions on what I can do to make this work I would really appreicate it. I apologize in advance for this ‘user error’ that might be an easy fix.

    Thank you!

  5. AJ says:

    Hi Xavier,

    In one of your screenshots above you reference a “sc_global” library script. Is this also required to make this functionality work? I am having difficulties getting this working and just wanted to make sure I wasn’t missing anything.

    Thank you.

  6. Pamela says:

    Xavier,
    Great post! Thanks so much. Having trouble getting this to work when I added more than one multi-select list per form. Should it still work? BTW – I added the new fields to the handlers.

  7. Pamela says:

    Xavier,
    It is now working for multiple fields, but when I save and close the record and reopen, only the first checkbox is selected even if I have selected other options. The value field is working correctly.

    • Pamela,

      I’m glad you got it working. For anyone else that might run into the same issue, Pamela accidentally put a space after the value stored in the value field so that each option had a space before the semicolon. This was causing the code to not parse the values correctly. Removing the space fixed the issue.

      -Xavier

  8. Garcia says:

    Great Post i love it.

    Xavier, could this be done with lookup fields? Can you give me some tips?

    • It could, but it would need to be a completely custom solution. If I were going to try an do a custom party list I’d look at creating a custom control that gets populated based on the values within hidden 1:N relationships. It would be quite a bit of work since you’d need to create the actual party list control that allows lookups on any of X number of entities, then the record in question would need to have those corresponding relationships created, and finally the visual control on the page would need to hold all of the values like a true party list.

      Please let me know if you go down this path and what your results are.

      -Xavier

      • Pamela says:

        Xavier,
        I am using your multi-select option list on the Opportunity form. I have several currency types and have noticed that if I change a currency type in an Opportunity record (doesn’t do this on any other form), I get an error. It says the error is due to a customized event and this is the only one I have. Here’s the error I get:

        There was an error with this field’s customized event
        Field: transactioncurrencyid
        Event: onchange
        Error: Unable to set value of the property ‘Data Value’: object is null or undefined.

        Help!

      • Pamela says:

        Xavier,
        I have a workflow that creates an Opportunity record (which is where my multi-select option list resides). When setting the properties for the Opportunity record to be created, it does not show the multi-select list. I want to be able to check one of the boxes as the default for all the records created with this workflow. How can I get the multi-list to show up in order to do this?

        Thanks!
        Pamela

      • Garrett says:

        I doubt it would be easy to get the multiselect list to show up on the workflow screens. However, you do have the field that stores the values for the each item that is checked in the multiselect list. Why don’t you just specify the default value in there separated by ‘;’. The code would read this on the form and check the box when displayed. After all the multislect list is only a interaction with the true data within the multiline text field.

      • You’re exactly right, Garret. That’s the approach I would take.

  9. Pamela says:

    Xavier,
    I was able to resolve the error issue by deleting the currency field from the form, saving and publishing, and then adding it back. Strange, but oh well. I do still need help with my previous post, though.

    Thanks!
    Pamela

    • Laura says:

      I had that too Pamela, and your solution worked for me too. I suspect this is something that doesn’t work quite right in the upgrade, as I’m sure this happened to me on another entity too.

  10. snehadeore says:

    Hello Sir,

    Thanks for the blog,I have used ‘ Multi Select Option Set’

    I have Category(which is an optionset) and Subcategory( Multi Select Option Set(as per ur blog)) and Mutliselect name sc_ServiceInterest_value ,

    now when a category is changed accordingly subcategory should be changed or listed(Multiple Cascading)

    how should I do it ?

  11. Dian says:

    Hi Xavier,
    What is the OS and OSV value? I am not sure what an field object is?

    • The OS and OSV are the OptionSet and OptionSet Value fields, respectively. They are the fields on the form that are passed into the code and then manipulated to show the new multi-select control.

  12. card says:

    Worked wonderful! Thank you!

  13. udaw says:

    Hi Xavier,

    how can I disable this control? I want to protect it from changes.

  14. Samitha says:

    Hi,
    What is field object which you have mentioned as OS and OSV.
    Actually i am new to MS CRM so dont know how to create field object could guide me.

    • Darth Maul says:

      Hey,
      As i always say to my friends, try to read a little bit more.
      Read the description of the code.

      Xavier Vargas, you made a great job here.

  15. Terry says:

    This is great, how would you implement this for showing an N:N relationship instead of option sets.

  16. Jyoti says:

    Unhandled Exception: System.ServiceModel.FaultException`1[[Microsoft.Xrm.Sdk.OrganizationServiceFault, Microsoft.Xrm.Sdk, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]: System.ArgumentException: Column ‘new_product__c_value_Value’ does not belong to table .Detail:

    -2147220970

    System.ArgumentException: Column ‘new_product__c_value_Value’ does not belong to table .
    2012-03-15T17:48:59.1046756Z

    I had tired this, i am not able to delete the fields and this error shows every time i try to access my contacts in which i tired this. please help

    • Jyoti,

      I’m not exactly sure what this is from as the code above is only client side script and what you posted is a .NET exception. It looks like you might have a plugin enabled that is causing this issue.

      I would recommend disabling all plugins on the system if possible. If this doesn’t work, you can try disabling all javascript on the culprit form. You can do this by going to the form and clicking on the form properties button. From there you can disable all libraries and event handlers.

      If this still does not solve the issue you should try running a platform trace to capture more info about the error.

      -Xavier

  17. A. Smith says:

    I’m learning CRM day by day, and yours is the most straight forward and thorough walkthrough so far. Thanks

  18. MP says:

    This is an excellent control – worked great in my test implmentation.
    I have a situation where the customer wants to use global option set on various entities (supported by CRM) but by displaying Radio Options rather than drop down / or multi select box (as in this post). Any suggestions?

  19. 4ndy says:

    Excellent walk through instructions for a Javascript beginner. Many thanks!

  20. pearse says:

    Is it necessary to create sc_global library. I created sc_MultiSelect_js and on it’s onload and onsave pointed the ConvertToMultiSelect and OnSave respectively. Am I right. I ask as it is not working for me.

  21. pearse says:

    re: the last question I got it to work.
    but I have a question though- I have 4 fields in the form which have option sets. Do I have to have 4 web resources with js script or can one be used globally for all. is that what is sc_global . please advise. appreciate very much. thanks in advance

    • Glad you got it working! To answer your question, the ConvertToMultiSelect function allows you to pass in any parameters meaning it can be reused across different fields. You only need the single javascript functions outlined above and multiple event registrations for each different field. Hope this helps.

      • pearse says:

        what does ” you need multiple event registrations for each different field ” mean?
        would you be kind enough to help me on this. i got this function to work for one field. I have 2 other fields Say- A & B in the same form which needs multiselect . What should I do ?
        Thanks in advance

  22. Drew Baratz says:

    would it be possible to have your firm implement this for me in my hosted dynamics crm application?

  23. pearse says:

    Thanks for your reply and advise. I will give it a try.

  24. Joy! After 6 hours of messing with this I finally got it working. Thank you thank you!

  25. Mathew says:

    Hi Xavier,

    I’m new to Dynamics CRM 2011 and love it. I added your multi-select option js to a custom Entity called “Licenses” and it works great! Thank you. Now, for my issue. I tried to do this same thing for the Opportunity entity and now I’m getting an error code:

    ====== ERROR =======
    OnSave

    Error: The Value of the property “OnSave” is null or undefined, not a Function object.
    ====================

    From what I can tell, I’ve set everything up exactly the same as the previous Licenses Entity. Could it be that I named the fields exactly the same?

    Any help on this would be appreciated.

  26. mcolby100 says:

    Hi Xavier,

    I\’m new to Dynamics CRM 2011 and love it. I added your multi-select option js to a custom Entity called \”Licenses\” and it works great! Thank you. Now, for my issue. I tried to do this same thing for the Opportunity entity and now I\’m getting an error code:

    ====== ERROR =======
    OnSave

    Error: The Value of the property \”OnSave\” is null or undefined, not a Function object.
    ====================

    From what I can tell, I\’ve set everything up exactly the same as the previous Licenses Entity. Could it be that I named the fields exactly the same?

    Any help on this would be appreciated.

  27. Ayan says:

    Hi Xavier.

    It worked for me and really a great stuff.
    Love it. :)

  28. Garrett says:

    Hi Xavier,

    We have been using this multi-select list for almost a year now. It works great for selecting multiple items for a single record. However, we keep getting requests for bulk editing the multi-select list for a group of records. Currently we are looking at some ways to keep the data clean through a backdoor. Do you have any ideas to accomplish bulk editing on the multi-select list by a user?

    Thanks again for this great functionality!

  29. Jens Borowy says:

    Hello Xavier,

    according to Jyoti’s reply, I’ve got the same problem and spend already hours of research and testing. But meanwhile I have no idea left and hope you may have a solution for this. I’ve also post this in the MS-CRM-Forum, unfortunately without any responds.

    It’s a large amount of text with a lot information from the logfiles, but may you got some time to read this: http://social.microsoft.com/Forums/en-US/crm/thread/a02b96b5-1f5a-469a-90a3-9b98c00a093d

    Thanks in advance.

    Kind regards

    Jens Borowy

  30. Andrea Lange says:

    I was struggling big time with how to do a data import for this and I FINALLY got it to work. Basically in the Type Value field, you enter the first item followed by a semi colon and then the second item with no spaces. Example:
    Item1;Item2

  31. Steve Cashwell says:

    I’ve got it mostly working except that when I open a previous record where I have saved some ‘checks’, none of them are showing as ‘checked’. All of the multi-select options are blank, as if nothing has been selected before. Any ideas??

  32. Brett says:

    This is working great for me, hopefully will handle an import from Act! Thanks for posting.

  33. Jebin says:

    How to make this mult-select option field as ‘Mandatory’?

  34. Walker says:

    Xavier,

    It appears that the new update pushed out this week has broken the above. I cannot seem to find where the error is occurring. Is anyone else experiencing these problems? Everything was working fine a week ago and now i keep getting errors.

  35. Chitra says:

    Even i am having the same problem as Walker and Pete

  36. Pingback: Multi-Select Option Sets: Part 2 « The Slalom Blog

  37. Parvati says:

    Previously ,my script was working for crm2011 online, but now its not working,giving error ,There was an error with fields customized event,
    Field:window
    Event:onload
    error:undefined,what is the cause(may be UI upgraded),to make that script work again what i need to do ,plz let me know……

  38. Leanne says:

    Fantastic instructions but when I go to the field I get an error that says:
    Field: window
    Event: onload
    Error: Undefined.

    Any idea what I may have missed here?

  39. Pingback: CRM 2011 Multi Pick list | DynamicsCRM@MindfireSolutions

  40. BOLLE REDDAT Jérémie says:

    I found a solution for act as required : I’m on CRM 2011 R12

    So :

    On the onSave Event check “Pass execution context as first parameter”

    Modify the OnSave function like this :

    function OnSave(context,OS, var_sc_optionsetvalue,var_sc_optionset)
    {

    var getInput = OS.nextSibling.getElementsByTagName(“input”);
    var result = ”;
    var total =0
    for( var i = 0; i < getInput.length; i++ )
    {
    if( getInput[i].checked)
    {
    total++
    result += getInput[i].nextSibling.innerText + ";";
    }
    }

    //save value
    control = Xrm.Page.getControl(var_sc_optionsetvalue);
    attribute = control.getAttribute();
    attribute.setValue(result);
    if(total==0)
    {
    alert("Thanks to select one or more than one value");
    context.getEventArgs().preventDefault();
    return false;
    }
    else{
    return true;
    }

    }

    it's working fine for me. the only detail missing is the red * to see that the field is mandatory

  41. BOLLE REDDAT Jérémie says:

    If found a solution for the red *

    juste for creation the div container i changed like this :

    // Create a DIV container
    var addDiv = document.createElement(“”);
    OS.parentNode.appendChild(addDiv);
    var addLabeltitle = document.createElement( “”);
    addLabeltitle.innerText = “Select one or more than one record “;
    OS.nextSibling.appendChild(addLabeltitle)
    var addLabeltitle1 = document.createElement( “”);
    addLabeltitle1.setAttribute(‘src’, ‘/_imgs/frm_required.gif’);
    OS.nextSibling.appendChild(addLabeltitle1)
    var addBrtitle3 = document.createElement( “”); //it’s a ‘br’ flag
    OS.nextSibling.appendChild(addBrtitle3);
    var addBrtitle4 = document.createElement( “”); //it’s a ‘br’ flag
    OS.nextSibling.appendChild(addBrtitle4);

    // Initialise checkbox controls

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 129 other followers

%d bloggers like this: