aanch
aanch

Reputation: 167

How to set Option set value in CRM 2011?

I have an Option set in CRM 2011. It has four options:

  1. Public
  2. Private
  3. Subsidiary
  4. Other

Through plugin I want to set the value of this option set. Can anyone provide me the statement to set the value of this option set?

Upvotes: 5

Views: 35507

Answers (3)

GoBeavs
GoBeavs

Reputation: 499

I thought I'd share some code for handling option-sets in CRM here...

fieldValue = ((OptionSetValue)entity.Attributes[field]).Value.ToString();

//need to get Option Set display label based on its value.  This requires getting attribute metadata
RetrieveAttributeRequest attributeRequest = new RetrieveAttributeRequest
{
    EntityLogicalName = entity.LogicalName,
    LogicalName = field,
    RetrieveAsIfPublished = true
};

RetrieveAttributeResponse attributeResponse = (RetrieveAttributeResponse)orgContext.Execute(attributeRequest);
EnumAttributeMetadata attributeMetadata = (EnumAttributeMetadata)attributeResponse.AttributeMetadata;

foreach (OptionMetadata om in attributeMetadata.OptionSet.Options)
{
    if (om.Value == ((OptionSetValue)entity.Attributes[field]).Value)
    {
        fieldlabel = om.Label.UserLocalizedLabel.Label;
    }
}

return fieldlabel;

Upvotes: 0

gabore
gabore

Reputation: 353

How to set optionsetvalue in plugins

In plugins you can write yourEntity.yourAttribute = new OptionSetValue(INDEX); The INDEX is an int you can look up in your optionset editor (default values are several digit long).

OR

You set the optionset like yourEntity.Attributes.Add(“yourAttribute”, new OptionSetValue(INDEX));

Upvotes: 10

Philip Rich
Philip Rich

Reputation: 637

You can set an option set value using the following:-

OptionSetValue myOptionSet = new OptionSetValue();
myOptionSet.Value = xxxx  
myEntity.Attributes["optionSetAttributeName"] = myOptionSet;

// Where xxxx represents the value desired and can be checked on the attribute metadata page within the entity customisations

Whether 'myEntity' is actually preImage/postImage or just a dynamically created entity in the plug-in will determine whether you need to actually call the update method, but essentially this is the way you set the option set value and update the attribute.

Upvotes: 8

Related Questions