• Lalit Mistry 21
  • SMARTIE
  • 893 Points
  • Member since 2016
  • Technical Lead
  • Arxxus Technology Partners Ltd.


  • Chatter
    Feed
  • 29
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 116
    Replies
Im currently writing a trigger handler to add a parent id to an account based on a variable called DUNS Number. When I add a new record I run into a DML Error 50001 limit reached.  

/******************************************************************************************************
 * @NAME         : OnBeforeInsert
 * @DESCRIPTION  : Catch any missing data before inserting a Account record
 * @PARAMETER    : List of Accounts to affect
 ******************************************************************************************************/
    public void BeforeInsert(Account[] newAccounts){
        Map<String, Id> dunsMap = getDUNSMap(newAccounts);
        try{
            FOR(Account acct : newAccounts){
                //acct.Sales_Region__c = region.getCorrectAccountRegionSingle(acct);
                if(acct.Parent_DUNS_Number__c != null){
                    acct.ParentId = dunsMap.get(acct.Parent_DUNS_Number__c);
                }
            }
        }catch(Exception ex){}
    }

 /******************************************************************************************************
 * @NAME         : getDUNSMap
 * @DESCRIPTION  : Gets the Id of the Parent Account based on the DUNS Number
 * @PARAMETER    : Account List to search for
 * @RETURN       : Map<String, Id> of the Queried Parent Account with their duns numbers
 ******************************************************************************************************/   
    private Map<String, Id> getDUNSMap(List<Account> accountList){
        Map<String, Id> dunsMap = new Map<String, Id>();
        
        List<String> parentDunsList = new List<String>();
        
        For(Account a : accountList){ 
            parentDunsList.add(a.Parent_DUNS_Number__c);
        }
        List<Account> parentList =[SELECT id, DUNS_Number__c FROM Account WHERE DUNS_Number__c In : parentDunsList];
        
        FOR(Account a1 : parentList){
            dunsMap.put(a1.DUNS_Number__c, a1.Id);
        }
        
        return dunsMap;
    }
Another list index ouf of bounds error encountered by an admin. The other posts aren't helping me. The purpose of my code is to chain Billing Schedule records together with with a self lookup based on a Date field. This will allow me to write validations to prevent certain actions until actions on the previous Billing Schedule record have been fulfilled. 

After thinking it though, I've determined that I have to use a custom sort for sobjects. I simply followed an example in salesforce docs on how to write a wrapper class that does this, and it appears to be working fine with the test class, but I'm getting a List Index out of bounds error when try it through the UI. 

I'm stuck because alll of my system.debugs look fine. For example, if my test has 8 Billing Schedule records then I get List index out of bounds:8 but the system debugs show that I'm only counting and retrieving from the list for 0 to 8. So, can anyone see how I'm going out of bounds? 
 
public class sortBillingSchedule {

    public static void populatePrevSched(String PrjId) {
        List<Billing_Schedule__c> bss = new List<Billing_Schedule__c>();
        List<BillingScheduleWrapper> bsList = new List<BillingScheduleWrapper>();
        Integer count = 0;
        
        for(Billing_Schedule__c bs : [select Id, Billing_Date__c, Previous_Billing_Schedule__c  from Billing_Schedule__c where Project__c = :PrjId]) {
            bsList.add(new BillingScheduleWrapper(bs));
        }
        bsList.sort();
        system.debug('======bsList '+bsList);
        while(count <= bsList.size()) {
           system.debug('========== count '+count+' ============ size'+bsList.size());
            If(count > 0) {
            	Billing_Schedule__c bs1 = bsList.get(count).bs;
            	bs1.Previous_Billing_Schedule__c = bsList.get(count - 1).bs.Id;
            	bss.add(bs1);
            }
            count++;
        }
        update bss;
        
    }
}

 
Hello friends
I am getting the error " INSUFFICIENT_ACCESS_OR_READONLY" when I execute apex code from trigger and the logic performs an DML operation.
I went through several posts to understand this error I understood that in the context of current user not having permission to perform edit on the object is resulting in this error.

The code was written by another user with 'WITH SHARING" keyword and also he has written as test class.
I checked with sysadmin so I do not have permissions to perform any edit on the said object.


My question is how do I resolve this error.

A) Can I actually remove the "WITH SHARING" keyword and then run the code from my login ?
B) In test class can I remove the option of 'WITHOUT SHARING"?
C) Also Pls lt me know how system.RunAs() works in the above context.
D) as of now this code is not deployed, so once it is deployed if this error occurs pls explain how to to resolve

I really hope I am clear.
Thanks
vandana R

 
Hello

I can't have trouble covering my page reference in test class
 
public class AccountInvoiceTabExtension {
    
    public ListPaginationBase ConstructionPaginationBaseObject {get; set;}
    public ListPaginationBase DeltaPaginationBaseObject {get; set;}
    public ListPaginationBase EnginePowerGenerationPaginationBaseObject {get; set;}
    public ListPaginationBase MiningPaginationBaseObject {get; set;}
    public ListPaginationBase ProductSupportPaginationBaseObject {get; set;}
    public ListPaginationBase SamsungPaginationBaseObject {get; set;}
    public ListPaginationBase OtherPaginationBaseObject {get; set;}
       
    public List<InvoiceWrapper> ConstructionInvoiceList {get; set;}
    public List<InvoiceWrapper> DeltaInvoiceList {get; set;}
    public List<InvoiceWrapper> EnginePowerGenerationInvoiceList {get; set;}
   public List<InvoiceWrapper> MiningInvoiceList {get; set;}
    public List<InvoiceWrapper> ProductSupportInvoiceList {get; set;}
    public List<InvoiceWrapper> SamsungInvoiceList {get; set;}
    public List<InvoiceWrapper> OtherInvoiceList {get; set;}
    
    public String constructionInvoiceSort {get; set;}
    public boolean constructionInvoiceSortDesc {get; set;} 
    public String DeltaInvoiceSort {get; set;}
    public boolean DeltaInvoiceSortDesc {get; set;} 
    public String EnginePowerGenerationInvoiceSort {get; set;}
    public boolean EnginePowerGenerationInvoiceSortDesc {get; set;} 
    public String MiningInvoiceSort {get; set;}
    public boolean MiningInvoiceSortDesc {get; set;} 
    public String ProductSupportInvoiceSort {get; set;}
    public boolean ProductSupportInvoiceSortDesc {get; set;} 
    public String SamsungInvoiceSort {get; set;}
    public boolean SamsungInvoiceSortDesc {get; set;}   
    public String OtherInvoiceSort {get; set;}
    public boolean OtherInvoiceSortDesc {get; set;} 
    
    public Account currentAccount {get; set;}
    
    public AccountInvoiceTabExtension(ApexPages.StandardController controller) {
        
        currentAccount = (Account) controller.getRecord();
        
        constructionInvoiceSort = 'Name';
        constructionInvoiceSortDesc = false;
        DeltaInvoiceSort = 'Name';
        DeltaInvoiceSortDesc = false;
        EnginePowerGenerationInvoiceSort = 'Name';
        EnginePowerGenerationInvoiceSortDesc = false;
        MiningInvoiceSort = 'Name';
        MiningInvoiceSortDesc = false;
        ProductSupportInvoiceSort = 'Name';
        ProductSupportInvoiceSortDesc = false;       
        SamsungInvoiceSort = 'Name';
        SamsungInvoiceSortDesc = false;
        OtherInvoiceSort = 'Name';
        OtherInvoiceSortDesc = false;
        
        refreshConstructionInvoiceList();
        refreshDeltaInvoiceList ();
        refreshEnginePowerGenerationInvoiceList();
        refreshMiningPaginationList();
        refreshProductSupportInvoiceList();
        refreshSamsungInvoiceList();
        refreshOtherInvoiceList();
    }
    
    public PageReference sortConstructionPaginationList() {
        refreshConstructionInvoiceList();
        return null;
    }
    
    public PageReference sortDeltaPaginationList() {
        refreshDeltaInvoiceList();
        return null;
    }
    
    public PageReference sortEnginePowerGenerationPaginationList() {
        refreshEnginePowerGenerationInvoiceList();
        return null;
    }
    
    public PageReference sortMiningPaginationList() {
        refreshMiningPaginationList();
        return null;
    }
    
    public PageReference sortProductSupportPaginationList() {
        refreshProductSupportInvoiceList();
        return null;
    }
    
    public PageReference sortSamsungPaginationList() {
        refreshSamsungInvoiceList();
        return null;
    }
    
    public PageReference sortOtherPaginationList() {
        refreshOtherInvoiceList();
        return null;
    }
    
    private void refreshConstructionInvoiceList() {
        getConstructionInvoiceList();
        
        constructionPaginationBaseObject = new ListPaginationBase();
        constructionPaginationBaseObject.initializePagination(ConstructionInvoiceList, 20);
    }
    
    private void refreshDeltaInvoiceList() {
        getDeltaInvoiceList();
        
        DeltaPaginationBaseObject = new ListPaginationBase();
        DeltaPaginationBaseObject.initializePagination(DeltaInvoiceList, 20);
    }
 
    private void refreshEnginePowerGenerationInvoiceList() {
        getEnginePowerGenerationInvoiceList();
        
        EnginePowerGenerationPaginationBaseObject = new ListPaginationBase();
        EnginePowerGenerationPaginationBaseObject.initializePagination(EnginePowerGenerationInvoiceList, 20);
    }
   
    private void refreshMiningPaginationList() {
        getMiningInvoiceList();
        
        MiningPaginationBaseObject = new ListPaginationBase();
        MiningPaginationBaseObject.initializePagination(MiningInvoiceList, 20);
    }
    
    private void refreshProductSupportInvoiceList() {
        getProductSupportInvoiceList ();
        
        ProductSupportPaginationBaseObject = new ListPaginationBase();
        ProductSupportPaginationBaseObject.initializePagination(ProductSupportInvoiceList, 20);
    }
    
    private void refreshSamsungInvoiceList() {
        getSamsungInvoiceList();
        
        SamsungPaginationBaseObject = new ListPaginationBase();
        SamsungPaginationBaseObject.initializePagination(SamsungInvoiceList, 20);
    }
    
    private void refreshOtherInvoiceList() {
        getOtherInvoiceList();
        
        OtherPaginationBaseObject = new ListPaginationBase();
        OtherPaginationBaseObject.initializePagination(OtherInvoiceList, 20);
    }
    
    public class InvoiceWrapper {
        public Id InvoiceId {get; set;}
        public String orderNumber {get; set;}
        public Date InvoiceDate {get; set;}
        public String OrderType {get; set;}
        public String  ModelDescription {get; set;}
        public String InvoiceType {get; set;}
        public String OrderTaking {get; set;}
        public double TotalSellVAT {get; set;}
        public String CostCenter {get; set;}
        public String CostCenterDivision {get; set;}    
        public Id ordertakingid {get; set;}
    }   
    
    private void getConstructionInvoiceList() {
        ConstructionInvoiceList = new List<InvoiceWrapper>();
        
        String soqlQuery = 'SELECT Id, Name, Cost_Centre_Main_Division__c, Cost_Center_Division__c, Invoice_Date__c, Order_Type__c, Model_Description__c, Invoice_Type__c, Order_Taking__r.name, Order_Taking__r.id, Total_Price_Net__c, Cost_Center__c';
        soqlQuery += ' FROM Order_ManPro__c ';
        soqlQuery += ' WHERE Account_order__c = \'' + currentAccount.Id  + '\'';
        soqlQuery += ' AND Cost_Centre_Main_Division__c = \'CONSTRUCTION ALL\'';
        soqlQuery += ' ORDER BY ' + constructionInvoiceSort;
        if (constructionInvoiceSortDesc)
            soqlQuery += ' DESC';
        
        for (Order_ManPro__c constInvoice : Database.query(soqlQuery))
        {
            InvoiceWrapper wrapper = new InvoiceWrapper();
            wrapper.InvoiceId = constInvoice.Id;
            wrapper.orderNumber = constInvoice.Name;
            wrapper.InvoiceDate = constInvoice.Invoice_Date__c;
            wrapper.OrderType = constInvoice.Order_Type__c;
            wrapper.ModelDescription = constInvoice.Model_Description__c;
            wrapper.InvoiceType = constInvoice.Invoice_Type__c;
            wrapper.OrderTaking = constInvoice.Order_Taking__r.name;
            wrapper.ordertakingid = constInvoice.Order_Taking__r.id;
            wrapper.TotalSellVAT = constInvoice.Total_Price_Net__c;
            wrapper.CostCenter = constInvoice.Cost_Center__c;
            wrapper.CostCenterDivision = constInvoice.Cost_Center_Division__c;
         
            ConstructionInvoiceList.add(wrapper);
        }
    }
    
    private void getDeltaInvoiceList() {
        DeltaInvoiceList = new List<InvoiceWrapper>();
        
        String soqlQuery = 'SELECT Id, Name, Cost_Centre_Main_Division__c, Account_order__c, Cost_Center_Division__c, Invoice_Date__c, Order_Type__c, Model_Description__c, Invoice_Type__c, Order_Taking__r.name, Total_Price_Net__c, Cost_Center__c';
        soqlQuery += ' FROM Order_ManPro__c ';
        soqlQuery += ' WHERE Account_order__c = \'' + currentAccount.Id  + '\'';
        soqlQuery += ' AND Cost_Centre_Main_Division__c = \'DELTA\'';
        soqlQuery += ' ORDER BY ' + DeltaInvoiceSort;
        if (DeltaInvoiceSortDesc)
            soqlQuery += ' DESC';
        
        for (Order_ManPro__c DeltaInvoice : Database.query(soqlQuery))
        {
            InvoiceWrapper wrapper = new InvoiceWrapper();
            wrapper.InvoiceId = DeltaInvoice.Id;
            wrapper.orderNumber = DeltaInvoice.Name;
            wrapper.InvoiceDate = DeltaInvoice.Invoice_Date__c;
            wrapper.OrderType = DeltaInvoice.Order_Type__c;
            wrapper.ModelDescription = DeltaInvoice.Model_Description__c;
            wrapper.InvoiceType = DeltaInvoice.Invoice_Type__c;
            wrapper.OrderTaking = DeltaInvoice.Order_Taking__r.name;
            wrapper.ordertakingid = DeltaInvoice.Order_Taking__r.id;
            wrapper.TotalSellVAT = DeltaInvoice.Total_Price_Net__c;
            wrapper.CostCenter = DeltaInvoice.Cost_Center__c;
            wrapper.CostCenterDivision = DeltaInvoice.Cost_Center_Division__c;
           
            DeltaInvoiceList.add(wrapper);
        }
    }
    private void getEnginePowerGenerationInvoiceList() {
        EnginePowerGenerationInvoiceList = new List<InvoiceWrapper>();
        
        String soqlQuery = 'SELECT Id, Name, Cost_Centre_Main_Division__c, Account_order__c, Cost_Center_Division__c, Invoice_Date__c, Order_Type__c, Model_Description__c, Invoice_Type__c, Order_Taking__r.name, Total_Price_Net__c, Cost_Center__c';
        soqlQuery += ' FROM Order_ManPro__c ';
        soqlQuery += ' WHERE Account_order__c = \'' + currentAccount.Id  + '\'';
        soqlQuery += ' AND Cost_Centre_Main_Division__c = \'ENGINE POWER GENERATION\'';
        soqlQuery += ' ORDER BY ' + EnginePowerGenerationInvoiceSort;
        if (EnginePowerGenerationInvoiceSortDesc)
            soqlQuery += ' DESC';
        
        for (Order_ManPro__c EnginePowerGenerationInvoice : Database.query(soqlQuery))
        {
            InvoiceWrapper wrapper = new InvoiceWrapper();
            wrapper.InvoiceId = EnginePowerGenerationInvoice.Id;
            wrapper.orderNumber = EnginePowerGenerationInvoice.Name;
            wrapper.InvoiceDate = EnginePowerGenerationInvoice.Invoice_Date__c;
            wrapper.OrderType = EnginePowerGenerationInvoice.Order_Type__c;
            wrapper.ModelDescription = EnginePowerGenerationInvoice.Model_Description__c;
            wrapper.InvoiceType = EnginePowerGenerationInvoice.Invoice_Type__c;
            wrapper.OrderTaking = EnginePowerGenerationInvoice.Order_Taking__r.name;
            wrapper.ordertakingid = EnginePowerGenerationInvoice.Order_Taking__r.id;
            wrapper.TotalSellVAT = EnginePowerGenerationInvoice.Total_Price_Net__c;
            wrapper.CostCenter = EnginePowerGenerationInvoice.Cost_Center__c;
            wrapper.CostCenterDivision = EnginePowerGenerationInvoice.Cost_Center_Division__c;
            
            EnginePowerGenerationInvoiceList.add(wrapper);
        }
    }
    
    private void getMiningInvoiceList() {
        MiningInvoiceList = new List<InvoiceWrapper>();
        
        String soqlQuery = 'SELECT Id, Name, Cost_Centre_Main_Division__c, Account_order__c, Cost_Center_Division__c, Invoice_Date__c, Order_Type__c, Model_Description__c, Invoice_Type__c, Order_Taking__r.name, Total_Price_Net__c, Cost_Center__c';
        soqlQuery += ' FROM Order_ManPro__c ';
        soqlQuery += ' WHERE Account_order__c = \'' + currentAccount.Id  + '\'';
        soqlQuery += ' AND Cost_Centre_Main_Division__c = \'MINING\'';
        soqlQuery += ' ORDER BY ' + MiningInvoiceSort;
        if (MiningInvoiceSortDesc)
            soqlQuery += ' DESC';
        
        for (Order_ManPro__c MiningInvoice : Database.query(soqlQuery))
        {
            InvoiceWrapper wrapper = new InvoiceWrapper();
            wrapper.InvoiceId = MiningInvoice.Id;
            wrapper.orderNumber = MiningInvoice.Name;
            wrapper.InvoiceDate = MiningInvoice.Invoice_Date__c;
            wrapper.OrderType = MiningInvoice.Order_Type__c;
            wrapper.ModelDescription = MiningInvoice.Model_Description__c;
            wrapper.InvoiceType = MiningInvoice.Invoice_Type__c;
            wrapper.OrderTaking = MiningInvoice.Order_Taking__r.name;
            wrapper.ordertakingid = MiningInvoice.Order_Taking__r.id;
            wrapper.TotalSellVAT = MiningInvoice.Total_Price_Net__c;
            wrapper.CostCenter = MiningInvoice.Cost_Center__c;
            wrapper.CostCenterDivision = MiningInvoice.Cost_Center_Division__c;
            
            MiningInvoiceList.add(wrapper);
        }
    }

    private void getProductSupportInvoiceList() {
        ProductSupportInvoiceList = new List<InvoiceWrapper>();
        
        String soqlQuery = 'SELECT Id, Name, Cost_Centre_Main_Division__c, Account_order__c, Cost_Center_Division__c, Invoice_Date__c, Order_Type__c, Model_Description__c, Invoice_Type__c, Order_Taking__r.name, Total_Price_Net__c, Cost_Center__c';
        soqlQuery += ' FROM Order_ManPro__c ';
        soqlQuery += ' WHERE Account_order__c = \'' + currentAccount.Id  + '\'';
        soqlQuery += ' AND Cost_Centre_Main_Division__c = \'PRODUCT SUPPORT\'';
        soqlQuery += ' ORDER BY ' + ProductSupportInvoiceSort;
        if (ProductSupportInvoiceSortDesc)
            soqlQuery += ' DESC';
        
        for (Order_ManPro__c ProductSupportInvoice : Database.query(soqlQuery))
        {
            InvoiceWrapper wrapper = new InvoiceWrapper();
            wrapper.InvoiceId = ProductSupportInvoice.Id;
            wrapper.orderNumber = ProductSupportInvoice.Name;
            wrapper.InvoiceDate = ProductSupportInvoice.Invoice_Date__c;
            wrapper.OrderType = ProductSupportInvoice.Order_Type__c;
            wrapper.ModelDescription = ProductSupportInvoice.Model_Description__c;
            wrapper.InvoiceType = ProductSupportInvoice.Invoice_Type__c;
            wrapper.OrderTaking = ProductSupportInvoice.Order_Taking__r.name;
            wrapper.ordertakingid = ProductSupportInvoice.Order_Taking__r.id;
            wrapper.TotalSellVAT = ProductSupportInvoice.Total_Price_Net__c;
            wrapper.CostCenter = ProductSupportInvoice.Cost_Center__c;
            wrapper.CostCenterDivision = ProductSupportInvoice.Cost_Center_Division__c;
            
            ProductSupportInvoiceList.add(wrapper);
        }
    }  
    
    private void getSamsungInvoiceList() {
        SamsungInvoiceList = new List<InvoiceWrapper>();
        
        String soqlQuery = 'SELECT Id, Name, Cost_Centre_Main_Division__c, Account_order__c, Cost_Center_Division__c, Invoice_Date__c, Order_Type__c, Model_Description__c, Invoice_Type__c, Order_Taking__r.name, Total_Price_Net__c, Cost_Center__c';
        soqlQuery += ' FROM Order_ManPro__c ';
        soqlQuery += ' WHERE Account_order__c = \'' + currentAccount.Id  + '\'';
        soqlQuery += ' AND Cost_Centre_Main_Division__c = \'SAMSUNG\'';
        soqlQuery += ' ORDER BY ' + SamsungInvoiceSort;
        if (SamsungInvoiceSortDesc)
            soqlQuery += ' DESC';
        
        for (Order_ManPro__c SamsungInvoice : Database.query(soqlQuery))
        {
            InvoiceWrapper wrapper = new InvoiceWrapper();
            wrapper.InvoiceId = SamsungInvoice .Id;
            wrapper.orderNumber = SamsungInvoice .Name;
            wrapper.InvoiceDate = SamsungInvoice .Invoice_Date__c;
            wrapper.OrderType = SamsungInvoice .Order_Type__c;
            wrapper.ModelDescription = SamsungInvoice .Model_Description__c;
            wrapper.InvoiceType = SamsungInvoice.Invoice_Type__c;
            wrapper.OrderTaking = SamsungInvoice.Order_Taking__r.name;
            wrapper.ordertakingid = SamsungInvoice.Order_Taking__r.id;
            wrapper.TotalSellVAT = SamsungInvoice.Total_Price_Net__c;
            wrapper.CostCenter = SamsungInvoice.Cost_Center__c;
            wrapper.CostCenterDivision = SamsungInvoice.Cost_Center_Division__c;
            
            SamsungInvoiceList.add(wrapper);
        }
    }  
    
    private void getOtherInvoiceList() {
        OtherInvoiceList = new List<InvoiceWrapper>();
        
        String soqlQuery = 'SELECT Id, Name, Cost_Centre_Main_Division__c, Account_order__c, Cost_Center_Division__c, Invoice_Date__c, Order_Type__c, Model_Description__c, Invoice_Type__c, Order_Taking__r.name, Total_Price_Net__c, Cost_Center__c';
        soqlQuery += ' FROM Order_ManPro__c ';
        soqlQuery += ' WHERE Account_order__c = \'' + currentAccount.Id  + '\'';
        soqlQuery += ' AND Cost_Centre_Main_Division__c = \'OTHERS MISC - INTERNAL\'';
        soqlQuery += ' ORDER BY ' + OtherInvoiceSort;
        if (OtherInvoiceSortDesc)
            soqlQuery += ' DESC';
        
        for (Order_ManPro__c OtherInvoice : Database.query(soqlQuery))
        {
            InvoiceWrapper wrapper = new InvoiceWrapper();
            wrapper.InvoiceId = OtherInvoice.Id;
            wrapper.orderNumber = OtherInvoice.Name;
            wrapper.InvoiceDate = OtherInvoice.Invoice_Date__c;
            wrapper.OrderType = OtherInvoice.Order_Type__c;
            wrapper.ModelDescription = OtherInvoice.Model_Description__c;
            wrapper.InvoiceType = OtherInvoice.Invoice_Type__c;
            wrapper.OrderTaking = OtherInvoice.Order_Taking__r.name;
            wrapper.ordertakingid = OtherInvoice.Order_Taking__r.id;
            wrapper.TotalSellVAT = OtherInvoice.Total_Price_Net__c;
            wrapper.CostCenter = OtherInvoice.Cost_Center__c;
            wrapper.CostCenterDivision = OtherInvoice.Cost_Center_Division__c;
            
            OtherInvoiceList.add(wrapper);
        }
    }  
    
    public pageReference NewInvoice() {
        PageReference pageRef = new PageReference('/a0J/e?CF00Nb0000005YEDS_lkid=' + currentAccount.Id  + '&CF00Nb0000005YEDS=' + currentAccount.Name);
        pageRef.setRedirect(true);
        return pageRef;
    }         
    
}

test class
@isTest  (SeeAllData=true) 

    private class TESTAccountInvoiceTabExtension {
    
        static testmethod void AccountInvoiceTabExtension_Test (){
                     
            test.StartTest();
            
            Account acc = new Account(Name ='icrm testing acc');
            insert acc;
            
            Order_ManPro__c constInvoice = new Order_ManPro__c ( Name='1234',  Account_order__c= acc.Id, 
                                                                Cost_Centre_Main_Division__c ='CONSTRUCTION ALL', Cost_Center_ManPRO__c = 'a0e8E000001OZuM', 
                                                                Cost_Center_Division__c = 'CONSTRUCTION ALL',Cost_Centre_Description__c = 'Machine Rental (Const)',Cost_Center__c = 'CMM',
                                                                CurrencyIsoCode = 'USD', Invoice_Date__c = System.today().addDays(30),Order_Type__c = 'rergg', Model_Description__c = 'desc',
                                                                Order_Taking__c = '005b00000010h3o', External_Order_ID__c = '9876000');
           insert constInvoice;
           
           Order_ManPro__c DeltaInvoice = new Order_ManPro__c ( Name='234' ,  Account_order__c= acc.Id, 
                                                                Cost_Centre_Main_Division__c ='DELTA', Cost_Center_ManPRO__c = 'a0e8E000001OZuM', 
                                                                Cost_Center_Division__c = 'AGRICULTURE',Cost_Centre_Description__c = 'John Deer',Cost_Center__c = 'NMB',
                                                                CurrencyIsoCode = 'USD', Invoice_Date__c = System.today().addDays(30),Order_Type__c = 'rergg', Model_Description__c = 'desc',
                                                                Order_Taking__c = '005b00000010h3o', External_Order_ID__c = '98760900');
           insert DeltaInvoice;
                 
           Order_ManPro__c EnginePowerGenerationInvoice = new Order_ManPro__c (Name='234' ,  Account_order__c= acc.Id, 
                                                   Cost_Centre_Main_Division__c ='ENGINE POWER GENERATION', Cost_Center_ManPRO__c = 'a0e8E000001OZvj', 
                                                   Cost_Center_Division__c = 'MARINE',Cost_Centre_Description__c = 'Marine Engines',Cost_Center__c = 'CEC',
                                                   CurrencyIsoCode = 'USD', Invoice_Date__c = System.today().addDays(30),Order_Type__c = 'rergg', Model_Description__c = 'desc',
                                                   Order_Taking__c = '005b00000010h3o', External_Order_ID__c = '1');
           insert EnginePowerGenerationInvoice;
           
           Order_ManPro__c MiningInvoice = new Order_ManPro__c (Name='234' ,  Account_order__c= acc.Id, 
                                                   Cost_Centre_Main_Division__c ='MINING', Cost_Center_ManPRO__c = 'a0e8E000001OZw8', 
                                                   Cost_Center_Division__c = 'MINING',Cost_Centre_Description__c = 'Rental machines Mining',Cost_Center__c = 'CMI',
                                                   CurrencyIsoCode = 'USD', Invoice_Date__c = System.today().addDays(30),Order_Type__c = 'rergg', Model_Description__c = 'desc',
                                                   Order_Taking__c = '005b00000010h3o', External_Order_ID__c = '9');
           insert MiningInvoice;
           
           Order_ManPro__c ProductSupportInvoice = new Order_ManPro__c (Name='234' ,  Account_order__c= acc.Id, 
                                                   Cost_Centre_Main_Division__c ='PRODUCT SUPPORT', Cost_Center_ManPRO__c = 'a0e8E000001OZvV', 
                                                   Cost_Center_Division__c = 'PRODUCT SUPPORT',Cost_Centre_Description__c = 'Service Admin Mining',Cost_Center__c = 'CS2',
                                                   CurrencyIsoCode = 'USD', Invoice_Date__c = System.today().addDays(30),Order_Type__c = 'rergg', Model_Description__c = 'desc',
                                                   Order_Taking__c = '005b00000010h3o', External_Order_ID__c = '2');
           insert ProductSupportInvoice;
           
           Order_ManPro__c SamsungInvoice = new Order_ManPro__c (Name='234' ,  Account_order__c= acc.Id, 
                                                   Cost_Centre_Main_Division__c ='SAMSUNG', Cost_Center_ManPRO__c = 'a0e8E000001OZxo', 
                                                   Cost_Center_Division__c = 'SAMSUNG',Cost_Centre_Description__c = 'Audio and Video Products',Cost_Center__c = 'TEC',
                                                   CurrencyIsoCode = 'USD', Invoice_Date__c = System.today().addDays(30),Order_Type__c = 'rergg', Model_Description__c = 'desc',
                                                   Order_Taking__c = '005b00000010h3o', External_Order_ID__c = '4');
           insert SamsungInvoice;
           
           Order_ManPro__c OtherInvoice = new Order_ManPro__c (Name='234' ,  Account_order__c= acc.Id, 
                                                   Cost_Centre_Main_Division__c ='OTHERS MISC - INTERNAL', Cost_Center_ManPRO__c = 'a0e8E000001OZuZ', 
                                                   Cost_Center_Division__c = 'OTHERS MISC - INTERNAL',Cost_Centre_Description__c = 'Internal Sales Reps',Cost_Center__c = 'ZSR',
                                                   CurrencyIsoCode = 'USD', Invoice_Date__c = System.today().addDays(30),Order_Type__c = 'rergg', Model_Description__c = 'desc',
                                                   Order_Taking__c = '005b00000010h3o', External_Order_ID__c = '6');
           insert OtherInvoice;          
           
           PageReference pref = Page.Invoice_Tabs;
           pref.getParameters().put('id', acc.id);
           Test.setCurrentPage(pref);
           
           ApexPages.StandardController sc = new ApexPages.StandardController(acc);
           
           AccountInvoiceTabExtension mc = new AccountInvoiceTabExtension(sc);
           PageReference result = AccountInvoiceTabExtension.autoRun();
           System.assertNotEquals(null, result);

   
           test.stopTest();        
        }     
}

 
Hello,

If i need to add errors to multiple objects that caused the eror.

I am executing triggers and i add apex.add message

but i want to add the message to the multiple objects that created the error

how cna i achieve ot ?

 


Hi Expert,

I have a scenerio in which i have to update the field "budget hours" of "project portfolio" object with the "budget hour" field of "project" object, hence 1 "project portfolio" have multiple "project", it should have all the sum of "budget hour" field into that "budget hours" of "project portfolio" object. 

But when we cange the "project portfolio" in "project" object. so in the "budget hours" field of "project portfolio" should deacreases, coz we have change the "project portfolio" of that partcular "project" and add the "budget hours" of another "project portfolio" which we have added. but it is not hapenning in my org. 

Code is here- 

public class updateBudgetedHours 
{

  public static List<CloudbyzITPM__Project__c> affectedBudgetedHours = new List<CloudbyzITPM__Project__c>();
 public static set<ID> affc = new set<ID>();
 public static void processAfterUpdateBudgetedHours()
 {
     affectedBudgetedHours = (List<CloudbyzITPM__Project__c>)Trigger.New;
     if(affectedBudgetedHours.size()>0){
     for(CloudbyzITPM__Project__c  affc1 : affectedBudgetedHours)
     {
         if(affc1.CloudbyzITPM__Project_Portfolio__c != null)
         {
      affc.add(affc1.CloudbyzITPM__Project_Portfolio__c);
     }
     }
     
    if(affc.size()>0)
    {
    CloudbyzITPM__Project_Portfolio__c fn = [select id,name, CloudbyzITPM__Budgeted_Hours__c from CloudbyzITPM__Project_Portfolio__c where id IN :affc limit 1];
    list<CloudbyzITPM__Project__c> affectedBudgetedHours1 = [select id,name,CloudbyzITPM__Project_Portfolio__c,CloudbyzITPM__Budgeted_Hours__c from CloudbyzITPM__Project__c where CloudbyzITPM__Project_Portfolio__c = :fn.id];
    Decimal i=0;
       
    if(affectedBudgetedHours1.size()>0)
       {
           for(CloudbyzITPM__Project__C afc1 : affectedBudgetedHours1)
        {
            i = i + afc1.CloudbyzITPM__Budgeted_Hours__c;
        }
    }
    
 if(i>0)
 {
     System.debug('@@pBUFinal@@');
    fn.CloudbyzITPM__Budgeted_Hours__c = i;
    }
     update fn; 
      System.debug('@@fn4@@'+fn);
    }
    
    }
 }
}

Trigger- 

Trigger UpdateBH on CloudbyzITPM__Project__c (before insert, before update, before delete,after insert, after update, after delete) 

{
if((Trigger.isInsert || Trigger.isUpdate) && Trigger.isAfter )   
{
updateBudgetedHours.processAfterUpdateBudgetedHours();
}

if((Trigger.isDelete || Trigger.isUpdate) && Trigger.isBefore)
{
updateBudgetedHours.processAfterUpdateBudgetedHours();
}
}


what to change in the code?

Thanks & Regards,

Deepak
I want to display the a field label differently on a Product record. I have written the VF below. However, when I go to a Product record, it still displays as "Product Name" and not "Project Name". What am I doing wrong?

<apex:page standardController="Product2">
   <apex:form>
       <apex:pageBlockSection columns="2">
    <apex:inputField Value="{!Product2.Name}" label="Project Name" />
       </apex:pageBlockSection>    
   </apex:form>
</apex:page>
public pagereference redirectLater(){
        pagereference pgRd;
        try{
            pgRd = new pagereference('/Save_Page?lang='+ApexPages.currentPage().getParameters().get('lang'));
            pgRd.setRedirect(true);
        }
        catch(Exception e){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, e.getMessage()));
            return null;
        }     
        return pgRd;    
    }
 
Hello friends,

I,ve been trying to deploy some metadata in the DE org thru Ant, I am pretty sure I've enter the correct username, password+security token and the url, but it keeps saying:

BUILD FAILED
D:\Salesforce Migration Tool\salesforce_ant_38.0\sample\build.xml:60: Invalid username, password, security token; or user locked out.

I don't know what else to try, if someone can help me I would appreciate it, thanks a lot.
 
I have made some additions and changes to a custom picklist field and then added this field to a change set. When I then deploy that change set to another sandbox none of the picklist value changes are being deployed.
Note:
  • I can see the new picklist values in the change set XML
  • I am not using any Record Types with the custom object - so its not that the values are yet to be made available
I'm sure this has always worked properly in the past but not now under Winter'17.
Having to document and make the changes to the destination orgs manually - very annoying.
I have the following Trigger to Update Contact Owner Only when Account Owner Changes however only some of the Contact Owners are being updated. It's not updating any other child records, which is great. I just need to understand why it won't update ALL Contacts on an Account.

trigger Changeownertrigger on Account (after update) {
       
          Set<Id> accountIds = new Set<Id>();
          Map<Id, String> oldOwnerIds = new Map<Id, String>();
          Map<Id, String> newOwnerIds = new Map<Id, String>();
          Contact[] contactUpdates = new Contact[0];
          
          for (Account a : Trigger.new)
          {
             if (a.OwnerId != Trigger.oldMap.get(a.Id).OwnerId)
             {
                oldOwnerIds.put(a.Id, Trigger.oldMap.get(a.Id).OwnerId);
                newOwnerIds.put(a.Id, a.OwnerId);
                accountIds.add(a.Id);
             }

          }
            if (!accountIds.isEmpty()) {
             for (Account acc : [SELECT Id, (SELECT Id, OwnerId FROM Contacts) FROM Account WHERE Id in :accountIds])
                {
                String newOwnerId = newOwnerIds.get(acc.Id);
                String oldOwnerId = oldOwnerIds.get(acc.Id);
                for (Contact c : acc.Contacts)
                {
                   if (c.OwnerId == oldOwnerId) 
                   {
                   Contact updatedContact = new Contact(OwnerId = newOwnerId);
                   contactUpdates.add(updatedContact);
                   }
                }
                 
                }
           }
                update contactUpdates;
    }
I need to pull any Projects were the EDI_Result__c LastModifiedDate = today. I can't seem to figure out how to right my query. Below is what I have right now. EDI_Result__c is a look up field. 

SELECT EDI_Result__c FROM Project__c WHERE LastModifiedDate = today
Is there a way to write logic that can determine if a value starts with any alpha character or any numeric character?  Example would be we want to know if a string begins with an 2 alpha characters.  Or we want to know if it begins with any 3 numeric values.  Or a combination.  

@@#####  So this would indicate the string should start with any 2 alpha and then have 5 numeric.  This will be used in an APEX batch process uses a rules table to determine if records meet one of the defined criteria.  So we would need a way to define the mapping and then a way to check it in APEX.  Any help would be appreciated.  Thanks.  
I have Field label as  Lead source which is Formula field  on Quote object .But  now the requirement is insted of formulae they require  Pick list field.So i created a new pick list field and labeld as Lead source .now i want to update all the pick list value by formula field by developer console ananymous window .how to update a record value from developer console. can any one help
Hi All,
I am getting error as following : IN operator must be used with an iterable expression .
My code is : 
List<Task> ts1=[Select Id,WhoId from Task];
    for(Task ts2 : ts1){
    Map<ID, Obj1__c> mapAccounts = new Map<ID, Obj1__c>([SELECT Id, Name, Filed1__c  FROM Obj1__c WHERE                                                                                                               Field1__r.Id IN: ts2.whoId]);
}
Filed1__c is lookup to account.
How to resolve this?

Thanks in Advance
public with sharing class Support_Footer_Controller {
    public List<Language_Codes__c> langCodeList = new List<Language_Codes__c>();
    public map<string, string> langCodeURLMap = new map<string, string>();
    //Default Constructor
    public Support_Footer_Controller(){
    }
    //Function to redirect contact support page
    public pagereference redirectToContactSupport(){
        try{
            //Get language code and URL parameters from custom setting
            langCodeList = Language_Codes__c.getAll().values();
            for(Language_Codes__c lang : langCodeList){
                langCodeURLMap.put(lang.language_code__c, lang.language_URL__c);
            }
            String userLanguage = ApexPages.currentPage().getParameters().get('lang');
            if(langCodeURLMap.get(userLanguage) != null){
                userLanguage = langCodeURLMap.get(userLanguage);
            }
            //Redirect to contact support page 
            pagereference pg = new pagereference(System.Label.url1+userLanguage+System.Label.url2);
            system.debug('userLanguage=='+userLanguage);
            pg.setRedirect(true);
            return pg;
        }
        catch(Exception e){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, e.getMessage()));
            return null;
        }

    }
}
Hi Community,
I am not a developer and am just trying to make, what I thought, was a quick update to an existing button.

The button creates a Project (Custom Object) from a Request (Custom Object).  I need to be able to relate the Request to the newly created Project.  This is the code that creates the project, but I need to then call the ID of the newly created Project and insert it into the Project Lookup Field on the Request so the Request becomes a record of the related list on the Project.  Does that make sense?  Is this even possible?

{!REQUIRESCRIPT("/soap/ajax/29.0/connection.js")} 

var Proj = new sforce.SObject("SFDC_Project__c"); 

Proj.SFDC_Project_Name__c = '{!SFDC_Request__c.Name}' 
Proj.SFDC_Project_Description__c = '{!SFDC_Request__c.Request_Detail__c}' 
Proj.Users_Affected__c = '{!SFDC_Request__c.Users_Affected__c}' 
Proj.Segment_specific_or_Veritiv__c = '{!SFDC_Request__c.Segment_Specific_or_Veritiv__c}' 
Proj.Urgency__c = '{!SFDC_Request__c.request_priority__c}' 
Proj.Recommended_Solution__c = '{!SFDC_Request__c.Requirements__c}' 

// {!SFDC_Request__c.SFDC_Project__c} = {!SFDC_Project__c.Id} 

var result = sforce.connection.create([Proj]) 

if(result[0].success=='true'){ 
alert('Project ' + Proj.SFDC_Project_Name__c + ' successfully created'); 
}else{ 
alert('Could not create record ' + result); 
}
 

Date.Today().MONTH()+'_'+Date.Today().Day()

From the above how can i get the first 3 letters of a month from the current date Date.Today().MONTH() (example: this should be as Nov, as this is Nov 3, 2016)

From the above how can i get the first 2 letters of the day from the current date Date.Today().Day() (example: This should be as 03, as today is Nov 3, 2016).

Can anyone provide their inputs to the code, which would be really helpful.


 

Hi,

I created an APEX class that creates a Flow plug-in. I followed the documentation online, I'll post link below. But I cant seem to be able to write a test class that will fully cover the APEX class.

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_process_plugin.htm


CLASS
global class flowTask implements Process.Plugin{
    
    global Process.PluginResult invoke(Process.PluginRequest request){
        
        string taskCase = (String) request.inputParameters.get('CaseId');
        date taskDate = date.today();
        String description = (String) request.inputParameters.get('subject');
        
        Task myTask = new Task();
        myTask.ActivityDate = taskDate;
		myTask.Description = description;
        myTask.Status = 'Completed';
        myTask.WhatId = taskCase;
        
        insert myTask;
        
        Map<String, Object> result = new Map<String, Object>();
        return new Process.PluginResult(result);
    }
    
    global Process.PluginDescribeResult describe(){
        Process.PluginDescribeResult result = new Process.PluginDescribeResult();
        result.Name = 'flowtaskpluggin';
        result.Tag = 'task';
        result.inputParameters = new List<Process.PluginDescribeResult.inputParameter>{
            new Process.PluginDescribeResult.InputParameter('subject', Process.PluginDescribeResult.ParameterType.STRING, true),
            new Process.PluginDescribeResult.InputParameter('CaseId', Process.PluginDescribeResult.ParameterType.STRING, true)   
        };
            result.outputParameters = new List<Process.PluginDescribeResult.outputParameter>{
                
            };
            return result;
    }

}


TEST
@isTest
private class flowTaskTest{
    
    static testmethod void flowTaskTest(){
        
        flowTask plugin = new flowTask();
        Map<String, Object> inputParams = new Map<String, Object>();
        string taskNum = '50063000003AEik';		//50063000003AEik-SBX | 500o000000GCryb-PROD
        string taskSub = 'Test Class';
        
        inputParams.put('subject', taskSub);
        inputParams.put('CaseId', taskNum);
        
        Process.PluginRequest request = new Process.PluginRequest(inputParams);
        
        plugin.invoke(request);
    }

}


Im not sure how to test the describe function in the APEX code. Any information is a helpful. 

Thanks,
-Julio Hernandez
i wrote a test class to test a trigger and future apex class, nevertheless i am reciving this error message, can anyone help me out

System.DmlException: Update failed. First exception on row 0 with id 00Q260000034xE0EAI; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, CP_Approve_Rejects: execution of AfterUpdate

caused by: System.NullPointerException: Attempt to de-reference a null object

Trigger.CP_Approve_Rejects: line 9, column 1: []


Test class code as below
@isTest
private class CP_Approve_Reject_Test {
    static testmethod void  Approve_CP_Lead() {              
        // This causes a fake response to be generated
         Lead lead = new Lead(firstName='first', lastName='last', company='company', leadSource='Client-Portal-Lead-Cn', entity__c='Hong Kong', isTest__c=true);
      
        
              
              
        Test.startTest();
         insert lead;
          Lead leads = lead;
         leads.Approval_Status__c ='Approved';
         update(leads);
        Test.setMock(WebServiceMock.class, new ADSSWebServicesMockImpl());
         
        // Test.setMock(WebServiceMock.class, new ADSSWebServicesMockImpl());
        
        Test.stopTest();

    }
    
    }
I have webhooks set up and running correctly in a sandbox between Stripe and Salesforce, but have an error when sending a test webhook from Stripe into production: "Certificate name mismatch".
Wondering if it likely due to the TLS update, a mismatched certificate for the Site in my production instance that I created today, or maybe something else? I can log a Case as well but maybe someone has an idea.
User-added imageI can not seem to figure out how to get a profile to show up here. There doesn't seem to be a default profile under my profiles called external identity. How do I get a profile to appear here that way I can allow self-register 
Hey all,

Posted about this a while ago, but still never got a real answer. Please help if you can!

We have a Date field in our Contact records - "Date of Training"

We want to build a Checkbox field in the Account level that looks at all of the Contacts related to that Account, and if there is a Contact trained in the past 6 months, then the box will be checked. If there is no Contact in the Account trained in the past 6 months, the Checkbox will be unchecked.

I'm aware this will take APEX code and triggers, just not sure how to approach it

Can anyone help with this?
We have below simple example visualforce page (to be used as inline VF page for Opportunity).
 
<apex:page standardController="Opportunity" >
    This page doesn't have any content.
</apex:page>

This page is added to Opportunity page layout for Partner Community User.
When we view as partner community user, it appears as a link as below.

User-added image

Because of this, it seems contents inline pages are not accessible. Also when we click on this page, it goes to 'Invalid page' community page which is not intended at all.
Any idea how we can remove this link behavior? Appreciate any help on this. Thanks.
 
Hello, there! The highlighted "if" and "else if" statement for the "Percent Complete" field below never execute. Only the "else" statement would work as expected. Does anyone know how to re-write to make it work? Any help will be greatly appreciated!!
if(fldsPopulated == numberFlds){
                PrecentComplete = 100;
            }else if(fldsPopulated == 0){
                PrecentComplete = 0;
            }else{
                precentComplete = ((numberFlds - fldsPopulated)/numberFlds)*100;
            }

Here's the complete Apex Class. Everything else works except for the if statement for the Percent Complete field mentioned above. Thanks in advance for your suggestions!
public with sharing class AccountGradingMethod {

    public static void AccountGrading(Set<String> setAcctGradingIds) {
        List<Account> lstAGS = new List<Account>();
        List<Account> lstUpdateAcct = new List<Account>();
        Map<String, Field_Value__mdt> mapFlds = new Map<String, Field_Value__mdt>();
        String strSOQLAcct;
        String strSOQLAcctGrade;
        Set<String> setFlds = new Set<String>();
        Set<String> setFldName = new Set<String>();
        String strScore;
        Decimal maxPossScore = 0;
        Decimal numberFlds = 0;

        strSOQLAcctGrade = 'SELECT Id';
        for(Field_Value__mdt fn:[SELECT Id, Field_Score_or_Multiplier__c, Picklist_API_Value__c, Use_Greater_then_or_Less_then__c, 
                                        Field_Name__r.Field_API_Name__c, Field_Name__r.Object__c, Field_Name__r.Type_of_Field__c,
                                        Greater_then__c, Less_then__c
                                    FROM Field_Value__mdt]){
            String mapKey;
            setFldName.add(fn.Field_Name__r.Field_API_Name__c);
            if(fn.Field_Name__r.Object__c == 'Account'){
                setFlds.add(fn.Field_Name__r.Field_API_Name__c);
            }
            if(fn.Use_Greater_then_or_Less_then__c){
                mapKey = fn.Field_Name__r.Field_API_Name__c + '-' + fn.Greater_then__c + '-' + fn.Less_then__c;
            }
            else{
                mapKey = fn.Field_Name__r.Field_API_Name__c + '-' + fn.Picklist_API_Value__c.deleteWhitespace();
            }
            mapFlds.put(mapKey, fn);
        }
        for(String f:setFlds){
            strSOQLAcctGrade += ', ' + f;
        }
        numberFlds = setFlds.size();
        strSOQLAcctGrade += ' FROM Account WHERE Id in :setAcctGradingIds';
        System.debug('strSOQLAcctGrade: ' + strSOQLAcctGrade);
        lstAGS = Database.query(strSOQLAcctGrade);
        strScore = System.Label.Max_Possible_Score;
        maxPossScore = Decimal.valueOf(strScore);

        for(Account ags:lstAGS){
            Decimal subTotal = 0;
            Decimal multiplier = 1;
            Decimal decTotal = 0;
            Decimal ecommTotal = 0;
            Decimal ecommMin = 0;
            Decimal ecommMax = 0;
            Decimal fldsPopulated = 0;
            Decimal precentComplete = 0;
            for(Field_Value__mdt fldVal:mapFlds.values()){
                String value;
                Decimal score = 0;
                Boolean skip = false;
                String fld = fldVal.Field_Name__r.Field_API_Name__c;
                String strKey;
                Decimal decValue = 0;
                if(setFldName.contains(fld)){
                    if(fldVal.Field_Name__r.Object__c == 'Account'){
                        value = String.valueOf(ags.get(fld));
                        if(value != '' && value != 'null' && value != null){
                            value = value.deleteWhitespace();
                            if(fldVal.Use_Greater_then_or_Less_then__c){
                                decValue = Decimal.valueOf(value);
                                System.debug('decValue: ' + decValue);
                                if(fldVal.Greater_then__c != null && fldVal.Less_then__c != null){
                                    if(fldVal.Greater_then__c > decValue && fldVal.Less_then__c < decValue){
                                     System.debug('if 1 fldVal.Less_then__c: ' + fldVal.Less_then__c);
                                        strKey = fld + '-' + fldVal.Greater_then__c + '-' + fldVal.Less_then__c;
                                    }
                                    else{
                                        skip = true;
                                    }
                                }
                                if(fldVal.Greater_then__c == null && fldVal.Less_then__c != null){
                                    if(fldVal.Less_then__c > decValue){
                                     System.debug('if 2 fldVal.Less_then__c: ' + fldVal.Less_then__c);
                                        strKey = fld + '-' + fldVal.Greater_then__c + '-' + fldVal.Less_then__c;
                                    }
                                    else{
                                        skip = true;
                                    }
                                }
                                if(fldVal.Greater_then__c != null && fldVal.Less_then__c == null){
                                    System.debug('if 3 fldVal.Greater_then__c : ' + fldVal.Greater_then__c );
                                    if(fldVal.Greater_then__c < decValue){
                                        strKey = fld + '-' + fldVal.Greater_then__c + '-' + fldVal.Less_then__c;
                                    }
                                    else{
                                        skip = true;
                                    }
                                }
                            }
                            else if (!fldVal.Use_Greater_then_or_Less_then__c){
                                strKey = fldVal.Field_Name__r.Field_API_Name__c + '-' + value;
                            }
                            if(!String.isBlank(strKey) && mapFlds.get(strKey) != null){
                                setFldName.remove(fld);
                                score = mapFlds.get(strKey).Field_Score_or_Multiplier__c;
                            }
                            if(score != null){
                                if(fld.startsWithIgnoreCase('e-commerce solutions')){
                                    skip = true;
                                    ecommTotal = ecommTotal + score;
                                    if(ecommMax<score){
                                        ecommMax = score;
                                    }
                                    if(ecommMin>score){
                                        ecommMin = score;
                                    }
                                }
                                if(fldVal.Field_Name__r.Type_of_Field__c == 'Score' && !skip){
                                    System.debug('fld: ' + fld);
                                    System.debug('Score: ' + score);
                                    subTotal = subTotal + score;
                                }
                                if(fldVal.Field_Name__r.Type_of_Field__c == 'Multiplier' && !skip){
                                    System.debug('fld: ' + fld);
                                    System.debug('multiplier: ' + score);
                                    multiplier = multiplier * score;
                                }
                            }
                        }
                        else{
                            fldsPopulated = fldsPopulated + 1;
                            setFldName.remove(fld);
                        }
                    }
                }
            }
            if(ecommTotal>=0){
                subTotal = subTotal + ecommMax;
            }
            else{
                subTotal = subTotal + ecommMin;
            }
            
            if(fldsPopulated == numberFlds){
                PrecentComplete = 100;
            }else if(fldsPopulated == 0){
                PrecentComplete = 0;
            }else{
                precentComplete = ((numberFlds - fldsPopulated)/numberFlds)*100;
            }
            
            System.debug('subtotal: ' +  subTotal);
            subTotal = (subTotal/maxPossScore)*100;
            System.debug('subtotal after: ' +  subTotal);
            System.debug('multiplier: ' + multiplier);
            decTotal = subTotal*multiplier;
            System.debug('decTotal: ' + decTotal );
            Account a = new Account();
                a.Id = ags.Id;
                a.Account_Overall_Grade__c = decTotal;
                a.Percent_Complete__c = precentComplete;
                a.LastScoredDate__c = System.today();
            lstUpdateAcct.add(a);

        }
        if(lstUpdateAcct.size()>0){
            update lstUpdateAcct;
        }
    }
}

 
Hi All

I have created a trigger for sum of child field and update in parent like roll up summary through look up relationship.When i am creating new child record its working,but i am updating extisting child record its not working ...
trigger TotalSalesTrigger on Sales__c (after insert, after delete, after undelete, after update) {
    set<Id> invIdSet = new set<Id>();
    
    if(trigger.isinsert || trigger.isUpdate || trigger.Isundelete){
        for(Sales__c invItem: Trigger.new){
            if(Trigger.isInsert || Trigger.isUndelete || (invItem.Sold_Price__c!= Trigger.oldMap.get(invItem.Id).Sold_Price__c|| invItem.Customer_Name__c!= Trigger.oldMap.get(invItem.Id).Customer_Name__c))
                invIdSet.add(invItem.Customer_Name__c);            
        }
    }    
    if(trigger.isUpdate || trigger.isDelete) {
        for(Sales__c invItem: Trigger.old){
            if(Trigger.isDelete || (invItem.Sold_Price__c!= Trigger.newMap.get(invItem.Id).Sold_Price__c|| invItem.Customer_Name__c!= Trigger.newMap.get(invItem.Id).Customer_Name__c))
                invIdSet.add(invItem.Customer_Name__c);
        }
    }
     List<Contact> invList= [Select id,name,Total_Sale__c,(Select id,Sold_Price__c from Sales__r) from Contact  Where ID IN: invIdSet];       
      
    for(Contact inv : invList){
        
        inv.Total_Sale__c= 0;
        for(Sales__c invItem : inv.Sales__r) {
            inv.Total_Sale__c+= invItem.Sold_Price__c ;
        }
    }
    update invList;

 
I want to create a two recordtypes on the case object.one is Master and One is custom.I don't want to see CaseOrigin field in the custom reportype.How can i hide a field for a particular recordtype .Please suggest me with this.
Hi,
I am trying to run a query below from developer documentation
SELECT Amount, FORMAT(amount) Amt, convertCurrency(amount) convertedAmount, FORMAT(convertCurrency(amount)) convertedCurrency FROM Opportunity where id = '0069000000va8SS'
When I am running this query from developer console -> query editor I am getting only first column (Amount) as result. And not other columns are showing.

but when I run same query from Workbench it is showing correct results.

User-added image
Could you please let me know what could be reason?

Best Regards,

Rahul
Hi
I have problem in my project, because i have application components with a lot of components and i have to define some constance to use them across all components in application. What is the best approach for this? Currently I define a lot of attributes with default text value and I use them as constans but i think that isn't the best solution.
 
Im currently writing a trigger handler to add a parent id to an account based on a variable called DUNS Number. When I add a new record I run into a DML Error 50001 limit reached.  

/******************************************************************************************************
 * @NAME         : OnBeforeInsert
 * @DESCRIPTION  : Catch any missing data before inserting a Account record
 * @PARAMETER    : List of Accounts to affect
 ******************************************************************************************************/
    public void BeforeInsert(Account[] newAccounts){
        Map<String, Id> dunsMap = getDUNSMap(newAccounts);
        try{
            FOR(Account acct : newAccounts){
                //acct.Sales_Region__c = region.getCorrectAccountRegionSingle(acct);
                if(acct.Parent_DUNS_Number__c != null){
                    acct.ParentId = dunsMap.get(acct.Parent_DUNS_Number__c);
                }
            }
        }catch(Exception ex){}
    }

 /******************************************************************************************************
 * @NAME         : getDUNSMap
 * @DESCRIPTION  : Gets the Id of the Parent Account based on the DUNS Number
 * @PARAMETER    : Account List to search for
 * @RETURN       : Map<String, Id> of the Queried Parent Account with their duns numbers
 ******************************************************************************************************/   
    private Map<String, Id> getDUNSMap(List<Account> accountList){
        Map<String, Id> dunsMap = new Map<String, Id>();
        
        List<String> parentDunsList = new List<String>();
        
        For(Account a : accountList){ 
            parentDunsList.add(a.Parent_DUNS_Number__c);
        }
        List<Account> parentList =[SELECT id, DUNS_Number__c FROM Account WHERE DUNS_Number__c In : parentDunsList];
        
        FOR(Account a1 : parentList){
            dunsMap.put(a1.DUNS_Number__c, a1.Id);
        }
        
        return dunsMap;
    }
I am trying to check to see if a field has only numbers in it. It can also be left blank. The regex formula that I have written accepts both letters and numbers and I cannot figure out what I am doing wrong. I am new to regex so please be kind.

The validation rule is:
AND( 
ISBLANK(Checking_Account_Number__c), 
NOT (REGEX(Checking_Account_Number__c, "(//[0-9]+)")) 
)

Thanks for any help.
Please help me how to fix it?
Hi All,

I have created onebatch apex as mentioend below.I want to scheduled the class everday midnight automatically.Can any one help me to create a Automatic scheduled class.

BatchApex:
global class OpportunitySplit implements Database.Batchable<Sobject>{
    global OpportunitySplit(){
    }
        //START Method
        global Database.QueryLocator start(Database.BatchableContext BC){
        DateTime dt = DateTime.now().addHours(-24);
        String query = 'SELECT Id,name,Total_Account_Manager__c,Total_Channel_Manager__c FROM Opportunity WHERE LastModifiedDate = ToDay ';
        return Database.getQueryLocator(query);
        }
        //execute Method
        global void execute(Database.BatchableContext BC,List<Opportunity> lstOpp){

            Map<Id,Integer> MapIdOppTosumAcMngr = new Map<Id,Integer>();
            Map<Id,Integer> MapIdOppTosumChMgnr = new Map<Id,Integer>();
            Map<Id,Opportunity> MapOpportunity = new Map<Id,Opportunity>(lstOpp);
            Opportunity objOppToUpdate;
            
            List<Opportunity> lstOppToUpdate = new List<Opportunity>();           
            for(OpportunitySplit objOppSplit : [SELECT Id, Role_Name__c, OpportunityId FROM OpportunitySplit WHERE Role_Name__c IN (' Account Manager',' Channel Manager') AND OpportunityId IN: MapOpportunity.keySet()]){                                     
                system.debug('====objOppSplit===='+objOppSplit);
                
                if(objOppSplit.Role_Name__c == 'Account Manager'){
                   
                    MapIdOppTosumAcMngr.put(objOppSplit.OpportunityId, MapIdOppTosumAcMngr.containsKey(objOppSplit.OpportunityId) ? (MapIdOppTosumAcMngr.get(objOppSplit.OpportunityId)+1): 1);
                }
                else{
                      
                     MapIdOppTosumChMgnr.put(objOppSplit.OpportunityId,MapIdOppTosumChMgnr.containsKey(objOppSplit.OpportunityId) ? (MapIdOppTosumChMgnr.get(objOppSplit.OpportunityId)+1): 1);
                    }
            }
            for(Opportunity objOpp : MapOpportunity.values()){
                objOppToUpdate = new Opportunity(Id = objOpp.Id);
                objOppToUpdate .Total_Account_Manager__c = MapIdOppTosumAcMngr.containsKey(objOpp.Id) ? MapIdOppTosumAcMngr.get(objOpp.Id) : 0;
                objOppToUpdate .Total_Channel_Manager__c = MapIdOppTosumChMgnr.containsKey(objOpp.Id) ? MapIdOppTosumChMgnr.get(objOpp.Id) : 0;
                
                lstOppToUpdate.add(objOppToUpdate );
            
                system.debug('====objOppToUpdate===='+objOppToUpdate);
            }
                if(!lstOppToUpdate.isEmpty())
                    
                    update lstOppToUpdate;         
        }
         //finish Method
                global void finish(Database.BatchableContext BC){
                    
                }
}

Thanks in Advance
Another list index ouf of bounds error encountered by an admin. The other posts aren't helping me. The purpose of my code is to chain Billing Schedule records together with with a self lookup based on a Date field. This will allow me to write validations to prevent certain actions until actions on the previous Billing Schedule record have been fulfilled. 

After thinking it though, I've determined that I have to use a custom sort for sobjects. I simply followed an example in salesforce docs on how to write a wrapper class that does this, and it appears to be working fine with the test class, but I'm getting a List Index out of bounds error when try it through the UI. 

I'm stuck because alll of my system.debugs look fine. For example, if my test has 8 Billing Schedule records then I get List index out of bounds:8 but the system debugs show that I'm only counting and retrieving from the list for 0 to 8. So, can anyone see how I'm going out of bounds? 
 
public class sortBillingSchedule {

    public static void populatePrevSched(String PrjId) {
        List<Billing_Schedule__c> bss = new List<Billing_Schedule__c>();
        List<BillingScheduleWrapper> bsList = new List<BillingScheduleWrapper>();
        Integer count = 0;
        
        for(Billing_Schedule__c bs : [select Id, Billing_Date__c, Previous_Billing_Schedule__c  from Billing_Schedule__c where Project__c = :PrjId]) {
            bsList.add(new BillingScheduleWrapper(bs));
        }
        bsList.sort();
        system.debug('======bsList '+bsList);
        while(count <= bsList.size()) {
           system.debug('========== count '+count+' ============ size'+bsList.size());
            If(count > 0) {
            	Billing_Schedule__c bs1 = bsList.get(count).bs;
            	bs1.Previous_Billing_Schedule__c = bsList.get(count - 1).bs.Id;
            	bss.add(bs1);
            }
            count++;
        }
        update bss;
        
    }
}

 
how can i conver exception catch block of this method in my test class

public static Boolean checkFaultAnalysis(String stockingRecordId,String mmId){
        Boolean faultAnalysisFlag = false;
        try{
            if(!String.IsEmpty(stockingRecordId) && !String.isEmpty(mmId)){
                
                List<ICS_WR_Customer_Warranty_Config_Matrix__c> faultMatrix = [SELECT id,Name,RecordTypeId FROM ICS_WR_Customer_Warranty_Config_Matrix__c WHERE ICS_WR_Stocking__c=:stockingRecordId AND ICS_WR_MMID__r.Name=:mmId AND RecordTypeId=:Label.ICS_WR_Fault_Analysis_RT_ID AND ICS_WR_Inactive__c = false];
                System.debug('faultMatrix ='+faultMatrix );
                if(faultMatrix!=null && faultMatrix.size()>0)
                    faultAnalysisFlag = true;
            }
        }catch(Exception e){
            System.Debug(e.getMessage());
            ApexPages.addMessages(e);
            String strInvocationID ='ICS_WR_Warranty_CreateExtension'+UserInfo.getUserId() + '_' + system.now().formatGmt('yyyyMMddkkmmssSS')
                + '_' + String.valueOf((Math.random() * 10).round()).leftpad(3,'0');
            Core_Log_Entry.logEntryWithException(strInvocationID,System.Label.ICS_WR_logging_Scope,'ICS_WR_Warranty_CreateExtension__checkFaultAnalysis','Error',e.getMessage(),'',e);
        }
        return faultAnalysisFlag;
    }
Hello friends
I am getting the error " INSUFFICIENT_ACCESS_OR_READONLY" when I execute apex code from trigger and the logic performs an DML operation.
I went through several posts to understand this error I understood that in the context of current user not having permission to perform edit on the object is resulting in this error.

The code was written by another user with 'WITH SHARING" keyword and also he has written as test class.
I checked with sysadmin so I do not have permissions to perform any edit on the said object.


My question is how do I resolve this error.

A) Can I actually remove the "WITH SHARING" keyword and then run the code from my login ?
B) In test class can I remove the option of 'WITHOUT SHARING"?
C) Also Pls lt me know how system.RunAs() works in the above context.
D) as of now this code is not deployed, so once it is deployed if this error occurs pls explain how to to resolve

I really hope I am clear.
Thanks
vandana R