Superbadge – Advanced Apex Specialist

Superbadge – Advanced Apex Specialist

Demonstrate your advanced Apex and Visualforce programming skills and implement complex business logic.

Step 1 – Update the codebase to use best practices

Delete the Apex class named PackageTests.Create new labels, constants, a new custom metadata type, and new custom metadata records.
  • Create new salesforce playground and Install this unmanaged Superbadge package.
  • Update the Product Family (PickList) field on the Product2 object with the following values only
    •  Entree
    • Side
    • Dessert
    • Beverage

Product Family Picklist Values

  • Update the product2 page layout to include the following fields
    • Initial Inventory – Initial_Inventory__c
    • Quantity Ordered – Quantity_Ordered__c
    • Quantity Remaining fields – Quantity_Remaining__c

Updated Product 2 Page Layout

  • Update the Account page layout to display the Orders related list.
  • Remove the Contract Number field from the Order page layout
  • Delete the Apex class named PackageTests.
  • Create two custom labels
    • Select One
    • Inventory Level Low

Create Two Custom Label

  • Create an Apex class named Constants. apxc with the mentioned attributes. All properties should be declared as static and final since it should be defined as constant.

Constants Class

  • Create Custom Metadata Type named Inventory Setting and insert the mentioned records.
    • Object Name – Inventory_Setting
    • API Name – Inventory_Setting__mdt

Custom Metadata Types.JPG

AAS Challenge 1 Completed.JPG

Step 2 – Update the order trigger

Correct the business logic that calculates inventory levels, and ensure the associated code is lean and efficient. Modify OrderTrigger to use best practices and to execute only upon the relevant and necessary trigger events. Update the code in OrderHelper.

  • Modify OrderTrigger for handling only after Update
  • Remove all the unnecessary code from the OrderTrigger and Call the AfterUpdate method in OrderHelper which takes and Trigger.old as input parameters
  • Extract all Order Ids by iterating the list, whose old status (fetch status from Trigger.old list )is Constants.DRAFT_ORDER_STATUS and new status after update ( fetch status from ) is Constants. ACTIVATED_ORDER_STATUS. Invoke RollUpOrderItems in OrderHelper by Passing filtered Ids.
  • In RollUpOrderItems method,
    • Declare a Map<Id,Product2> named productMap 
    • Create a List named productIds to store the product Ids which are included in the Orders (Order Ids passed as the method argument).
    • Select Id, Quantity_Ordered__c from Product2 based on the productIds list filter. Pass the Id and Product2 object into the productMap declared earlier
    • productMap = new Map<Id,Product2>([Select id,Quantity_Ordered__c from product2 where id in :productIds]);

    • Loop through a query that aggregates the OrderItems related to the Products in the productMap keyset
    • <AggregateResult[] groupedResult = [Select Product2Id,sum(Quantity) totalQuantity from OrderItem where product2Id in :productMap.keySet() group by product2Id];

    • for(AggregateResult result : groupedResult) {productMap.get((String)result.get(‘Product2Id’)).Quantity_Ordered__c = Integer.valueOf(result.get(‘totalQuantity’));}

    • Finally, update the productMap.values()

AAS Challenge 2 Completed.JPG

Step 3 – Update the new product Visualforce page

Update the Product2New Visualforce page and Product2Extension class to meet the business requirements.

  • Add standardController attribute in the ProductNew2 Visualforce Page
  • Override the Add and New Button with the ProductNew2 Page
  • Replace the column header with referred the field label, Use the following syntax to get the field label
    • $ObjectType.Product2.Fields.Name.Label

  • In Product2Extension, Create an inner class named ProductWrapper which includes the attributes,
    • productRecord of Product2 
    • pricebookEntryRecord of PriceBookEntry
    • Create a constructor to instantiate the class attributes
  • Replace the productsToInsert attribute type in all references with List  
  • Replace the value parameter of inputField and inputText  in ProductNew2 VF page, refer the below 
  • Replace the loop iteration limit with Constants.DEFAULT_ROWS in the addRows method
  • Create a new method GetFamilyOptions 
    • create a list of SelectOption
    • add Constants.SELECT_ONE into the list
    • Iterate the Constants.PRODUCT_FAMILY and add to the SelectOption list
      • use getLabel and getValue methods of Schema.PicklistEntry
    • set the SelectOption List to product family (apex:selectList in ProductNew2 VF page )
  • In save() method,
    • Create SavePoint before trycatch
    • extract all valid entries of product and pricebookentry record from productsToInsert List
    • Insert the products
    • Using the product Ids, insert the corresponding price book entries
      • set the isActive to true
      • Pricebook2Id with Constants.STANDARD_PRICEBOOK_ID
  • Add horizontal bar chart with necessary rerender options
    • Add @AuraEnabled annotation to the GetInventory method
    • Chart data initialisation logic to Chart Helper class
    • Update ChartHelper class to without sharing

AAS Challenge 3 Completed.JPG

Step 4 -Create the Test Data Factory

Complete the TestDataFactory Apex class, whose methods produce sample data for your unit tests. The methods should not be instance methods.

  • Update all methods to public static
  • Mark the class to with sharing
  • InsertTestData method invoke all the above construct method (with dependent parameters) and insert it

Step 5 -Increase test coverage with unit tests

Create the new VerifyQuantityOrdered method in TestDataFactory according to its signature. Update OrderTests to verify OrderTrigger and OrderHelper logic. Complete the Product2Extension_UnitTest in Product2Tests.

  • Add a new method VerifyQuantityOrdered with the mentioned signature in TestDataFactory.
    •  System.assertEquals((updatedProduct.Quantity_Ordered__c – originalProduct.Quantity_Ordered__c), qtyOrdered);

  • Update the seeAllData annotation value to false
  • Create a test setup method SetupTestData which invoke InsertTestData method of  TestDataFactory class
  • Create a new test method named OrderUpdate_UnitTest in OrderTests
    • Select a product before updating the order
    • Select an Order and update its status to Constants. ACTIVATED _ORDER _STATUS
    • Select the updated product
    • Pass the values into the VerifyQuantityOrdered method
  • Create or complete the Product2Extension_UnitTest in Product2Tests
    • Update the seeAllData annotation value to false
    • Create a StandardController instance of the Product2 object
    • Create a Product2Extension instance by passing StandardController as its constructor parameter
    • Check if the number of added rows equal to Constants.DEFAULT_ROWS – Use Assert Equal
    • Call the AddRows() method and do an Assert Equal once again
    • Insert few products and price book entries to productsToInsert
    • Invoke the method – Save()
    • Invoke the method – GetFamilyOptions()
    • Invoke the method – GetInventory()
    • Check if the Save action works as expected using Assert Equal

AAS Super badge Challenge 5

Step 6 -Automate internal announcements when inventory is low

AAS Super badge Challenge 6

Step 7 – Complete a Controller Extension for a Visualforce Page to Enable Rapid Order Entry

Step 8 – Complete Test class for Order Extension

  • Create a test method OrderExtension_UnitTest in OrderTests 
    • Set test page reference as OrderEdit
    • Create StandardController instance of Order
    • Create OrderExtension instance by passing StandardController as its constructor parameter
    • Assert the orderlistItem list size with Constant.DEFAULT_ROWS 
    • invoke the methods SelectFamily(), OnFieldChange(), First(), Next(), Previous(), Last(), GetHasNext(), GetPageNumber(), GetHasPrevious(), GetTotalPages(), GetFamilyOptions(), Save(), ChartHelper.GetInventory()
  • Create a new test method titled Product2Trigger_UnitTest in Product2Tests
    • insert a product2 record
    • insert CollaborationGroup record
    • update Quantity_Ordered__c field of product2 record
Advanced Apex Specialist
Advanced Apex Specialist Challenge – Accomplished

Don’t forget to share the post if you like it & bookmark the blog for future references. If you have any comments or doubts on this post, Please comment on the box.

9 thoughts on “Superbadge – Advanced Apex Specialist”

  1. Hi,

    I am Facing on issue in step 8

    Challenge Not yet complete… here’s what’s wrong:
    Ensure that product2Controller is still working as specified in the earlier challenge.

  2. Challenge Not yet complete… here’s what’s wrong:
    Ensure that you create the Select One label.
    no matter what i am not able to clear this….can you help me?

  3. Hi,

    I was unable to complete step 5: getting error assert equals fails when challenging step 5.

    Please find below error

    ” Challenge Not yet complete… here’s what’s wrong:
    Ensure that you create the OrderUpdate_UnitTest test method with the proper declaration and proper access modifier, to ensure best practices. “

    1. Hi NAGENDRA (@NPNAGENDRA25) – How did you resolve the above error. I am stuck at this past two days. Can you help me
      Ensure that you create the OrderUpdate_UnitTest test method with the proper declaration and proper access modifier, to ensure best practices. “

    2. Hi NAGENDRA (@NPNAGENDRA25) – How did you resolve the above error. I am stuck at this past two days. Can you help me
      Ensure that you create the OrderUpdate_UnitTest test method with the proper declaration and proper access modifier, to ensure best practices. “

    3. Replace:
      System.assertEquals(Constants.DEFAULT_ROWS, prodExt.productsToInsert.size());
      System.assert(prodExt.productsToInsert.size() == Constants.DEFAULT_ROWS);

      System.assertEquals(2*Constants.DEFAULT_ROWS, prodExt.productsToInsert.size());
      System.assert(prodExt.productsToInsert.size() == 2*Constants.DEFAULT_ROWS);

  4. Challenge Not yet complete… here’s what’s wrong:
    Ensure that the save method inserts only Products and Pricebooks for rows that have all fields populated.

    I’m getting this on Step 3 … any ideas?

    “public class Product2Extension {

    public List productsToInsert {get; set;}

    public Product2Extension(ApexPages.StandardController controller){
    productsToInsert = new List();

    public void AddRows(){
    for (Integer i=0; i<Constants.DEFAULT_ROWS; i++ ) {
    productsToInsert.add( new ProductWrapper() );

    public List GetInventory(){
    return ChartHelper.GetInventory();

    public List GetFamilyOptions() {
    List options = new List();
    options.add(new SelectOption(Constants.SELECT_ONE, Constants.SELECT_ONE));
    for(PickListEntry eachPicklistValue : Constants.PRODUCT_FAMILY) {
    options.add(new SelectOption(eachPicklistValue.getValue(), eachPicklistValue.getLabel()));
    return options;

    public PageReference Save(){
    Savepoint sp = Database.setSavepoint();
    try {
    List products = new List();
    List pbes = new List();

    for (ProductWrapper prodwrapper : productsToInsert) {
    if(prodwrapper.productRecord != null && prodwrapper.pricebookEntryRecord != null) {
    if(prodwrapper.productRecord.Name != null && prodwrapper.productRecord.Family != null && constants.SELECT_ONE != prodwrapper.productRecord.Family && prodwrapper.productRecord.Initial_Inventory__c != null && prodwrapper.pricebookEntryRecord.UnitPrice != null) {
    PricebookEntry pbe = prodwrapper.pricebookEntryRecord;
    pbe.IsActive = true;
    pbe.Pricebook2Id = Constants.STANDARD_PRICEBOOK_ID;

    insert products;

    for (integer i = 0; i < pbes.size(); i++) {
    pbes[i].Product2Id = products[i].Id;
    insert pbes;

    //If successful clear the list and display an informational message
    apexPages.addMessage(new ApexPages.message(ApexPages.Severity.INFO,productsToInsert.size()+' Inserted'));
    productsToInsert.clear(); //Do not remove
    AddRows(); //Do not remove
    } catch (Exception e){
    apexPages.addMessage(new ApexPages.message(ApexPages.Severity.ERROR, Constants.ERROR_MESSAGE));
    return null;

    public class ProductWrapper {
    public Product2 productRecord {get; set;}
    public PriceBookEntry pricebookEntryRecord {get; set;}

    public ProductWrapper() {
    productRecord = new product2(Initial_Inventory__c =0);
    pricebookEntryRecord = new pricebookEntry(Unitprice=0.0);

  5. Hi Nagendra

    In Step for getting error System.LimitException: Too many SOQL queries: 101 . Did all as per instruction .

  6. Hi Nagendra, I am facing error on Step 1 Update the codebase to use best practices

    Challenge Not yet complete… here’s what’s wrong:
    Ensure that you create the DEFAULT_ROWS constant and that it is an immutable property.

    I am stuck at this past three days. Can you please help me

Leave a Reply

%d bloggers like this: