Crear la automatización para ejecutar la promoción del ramo gratuito
En este paso, creamos una clase y un método nuevos, en los que comprobamos el estado de todos los pedidos. Si se activa un pedido, agregamos automáticamente un ramo de regalo al pedido.
Cuando vea el código, recuerde que cualquier texto que empieza con // es un comentario de código. En el código, los comentarios describen el propósito de un bloque de código (una o más líneas de código). Los comentarios ayudan a los desarrolladores a entender el código que deben escribir, la función del código existente y lo que debería hacer el código que presenta errores.
Cómo crear una clase y un método
- Haga clic en
y seleccione Setup (Configuración).
- En el cuadro de búsqueda rápida, busque y seleccione Web Console (Consola web).
- En Enable Developer Console (Habilitar Consola de desarrollador), configúrela como Active (Activa).
- Actualice la página.
- Haga clic en
y seleccione Developer Console.
- Haga clic en File (Archivo) | New (Nuevo) | Apex Class (Clase de Apex).
- Asigne el nombre
OrderItemUtilitya la clase y haga clic en OK (Aceptar).
- Sustituya el código existente por este código:
//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 //TO DO 2.1: Create a list to store any new bouquets we'll insert later //TO DO 2.2: Loop over orders in ordersFromTrigger, for each order (called currentOrder) do something //TO DO 2.3: Verify the order status is 'Activated' //TO DO 2.4: Create a new bouquet and set values //TO DO 2.5: Add the freeBouquet sObject to your list //TO DO 2.6: Close the "if" and "for loop" sections //TO DO 3.2: Use DML to add the new list of newBouquets //TO DO 3.3: Close the if section } //end method } //end class - Haga clic en File (Archivo) | Save (Guardar) para guardar la clase.
Cómo agregar una automatización para crear un ramo nuevo
A continuación, agregamos una automatización a la clase. Una vez que pegue las líneas de código adicionales, observará que se agregó un comentario de código, //, a la línea en blanco. No olvide eliminar el comentario adicional antes de pegar el código.
- Cree una lista para almacenar ramos de regalo nuevos.
En su clase, bajo el comentario//TO DO 2.1, pegue este código:List<OrderItem> newBouquets = new List<OrderItem>();
- Utilice un bucle
forpara iterar a través de los pedidos enviados desde un desencadenador. (Crearemos ese desencadenador más adelante).
En su clase, bajo el comentario//TO DO 2.2, pegue este código:for(Order currentOrder : ordersFromTrigger) {
This is the first part of the for loop. It takes all the orders from the trigger and adds them to theordersFromTriggerlist. The for loop evaluates each order and names the ordercurrentOrder.
- A continuación, observamos cada pedido (mediante la variable
currentOrderque creamos) y preguntamos lo siguiente: ¿Está activado el pedido? Si la respuesta es afirmativa, hacemos algo. Si no lo es, pasamos al siguiente pedido y hacemos la misma pregunta.
En su clase, bajo el comentario//TO DO 2.3, pegue este código:if(currentOrder.Status == 'Activated') {
Como observó en el código del buclefor, solo hay una llave. Agregaremos la otra después de terminar todo lo que queremos hacer a cada pedido activado.
Cuando encontramos un pedido que efectivamente está activado, creamos un sObject para un nuevoOrderItem.
En su clase, bajo el comentario//TO DO 2.4, pegue este código:
-
Aquí creamos el sObject de OrderItem, llamado
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 );freeBouquet, y luego asignamos valores a sus campos.
A continuación, agregamos el sObject a la lista que creamos en//TO DO 2.1.
En su clase, bajo el comentario//TO DO 2.5, pegue este código:
-
newBouquets.add(freeBouquet);
We're using theaddmethod that's built into Apex, making it easy to add an item to a list.
In this statement,newBouquetsis the name of the list, add is the method, andfreeBouquet(in parentheses) is the sObject that is added to thenewBouquetslist.
- Finally, we need to end the
ifstatement (the code that runs only for activated orders) and theforloop (the code that runs for each order as the loop cycles through all activated orders).
In your class, under the comment//TO DO 2.6, paste this code:Ahora el archivo de la clase debe tener este aspecto:} //end if } //end for loop
//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 //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 //TO DO 3.3: Close the if section } //end method } //end class - Haga clic en File (Archivo) | Save (Guardar) para guardar la clase
OrderItemUtility.
En la próxima unidad, aprenderá a obtener datos de Salesforce y a enviarlos a Salesforce, y creará un desencadenador. Luego comienza la diversión: probar su código.
