• Swetha S415
  • NEWBIE
  • 30 Points
  • Member since 2018

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 4
    Questions
  • 4
    Replies
Hello Everyone,
Struggling with step 8 in Advanced apex specialist since a week. Could you please help me out what was the issue and fix that.

Product2Extension:

Public without sharing class Product2Extension {
   
    public List<productWrapper> productsToInsert {get;set;}
    public Product2Extension(ApexPages.StandardController controller){
        productsToInsert = new List<productWrapper>();         
        AddRows();  
    }
    //Get select list options//    
    public List<SelectOption> GetFamilyOptions() {
        List<SelectOption> options = new List<SelectOption>{new SelectOption(Constants.SELECT_ONE, Constants.SELECT_ONE)};
                    for (Schema.PicklistEntry ple : Constants.PRODUCT_FAMILY) {
                        options.add(new SelectOption(ple.getValue(), ple.getLabel()));
                    }
        return options;
    }
    public void AddRows(){
        for ( Integer i=0; i<Constants.DEFAULT_ROWS; i++ ){
            productsToInsert.add( new ProductWrapper() );
        }
    }
   
    public List<ChartHelper.ChartData> GetInventory(){
        return ChartHelper.GetInventory();
    }
   
    public PageReference Save(){
        Savepoint sp = Database.setSavepoint();
        try {
            List<Product2> products = new List<Product2>();
            List<PricebookEntry> entries = new List<PricebookEntry>();
            for (ProductWrapper wrp : productsToInsert){
                if(null!=wrp.productRecord && null!=wrp.pricebookEntryRecord){
                    if(null!=wrp.productRecord.Name && null!=wrp.productRecord.Family && constants.SELECT_ONE!=wrp.productRecord.Family
                       && null!=wrp.productRecord.Initial_Inventory__c && null!=wrp.pricebookEntryRecord.UnitPrice){
                           products.add(wrp.productRecord);
                           PricebookEntry entry=wrp.pricebookEntryRecord;
                           entry.IsActive=true;
                           system.debug('=======454545===='+constants.STANDARD_PRICEBOOK_ID);
                           entry.Pricebook2Id=constants.STANDARD_PRICEBOOK_ID;
                           entries.add(entry);  
                       }
                }
            }
            insert products;           
            for (integer itr=0; itr<entries.size();itr++){
                entries[itr].Product2Id=products[itr].id;
            }
            Database.SaveResult[] srList = Database.insert(entries, false);
            system.debug('============='+srList);
            //insert entries;
            //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){
            Database.rollback(sp);
           
            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);
        }
    }
}

ProductWrapper:

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);
        }
    }

Product2Helper:
public class Product2Helper {
    /**
* @name COLLABORATION_GROUP
* @description List of CollaborationGroup used in both business and test logic
**/
    static List<CollaborationGroup> COLLABORATION_GROUP = [
        SELECT Id
        FROM CollaborationGroup
        WHERE Name = :Constants.INVENTORY_ANNOUNCEMENTS
        OR Name = :('TEST '+Constants.INVENTORY_ANNOUNCEMENTS)
        LIMIT 1
    ];   
    /**
* @name afterUpdate
* @description called by product2 Trigger on After Update
* @param List<Product2> newList
* @param List<Product2> oldList
**/
    public static void AfterUpdate(List<Product2> oldList, List<Product2> newList){
        //ToDo: Declare a List of Product2 records named needsAnnouncement
        List<Product2> needsAnnouncement = new List<Product2>();
        //ToDo: Declare a Map of Strings to Inventory_Setting__mdt records
        Map<String, Decimal> invSettingsMap = new Map<String, Decimal>();
        //ToDo: Loop through a query of Inventory_Setting__mdt records and populate the Map with Name as the key
        List<Inventory_Setting__mdt> invSettings = [SELECT Id, DeveloperName, Low_Quantity_Alert__c FROM Inventory_Setting__mdt];
        for (Inventory_Setting__mdt sett : invSettings) {
            invSettingsMap.put(sett.DeveloperName, sett.Low_Quantity_Alert__c);
        }
        //ToDo: Loop through the Products in newList
        // Use the corresponding Inventory Setting record to determine the correct Low Quantity Alert
        // If the Product's Quantity Remaining has been changed to less than the Low Quantity Alert
        //      add it to the needsAnnouncement list
        for (Product2 prod : newList) {
            if (invSettingsMap.containsKey(prod.Family) && prod.Quantity_Remaining__c < invSettingsMap.get(prod.Family)) {
                needsAnnouncement.add(prod);
            }
        }
        //ToDo: Pass records to the postAlerts method
        PostAlerts(needsAnnouncement);
    }
   
    /**
* @name postAlerts
* @description called by product2 Trigger on After Update
* @param List<Product2> productList
**/
    public static void PostAlerts(List<Product2> productList){
        List<ConnectApi.AnnouncementInput> toPost = new List<ConnectApi.AnnouncementInput>();
        for ( Product2 p : productList ){
            // ToDo: Construct a new AnnouncementInput for the Chatter Group so that it:
            // expires in a day
            // does not notify users via email.
            // and has a text body that includes the name of the product followed by the INVENTORY_LEVEL_LOW constant
            ConnectApi.MessageBodyInput mbi = new ConnectApi.MessageBodyInput();
            ConnectApi.TextSegmentInput textSegmentInput = new ConnectApi.TextSegmentInput();
            mbi.messageSegments = new List<ConnectApi.MessageSegmentInput>();
            textSegmentInput.text = p.Name + ' ' +Constants.INVENTORY_LEVEL_LOW;
            mbi.messageSegments.add(textSegmentInput);
            ConnectApi.AnnouncementInput ai = new ConnectApi.AnnouncementInput();
            ai.expirationDate = Date.today().addDays(1);
            ai.sendEmails = true;
            ai.parentId = COLLABORATION_GROUP[0].Id;
            ai.body = mbi;
            toPost.add(ai);
        }
        // ToDo: Create and enqueue an instance of the announcementQueuable class with the list of Products
        AnnouncementQueueable q = new AnnouncementQueueable(toPost);
        // q.toPost = toPost;
        System.enqueueJob(q);
    }
}

OrderHelper:

public without sharing class OrderHelper {
    /**
* @name AfterUpdate
* @description
* @param List<Order> newList
* @param List<Order> oldList
* @return void
**/
    public static List<Double> check =new List<Double>();
    public Static List<Product2> pr;
    public static void AfterUpdate(List<Order> newList, List<Order> oldList){
        Set<Id> orderIds = new Set<Id>();
        for ( Integer i=0; i<newList.size(); i++ ){
            if ( newList[i].Status == Constants.ACTIVATED_ORDER_STATUS && oldList[i].Status == Constants.DRAFT_ORDER_STATUS ){
                orderIds.add(newList[i].Id);
            }
        }
        RollUpOrderItems(orderIds);
    }
    /**
* @name RollUpOrderItems
* @description Given a set of Activated Order ids, query the child Order Items and related Products to calculate Inventory levels
* @param Set<Id> activatedOrderIds
* @return void
**/
    public static void RollUpOrderItems(Set<Id> activatedOrderIds){
        //ToDo: Declare a Map named "productMap" of Ids to Product2 records
        Map<ID,Product2> productMap =new Map<ID,Product2>();
        List<OrderItem> orderId =[Select OrderID,Product2Id from OrderItem where OrderId IN: activatedOrderIds];
        //ToDo: Loop through a query of OrderItems related to the activatedOrderIds
        for(OrderItem o: orderId){
            //ToDo: Populate the map with the Id of the related Product2 as the key and Product2 record as the value
            Product2 p= [select name,Quantity_Ordered__c from Product2 where Id=: o.Product2Id];
            productmap.put(o.Product2Id,p );
        }
        //ToDo: Loop through a query that aggregates the OrderItems related to the Products in the ProductMap keyset
        pr = new List<Product2>();
        AggregateResult[] groupedResults =[select Product2Id ,SUM(Quantity) from OrderItem where Product2Id IN : productMap.keySet() group by Product2Id];
        for(AggregateResult ag: groupedResults){
            Product2 p= productmap.get((Id)ag.get('Product2Id'));
            p.Quantity_Ordered__c =(Double)ag.get('expr0');
            pr.add(p);
            check.add((Double)ag.get('expr0'));
        }
        update pr;
        //ToDo: Perform an update on the records in the productMap
    }
}

Constants:

public class Constants {
    public static final Integer DEFAULT_ROWS = 5;
    public static final String SELECT_ONE = Label.Select_One;
    public static final String INVENTORY_LEVEL_LOW = Label.Inventory_Level_Low;
    public static final List<Schema.PicklistEntry> PRODUCT_FAMILY;
       static {
        Schema.DescribeFieldResult fieldResult = Product2.Family.getDescribe();
        PRODUCT_FAMILY = fieldResult.getPicklistValues();
    }
    public static final String DRAFT_ORDER_STATUS = 'Draft';
    public static final String ACTIVATED_ORDER_STATUS = 'Activated';
    public static final String INVENTORY_ANNOUNCEMENTS = 'Inventory Announcements';
    public static final String ERROR_MESSAGE = 'An error has occurred, please take a screenshot with the URL and send it to IT.';
    public static final Id STANDARD_PRICEBOOK_ID = '01sf4000007hhtPAAQ';
 }



Please help me out to achieve this Badge.
User-added image
Hi Developers,

Need a help to achieve below functionality. 
how to write a validation rule such that it should not allow any special characters(!@#$%^&*) and not allow all zeros in a field. (eg: 0 or 00 or 000 or 0000). 

I have used the below validation rule that is restricting special characters but allowing all zeros. 
NOT(REGEX(Phone__c,"^[a-zA-Z0-9]*$"))

Hello,
how to write a custom validation rule such that it prevents special character and spaces, it should allow only alphanumeric characters. But it should not affect any old records until unless user edits that field.

Example:
Not be allowed.
1.Student*&&^
2.Stud ent   
 
Allowed:
1. Student5654

Hi All,
Could you please help me out how to achieve the below scenario using maps concept.
Scenario :
Having 4 object ===> Accounts, Contacts, opportunity and Quotes.
Accounts will have lookup to only Contact.
Contact will have lookup to only Opportunity.
Opportunity will have lookup to only Quote.

Create a visualforce page such that while on account search related contacts records should be displayed, if Contacts has opportunity records then those records to get displayed if it has none records nothing to get displayed. Similarly for opportunity has quote record those to be displayed.

Can anyone achieve this functionality by using Maps Concept? 
 
Hello Everyone,
Struggling with step 8 in Advanced apex specialist since a week. Could you please help me out what was the issue and fix that.

Product2Extension:

Public without sharing class Product2Extension {
   
    public List<productWrapper> productsToInsert {get;set;}
    public Product2Extension(ApexPages.StandardController controller){
        productsToInsert = new List<productWrapper>();         
        AddRows();  
    }
    //Get select list options//    
    public List<SelectOption> GetFamilyOptions() {
        List<SelectOption> options = new List<SelectOption>{new SelectOption(Constants.SELECT_ONE, Constants.SELECT_ONE)};
                    for (Schema.PicklistEntry ple : Constants.PRODUCT_FAMILY) {
                        options.add(new SelectOption(ple.getValue(), ple.getLabel()));
                    }
        return options;
    }
    public void AddRows(){
        for ( Integer i=0; i<Constants.DEFAULT_ROWS; i++ ){
            productsToInsert.add( new ProductWrapper() );
        }
    }
   
    public List<ChartHelper.ChartData> GetInventory(){
        return ChartHelper.GetInventory();
    }
   
    public PageReference Save(){
        Savepoint sp = Database.setSavepoint();
        try {
            List<Product2> products = new List<Product2>();
            List<PricebookEntry> entries = new List<PricebookEntry>();
            for (ProductWrapper wrp : productsToInsert){
                if(null!=wrp.productRecord && null!=wrp.pricebookEntryRecord){
                    if(null!=wrp.productRecord.Name && null!=wrp.productRecord.Family && constants.SELECT_ONE!=wrp.productRecord.Family
                       && null!=wrp.productRecord.Initial_Inventory__c && null!=wrp.pricebookEntryRecord.UnitPrice){
                           products.add(wrp.productRecord);
                           PricebookEntry entry=wrp.pricebookEntryRecord;
                           entry.IsActive=true;
                           system.debug('=======454545===='+constants.STANDARD_PRICEBOOK_ID);
                           entry.Pricebook2Id=constants.STANDARD_PRICEBOOK_ID;
                           entries.add(entry);  
                       }
                }
            }
            insert products;           
            for (integer itr=0; itr<entries.size();itr++){
                entries[itr].Product2Id=products[itr].id;
            }
            Database.SaveResult[] srList = Database.insert(entries, false);
            system.debug('============='+srList);
            //insert entries;
            //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){
            Database.rollback(sp);
           
            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);
        }
    }
}

ProductWrapper:

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);
        }
    }

Product2Helper:
public class Product2Helper {
    /**
* @name COLLABORATION_GROUP
* @description List of CollaborationGroup used in both business and test logic
**/
    static List<CollaborationGroup> COLLABORATION_GROUP = [
        SELECT Id
        FROM CollaborationGroup
        WHERE Name = :Constants.INVENTORY_ANNOUNCEMENTS
        OR Name = :('TEST '+Constants.INVENTORY_ANNOUNCEMENTS)
        LIMIT 1
    ];   
    /**
* @name afterUpdate
* @description called by product2 Trigger on After Update
* @param List<Product2> newList
* @param List<Product2> oldList
**/
    public static void AfterUpdate(List<Product2> oldList, List<Product2> newList){
        //ToDo: Declare a List of Product2 records named needsAnnouncement
        List<Product2> needsAnnouncement = new List<Product2>();
        //ToDo: Declare a Map of Strings to Inventory_Setting__mdt records
        Map<String, Decimal> invSettingsMap = new Map<String, Decimal>();
        //ToDo: Loop through a query of Inventory_Setting__mdt records and populate the Map with Name as the key
        List<Inventory_Setting__mdt> invSettings = [SELECT Id, DeveloperName, Low_Quantity_Alert__c FROM Inventory_Setting__mdt];
        for (Inventory_Setting__mdt sett : invSettings) {
            invSettingsMap.put(sett.DeveloperName, sett.Low_Quantity_Alert__c);
        }
        //ToDo: Loop through the Products in newList
        // Use the corresponding Inventory Setting record to determine the correct Low Quantity Alert
        // If the Product's Quantity Remaining has been changed to less than the Low Quantity Alert
        //      add it to the needsAnnouncement list
        for (Product2 prod : newList) {
            if (invSettingsMap.containsKey(prod.Family) && prod.Quantity_Remaining__c < invSettingsMap.get(prod.Family)) {
                needsAnnouncement.add(prod);
            }
        }
        //ToDo: Pass records to the postAlerts method
        PostAlerts(needsAnnouncement);
    }
   
    /**
* @name postAlerts
* @description called by product2 Trigger on After Update
* @param List<Product2> productList
**/
    public static void PostAlerts(List<Product2> productList){
        List<ConnectApi.AnnouncementInput> toPost = new List<ConnectApi.AnnouncementInput>();
        for ( Product2 p : productList ){
            // ToDo: Construct a new AnnouncementInput for the Chatter Group so that it:
            // expires in a day
            // does not notify users via email.
            // and has a text body that includes the name of the product followed by the INVENTORY_LEVEL_LOW constant
            ConnectApi.MessageBodyInput mbi = new ConnectApi.MessageBodyInput();
            ConnectApi.TextSegmentInput textSegmentInput = new ConnectApi.TextSegmentInput();
            mbi.messageSegments = new List<ConnectApi.MessageSegmentInput>();
            textSegmentInput.text = p.Name + ' ' +Constants.INVENTORY_LEVEL_LOW;
            mbi.messageSegments.add(textSegmentInput);
            ConnectApi.AnnouncementInput ai = new ConnectApi.AnnouncementInput();
            ai.expirationDate = Date.today().addDays(1);
            ai.sendEmails = true;
            ai.parentId = COLLABORATION_GROUP[0].Id;
            ai.body = mbi;
            toPost.add(ai);
        }
        // ToDo: Create and enqueue an instance of the announcementQueuable class with the list of Products
        AnnouncementQueueable q = new AnnouncementQueueable(toPost);
        // q.toPost = toPost;
        System.enqueueJob(q);
    }
}

OrderHelper:

public without sharing class OrderHelper {
    /**
* @name AfterUpdate
* @description
* @param List<Order> newList
* @param List<Order> oldList
* @return void
**/
    public static List<Double> check =new List<Double>();
    public Static List<Product2> pr;
    public static void AfterUpdate(List<Order> newList, List<Order> oldList){
        Set<Id> orderIds = new Set<Id>();
        for ( Integer i=0; i<newList.size(); i++ ){
            if ( newList[i].Status == Constants.ACTIVATED_ORDER_STATUS && oldList[i].Status == Constants.DRAFT_ORDER_STATUS ){
                orderIds.add(newList[i].Id);
            }
        }
        RollUpOrderItems(orderIds);
    }
    /**
* @name RollUpOrderItems
* @description Given a set of Activated Order ids, query the child Order Items and related Products to calculate Inventory levels
* @param Set<Id> activatedOrderIds
* @return void
**/
    public static void RollUpOrderItems(Set<Id> activatedOrderIds){
        //ToDo: Declare a Map named "productMap" of Ids to Product2 records
        Map<ID,Product2> productMap =new Map<ID,Product2>();
        List<OrderItem> orderId =[Select OrderID,Product2Id from OrderItem where OrderId IN: activatedOrderIds];
        //ToDo: Loop through a query of OrderItems related to the activatedOrderIds
        for(OrderItem o: orderId){
            //ToDo: Populate the map with the Id of the related Product2 as the key and Product2 record as the value
            Product2 p= [select name,Quantity_Ordered__c from Product2 where Id=: o.Product2Id];
            productmap.put(o.Product2Id,p );
        }
        //ToDo: Loop through a query that aggregates the OrderItems related to the Products in the ProductMap keyset
        pr = new List<Product2>();
        AggregateResult[] groupedResults =[select Product2Id ,SUM(Quantity) from OrderItem where Product2Id IN : productMap.keySet() group by Product2Id];
        for(AggregateResult ag: groupedResults){
            Product2 p= productmap.get((Id)ag.get('Product2Id'));
            p.Quantity_Ordered__c =(Double)ag.get('expr0');
            pr.add(p);
            check.add((Double)ag.get('expr0'));
        }
        update pr;
        //ToDo: Perform an update on the records in the productMap
    }
}

Constants:

public class Constants {
    public static final Integer DEFAULT_ROWS = 5;
    public static final String SELECT_ONE = Label.Select_One;
    public static final String INVENTORY_LEVEL_LOW = Label.Inventory_Level_Low;
    public static final List<Schema.PicklistEntry> PRODUCT_FAMILY;
       static {
        Schema.DescribeFieldResult fieldResult = Product2.Family.getDescribe();
        PRODUCT_FAMILY = fieldResult.getPicklistValues();
    }
    public static final String DRAFT_ORDER_STATUS = 'Draft';
    public static final String ACTIVATED_ORDER_STATUS = 'Activated';
    public static final String INVENTORY_ANNOUNCEMENTS = 'Inventory Announcements';
    public static final String ERROR_MESSAGE = 'An error has occurred, please take a screenshot with the URL and send it to IT.';
    public static final Id STANDARD_PRICEBOOK_ID = '01sf4000007hhtPAAQ';
 }



Please help me out to achieve this Badge.
User-added image
Hi Developers,

Need a help to achieve below functionality. 
how to write a validation rule such that it should not allow any special characters(!@#$%^&*) and not allow all zeros in a field. (eg: 0 or 00 or 000 or 0000). 

I have used the below validation rule that is restricting special characters but allowing all zeros. 
NOT(REGEX(Phone__c,"^[a-zA-Z0-9]*$"))