Personalizar opciones

Normalmente, usa opciones globales (conjuntos de opciones) para establecer campos de modo que diferentes campos puedan compartir el mismo conjunto de opciones, que se mantienen en una ubicación. A diferencia de las opciones local, que se definen solo para una columna de tabla específica, puede reutilizar opciones globales. También las verá usadas en los parámetros de solicitudes, de manera similar a una enumeración.

Nota

Solo el editor de una solución administrada puede importar cambios que eliminen una opción de un conjunto de opciones globales. Esto incluye soluciones publicadas por Microsoft, como los conjuntos de opciones globales listas para usar. Para realizar un cambio en en los conjuntos de opciones, se debe realizar una actualización a la solución que agregó el conjunto de opciones. Más información: Actualizar una solución. Los usuarios pueden eliminar manualmente una opción en su entorno si no pueden modificar la solución o ponerse en contacto con el editor de soluciones, pero esto debe hacerse en cada entorno de forma manual.

Cuando define una opción global usando CreateOptionSetRequest, le recomendamos que deje que el sistema asigne un valor. Realice esta acción al pasar un valor null al crear la nueva instancia de OptionMetadata. Cuando defina una opción, contendrá un prefijo de valor de opción específico para el contexto del editor establecido para la solución en la que se crea la opción. Este prefijo ayuda a reducir la posibilidad de crear opciones duplicadas para un solución administrada y en cualquier opción que esté definida en las organizaciones donde está instalado solución administrada. Para obtener más información, vea Combinar opciones.

Puede descargar el código de ejemplo aquí.

Clases de solicitud de mensajes

Utilice las siguientes clases de solicitud de mensajes para trabajar con opciones globales.

Utilice las siguientes clases de solicitud de mensajes para trabajar con opciones globales y locales.

Recuperar una elección global

El siguiente ejemplo de código muestra cómo recuperar una elección global por nombre usando el mensaje RetrieveOptionSetRequest:

// Use the RetrieveOptionSetRequest message to retrieve
// a global option set by it's name.
RetrieveOptionSetRequest retrieveOptionSetRequest =
    new RetrieveOptionSetRequest
    {
        Name = _globalOptionSetName
    };

// Execute the request.
RetrieveOptionSetResponse retrieveOptionSetResponse =
    (RetrieveOptionSetResponse)svc.Execute(
    retrieveOptionSetRequest);

Console.WriteLine("Retrieved {0}.",
    retrieveOptionSetRequest.Name);

// Access the retrieved OptionSetMetadata.
OptionSetMetadata retrievedOptionSetMetadata =
    (OptionSetMetadata)retrieveOptionSetResponse.OptionSetMetadata;

// Get the current options list for the retrieved attribute.
OptionMetadata[] optionList =
    retrievedOptionSetMetadata.Options.ToArray();

Crear una opción global

Utilizar el mensaje CreateOptionSetRequest para crear una nueva opción global. Esatblezca la propiedad IsGlobal en true para indicar que la opción es global. El siguiente ejemplo de código crea una opción global llamada "Ejemplo conjunto de opciones":

// Define the request object and pass to the service.
CreateOptionSetRequest createOptionSetRequest = new CreateOptionSetRequest
{
    // Create a global option set (OptionSetMetadata).
    OptionSet = new OptionSetMetadata
    {
        Name = _globalOptionSetName,
        DisplayName = new Label("Example Option Set", _languageCode),
        IsGlobal = true,
        OptionSetType = OptionSetType.Picklist,
        Options =
    {
        new OptionMetadata(new Label("Open", _languageCode), null),
        new OptionMetadata(new Label("Suspended", _languageCode), null),
        new OptionMetadata(new Label("Cancelled", _languageCode), null),
        new OptionMetadata(new Label("Closed", _languageCode), null)
    }
    }
};

// Execute the request.
CreateOptionSetResponse optionsResp =
    (CreateOptionSetResponse)svc.Execute(createOptionSetRequest);

Crear una columna de opciones que utilice una opción global

El ejemplo siguiente muestra cómo crear una columna de opciones que usa una opción global mediante CreateAttributeRequest:

// Create a Picklist linked to the option set.
// Specify which entity will own the picklist, and create it.
CreateAttributeRequest createRequest = new CreateAttributeRequest
{
    EntityName = Contact.EntityLogicalName,
    Attribute = new PicklistAttributeMetadata
    {
        SchemaName = "sample_examplepicklist",
        LogicalName = "sample_examplepicklist",
        DisplayName = new Label("Example Picklist", _languageCode),
        RequiredLevel = new AttributeRequiredLevelManagedProperty(AttributeRequiredLevel.None),

        // In order to relate the picklist to the global option set, be sure
        // to specify the two attributes below appropriately.
        // Failing to do so will lead to errors.
        OptionSet = new OptionSetMetadata
        {
            IsGlobal = true,
            Name = _globalOptionSetName
        }
    }
};

svc.Execute(createRequest);

Actualizar una opción global

El siguiente ejemplo de código muestra cómo actualizar la etiqueta de una elección global por nombre usando UpdateOptionSetRequest:

// Use UpdateOptionSetRequest to update the basic information of an option
// set. Updating option set values requires different messages (see below).
UpdateOptionSetRequest updateOptionSetRequest = new UpdateOptionSetRequest
{
    OptionSet = new OptionSetMetadata
    {
        DisplayName = new Label("Updated Option Set", _languageCode),
        Name = _globalOptionSetName,
        IsGlobal = true
    }
};

svc.Execute(updateOptionSetRequest);

//Publish the OptionSet
PublishXmlRequest pxReq1 = new PublishXmlRequest { ParameterXml = String.Format("<importexportxml><optionsets><optionset>{0}</optionset></optionsets></importexportxml>", _globalOptionSetName) };
svc.Execute(pxReq1);

Opciones de ordenación

El siguiente ejemplo de código muestra cómo se pueden ordenar las opciones de la elección global usando OrderOptionRequest:

// Change the order of the original option's list.
// Use the OrderBy (OrderByDescending) linq function to sort options in
// ascending (descending) order according to label text.
// For ascending order use this:
var updateOptionList =
    optionList.OrderBy(x => x.Label.LocalizedLabels[0].Label).ToList();

// For descending order use this:
// var updateOptionList =
//      optionList.OrderByDescending(
//      x => x.Label.LocalizedLabels[0].Label).ToList();

// Create the request.
OrderOptionRequest orderOptionRequest = new OrderOptionRequest
{
    // Set the properties for the request.
    OptionSetName = _globalOptionSetName,
    // Set the changed order using Select linq function
    // to get only values in an array from the changed option list.
    Values = updateOptionList.Select(x => x.Value.Value).ToArray()
};

// Execute the request
svc.Execute(orderOptionRequest);

//Publish the OptionSet
PublishXmlRequest pxReq4 = new PublishXmlRequest {
ParameterXml = String.Format("<importexportxml><optionsets><optionset>{0}</optionset></optionsets></importexportxml>", _globalOptionSetName)
};
svc.Execute(pxReq4);

Recuperar todas las elecciones globales

El siguiente ejemplo de código muestra cómo recuperar todas las elecciones globales usando RetrieveAllOptionSetsRequest:

// Use RetrieveAllOptionSetsRequest to retrieve all global option sets.
// Create the request.
RetrieveAllOptionSetsRequest retrieveAllOptionSetsRequest =
    new RetrieveAllOptionSetsRequest();

// Execute the request
RetrieveAllOptionSetsResponse retrieveAllOptionSetsResponse =
    (RetrieveAllOptionSetsResponse)svc.Execute(
    retrieveAllOptionSetsRequest);

// Now you can use RetrieveAllOptionSetsResponse.OptionSetMetadata property to
// work with all retrieved option sets.
if (retrieveAllOptionSetsResponse.OptionSetMetadata.Count() > 0)
{
    Console.WriteLine("All the global option sets retrieved as below:");
    int count = 1;
    foreach (OptionSetMetadataBase optionSetMetadata in
        retrieveAllOptionSetsResponse.OptionSetMetadata)
    {
        Console.WriteLine("{0} {1}", count++,
            (optionSetMetadata.DisplayName.LocalizedLabels.Count >0)? optionSetMetadata.DisplayName.LocalizedLabels[0].Label : String.Empty);
    }
}

Eliminar una opción global

El siguiente ejemplo de código muestra cómo comprobar si otro componente de la solución está utilizando una opción global mediante el uso del mensaje RetrieveDependentComponents (RetrieveDependentComponents Function o RetrieveDependentComponentsRequest) y luego cómo eliminarlo usando el mensaje DeleteOptionSet (para el SDK para .NET, utilice DeleteOptionSetRequest):

// Create the request to see which components have a dependency on the
// global option set.
RetrieveDependentComponentsRequest dependencyRequest =
    new RetrieveDependentComponentsRequest
    {
        ObjectId = _optionSetId,
        ComponentType = (int)componenttype.OptionSet
    };

RetrieveDependentComponentsResponse dependencyResponse =
    (RetrieveDependentComponentsResponse)svc.Execute(
    dependencyRequest);

// Here you would check the dependencyResponse.EntityCollection property
// and act as appropriate. However, we know there is exactly one
// dependency so this example deals with it directly and deletes
// the previously created attribute.
DeleteAttributeRequest deleteAttributeRequest =
    new DeleteAttributeRequest
{
    EntityLogicalName = Contact.EntityLogicalName,
    LogicalName = "sample_examplepicklist"
};

svc.Execute(deleteAttributeRequest);

Console.WriteLine("Referring attribute deleted.");

// Finally, delete the global option set. Attempting this before deleting
// the picklist above will result in an exception being thrown.
DeleteOptionSetRequest deleteRequest = new DeleteOptionSetRequest
{
    Name = _globalOptionSetName
};

svc.Execute(deleteRequest);

Consulte también

Crear y actualizar opciones mediante la API web

Nota

¿Puede indicarnos sus preferencias de idioma de documentación? Realice una breve encuesta. (tenga en cuenta que esta encuesta está en inglés)

La encuesta durará unos siete minutos. No se recopilan datos personales (declaración de privacidad).