Skip to main content

Usar datos de Salesforce en código Apex

Nota

Nota

¿Es su idioma de aprendizaje español (LATAM)? En esta insignia, las validaciones de los retos prácticos de Trailhead funcionan en inglés. Entre paréntesis se incluyen las traducciones a modo de referencia. Copie y pegue los valores que figuran en inglés y, luego, cambie el idioma de su Trailhead Playground a inglés y la configuración local a Estados Unidos. Siga las instrucciones que figuran aquí.

Consulte la insignia Trailhead en su idioma para aprender a aprovechar la experiencia traducida de Trailhead.

Utilizamos SOQL para consultar una organización de Salesforce y utilizar sus datos con nuestro código. En este paso, utilizamos SOQL para obtener información sobre el producto que queremos agregar como orderItem de regalo.

Un icono que representa el objeto Orders (Pedidos) de Salesforce con una flecha con la etiqueta SOQL que apunta a una tabla de datos que coinciden con su consulta.

Cómo agregar SOQL para obtener datos de Salesforce

  1. En su clase, bajo el título //TO DO 3.1 (cerca de la línea 7), pegue este código:
    // Use SOQL to get the ID of the bonus bouquet and store it in an sObject variable called bonusProduct
    List<Product2> bonusProductList = [SELECT Id, ProductCode FROM Product2 WHERE ProductCode = 'BOT-BB-12'];
    Product2 bonusProduct = new Product2();
    if(bonusProductList.size() > 0) {
        bonusProduct = bonusProductList[0];
      
        // Use SOQL to get the price book entry ID associated with the bonusProduct and store it in an sObject variable called entry
        // Every Product has an assosiated PricebookEntry
        List<PricebookEntry> entryList = [SELECT Id, Product2Id FROM PricebookEntry WHERE Product2Id = :bonusProduct.Id];
        PricebookEntry entry = new PricebookEntry();
        if(entryList.size() > 0) {
            entry = entryList[0];
        }

¿Qué es lo que hacemos aquí?

En primer lugar, utilizamos SOQL para obtener el ID y el ProductCode del producto ramo que tiene el código de producto BOT-BB-12, y almacenamos el ID en una lista llamada bonusProductList. A continuación, comprobamos la cantidad de elementos de bonusProductList. Si hay al menos un valor en la lista, definimos un nuevo sObject Product2, llamado bonusProduct y le asignamos el primer sObject de la lista bonusProductList.

Nota

La numeración de los elementos de una lista siempre empieza por 0, por lo que bonusProductList[0] hace referencia al primer elemento de la lista.

Luego, utilizamos otra consulta SOQL para obtener el Id. de PricebookEntry para bonusProduct. Almacenamos el ID de PricebookEntry en una lista de PricebookEntry llamada entryList.

Por último, comprobamos la cantidad de elementos de entryList. Si hay al menos un valor en la lista, definimos un nuevo sObject de PricebookEntry, llamado entry y le asignamos el primer sObject de la lista entryList.

Usar DML para enviar datos a Salesforce

Si completó el módulo Programación orientada a objetos para administradores, recordará que DML es el lenguaje de manipulación de datos que utilizamos para enviar datos a una organización de Salesforce. Como administrador, conoce DML como las declaraciones Insert (crear un registro), Update (modificar un registro) y Delete (borrar un registro) que utiliza con las herramientas de manipulación de datos, como el cargador de datos.

Creamos uno o varios ramos gratuitos y los agregamos a una lista. Pero solo existen en código Apex. No guardamos nada en la organización de Salesforce. Para eso utilizamos DML.

Un ramo de flores etiquetado OrderItem sObject con una flecha con la etiqueta DML que apunta a un icono OrderItem dentro de una nube con la etiqueta Record saved in Salesforce OrderItem object (Registro guardado en el objeto OrderItem de Salesforce).

  1. En su clase, bajo el título //TO DO 3.2 (cerca de la línea 50), pegue este código:
    insert newBouquets;
  2. Bajo el título //TO DO 2.4 (cerca de la línea 34), elimine los caracteres de comentario (//) de la siguiente línea: //PricebookEntryId = entry.id,
  3. Por último, tenemos que terminar la declaración if (el código que se ejecuta si determinamos que tenemos un ramo de regalo).

    En su clase, bajo el título //TO DO 3.3 (cerca de la línea 53), pegue este código:

    } //end if
  4. Guarde la clase.

Ahora la clase debe tener este aspecto:

//Create the class
  public class OrderItemUtility {
  
      //Create the method that will add free bonus bouquet when order is activated
      public static void addBonusBouquet(List<Order> ordersFromTrigger) {
      
          //TO DO 3.1: Determine if we have a bonus product and get its ID to add to the order
          // Use SOQL to get the ID of the bonus bouquet and store it in an sObject variable called bonusProduct
          List<Product2> bonusProductList = [SELECT Id, ProductCode FROM Product2 WHERE ProductCode = 'BOT-BB-12'];
          Product2 bonusProduct = new Product2();
          if(bonusProductList.size() > 0) {
              bonusProduct = bonusProductList[0];
  
              // Use SOQL to get the price book entry ID associated with the bonusProduct and store it in an sObject variable called entry
              // Every Product has an assosiated PricebookEntry
              List<PricebookEntry> entryList = [SELECT Id, Product2Id FROM PricebookEntry WHERE Product2Id = :bonusProduct.Id];
              PricebookEntry entry = new PricebookEntry();
              if(entryList.size() > 0) {
                  entry = entryList[0];
              }
      
              //TO DO 2.1: Create a list to store any new bouquets we'll insert later
              List<OrderItem> newBouquets = new List<OrderItem>();
          
              //TO DO 2.2: Loop over orders in ordersFromTrigger, for each order (called currentOrder) do something
              for(Order currentOrder : ordersFromTrigger) {
              
                  //TO DO 2.3: Verify the order status is 'Activated'
                  if(currentOrder.Status == 'Activated') {
                  
                      //TO DO 2.4: Create a new bouquet and set values
                      OrderItem freeBouquet = new OrderItem(
                          OrderId = currentOrder.id, //this is the order we're linking the bouquet to
                          PricebookEntryId = entry.id,
                          numberOfFlowers__c = 3,
                          description = 'FREE Bouquet',
                          Quantity = 1,
                          colorTheme__c = 'Spectacular Sunset',
                          percentOfOpening__c = 0,
                          UnitPrice = 0.00
                      );
                      
                      //TO DO 2.5: Add the freeBouquet sObject to your list
                      newBouquets.add(freeBouquet);
                      
                  //TO DO 2.6: Close the "if" and "for loop" sections
                  } //end if
              } //end for loop
              
              //TO DO 3.2: Use DML to add the new bouquet to the Order
              insert newBouquets;
              
          //TO DO 3.3: Close the if section
          } //end if
      } //end method
  } //end class
¡Siga aprendiendo gratis!
Regístrese para obtener una cuenta y continuar.
¿Qué hay para usted?
  • Consiga recomendaciones personalizadas para sus objetivos profesionales
  • Practique sus aptitudes con retos prácticos y pruebas
  • Siga y comparta su progreso con empleadores
  • Póngase en contacto para recibir asesoramiento y oportunidades laborales