• sfdc-admin-sm
  • NEWBIE
  • 10 Points
  • Member since 2013

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 10
    Questions
  • 8
    Replies
Hello,

I wrote the trigger code below and it works fine. However I feel it can be optimized better to follow best practices. Can you please review it and let me know what enhancements I could have used?

I know 1 best practice is that I shouldn't write all this logic in Trigger but instead use a helper class and let the Trigger call that help class. Any other improvements? Please provide code samples if possible. I am trying to learn.

Thanks in advance...
//Trigger that updates the AnnualAmount Account field based on the most recent Opportunity's AnnualAmount associated with the Account where the Opportunity Owner is not the test user and //AnnualAmount is > $0.

trigger UpdateAnnualAmountAcct on Opportunity (after insert, after update) {
    
    list<Opportunity> lstOpp = new list<Opportunity>();
    
    for(Opportunity o : Trigger.new){
        if(o.AnnualAmount__c > 0 && o.OwnerId != '00580000003mBZb'){ //id of test user
        lstOpp.add(o);
        }     
    }
    
    list<Opportunity> mostRecentOppty = new list<Opportunity>();
    
    if(lstOpp != NULL){
        mostRecentOppty = [SELECT Id, CloseDate, AnnualAmount__c, AccountId FROM Opportunity WHERE Id IN : lstOpp ORDER BY CloseDate DESC LIMIT 1];       
    }
    
    list<Account> acctToUpdate = new list<Account>();
    
    for(Opportunity o : lstOpp){
        Account a = new Account();
        a.Id = o.AccountId;
        a.AnnualAmount__c = o.AnnualAmount__c;
        acctToUpdate.add(a);
    }
    update acctToUpdate;
}

 
Hello,

I am getting the error System.TypeException: Invalid decimal: null after running a test class. The test class (and others) that is failing is inserting an Account and the error is referencing the line a.Annualized_ACV__c = Decimal.valueOf(str); in the snippet of my before update Account trigger code below:

for(Account a : Trigger.new){         
    for (AggregateResult ar : lstOpptyAnnualACV){             
       if(lstOpptyAnnualACV != NULL){                   
          String str = '' + lstOpptyAnnualACV[0].get('sum');                 
          a.Annualized_ACV__c = Decimal.valueOf(str);                           
       }
    }


Any advice on how to fix this? Note the trigger code is working fine and is updating the Annualized_ACV__c correctly through the UI. The error occurs when running test classes that are inserting Accounts

Thanks
Hello,

I am getting the following error: Invalid foreign key relationship: License__c.Account__c at line 21 column 23 for my code: mapAcct.put(ObjLic.Account__c.Id, ObjLic.Account__c); in the below trigger code snippet. What should the correct code be to add an Acciount Id and Account record to the mapAcct? The License__c custom object has a lookup relationship to Accounts.

My code:

Set<Id> licIds = new Set<Id>();
   
    for(License__c l : Trigger.new){
        if(l.Expiration_Date__c > Date.Today()){
            licIds.add(l.Id);
        }
    }
   
System.debug('<<<licIds size = ' +licIds.size());

Map<Id, Account> mapAcct;
   
    if(licIds != NULL){
       for(License__c ObjLic : licIds){
          mapAcct.put(ObjLic.Account__c.Id, ObjLic.Account__c);   
       }
    }

Hello,

 

I'm getting error: Too many SOQL queries: 101 Trigger.UpdateTableLink: line 16, column 1. Line 16 in my code is

 

 List<Country_Codes__C> ICC = [Select id, Country_Name__c from Country_codes__C Where Country_Name__c in :CountryNames ];  

 

Below is my full code. Please advise on how to fix with specific code examples.

 

trigger UpdateTableLink on Account (before insert, before update) {
 
   Set<String> CountryNames = new Set<String>();

    for (Account a : Trigger.new){
      if (a.ShippingCountry == NULL){
      a.ShippingCountry = 'NONE';   
        }

    if (a.ShippingCountry <> NULL){
      CountryNames.add((a.ShippingCountry.toUpperCase()));   
        }}

    List<Country_Codes__C> CC = [Select id, Country_Name__c from Country_codes__C Where Country_Name__c in :CountryNames ];  

    Map <String, ID> map1 = new Map<String, ID>();
    for (Country_Codes__c countryRecord: CC) {
        map1.put(countryRecord.Country_Name__c, countryRecord.Id);
    }

    for (Account a : Trigger.new)
 if (a.ShippingCountry <> NULL){
      {   
        a.CountryCodesLink__c = map1.get(a.ShippingCountry.toUppercase());

      }  }
}

 

Hello,

 

I need help with getting 100% coverage for my trigger below. Current code coverage is 37% (3/8)

 

trigger RunRules on Lead (After update) {
   string fname = UserInfo.getFirstName();
    for (Lead lead : Trigger.new) {
       if (fname == 'Fred' && (lead.L_Rate__c == 'A' ||lead.L_Rate__c == 'B') && LeadAssignRuleUtil.firstTime && Lead.ISConverted == False && Lead.OwnerID != '00G70000001ifuqFWE' ) {
            Database.DMLOptions dmo = new Database.DMLOptions();
            dmo.assignmentRuleHeader.useDefaultRule= true;
            lead.setOptions(dmo);
            LeadAssignRuleUtil.firstTime = false;
            Database.Update(lead);
       }
    }
}

 

My Question:

 

How do I know what Test Class is doing the code coverage for my Trigger? When I look under Setup -> Develop -> Apex Classes, I don't see any classes with a name close to or similar to the associated trigger name "RunRules" but I know it is getting partially covered (Current code coverage is 37%) by an unknown test class. 

Hello,

 

I am trying to assign a Region value to an Account based on the Shipping Address of the Account. My Case function (sample below) works when it does not go over the 3900 character limit:

 

CASE(ShippingCountry,
"Afghanistan", "EMEA",
"Åland Islands", "EMEA",
"Albania", "EMEA",
"Algeria", "EMEA",
"American Samoa", "APAC",
...)

 

However, with over 300 different countries, the complete function is over 8000 characters and will not save. How would I optimize this formula to work for all 300 different countries and keep the same functionality?

 

Please respond with specific formulas to help.

 

Thanks.

Hello All,

 

I currently have a working workflow formula as follows:

 

IF(Product2.Name = "13-Credits" && Quantity = 1, 13, 
IF(Product2.Name = "13-Credits" && Quantity = 2, 13 * 2, 
IF(Product2.Name = "13-Credits" && Quantity = 3, 13 * 3, 

)))

 

I know I can either keep this formula as is or use a Case function. However, if I need to 100 different Quantity values, this will require me to have 100 different lines on the formula for each Quantity value. Even worst if I have 10 different Product2.Name requiring 100 different Quantity variations, the number of lines in this formula can easily = 10 * 100 = 1000 lines!

 

Is there any way I can reduce the number of lines in the this formula? 

 

Please respond with specific working formula examples.

 

Thanks,

Hello,

 

I need some help.

 

I am trying to automatically populate a date fieId (Expiration_Date__c) by a workflow field update based on multiple values of the Term field (Term__c)

 

So for example,

 

If Term__c  = 1 then the Expiration_Date__c = Start_Date__c + 1 month

If Term__c  = 6 then the Expiration_Date__c = Start_Date__c + 6 months

If Term__c  = 12 then the Expiration_Date__c = Start_Date__c + 12 months

If Term__c  = 24 then the Expiration_Date__c = Start_Date__c + 24 months

 

Please help me create this formula for the workflow field update.

 

Thanks,

Hello all,

 

I am getting the error below in my Lead trigger

 

Non-selective query against large object type (more than 100000 rows). Consider an indexed filter.

 

I am guessing my SOQL query in the list is returning too many results. It is:

 

List<CampaignMember> listCampaignMember = [Select Id,CampaignId,LeadId From CampaignMember Where LeadId IN:setLeadId];

 

I have read that a solution involves making one of the CampaignMember fields an "External ID" but don't know which one to do this for.

 

Any ideas on how to optimize my SOQL query or what field I should make an External ID on the CampaignMember object?

 

Thanks!

 

 

Hello all,

 

I have a Lead validation rule using an IF statement that works as follows:

 

IF(AND(ISPICKVAL(Status, "Junk") , ISPICKVAL(junk_reason__c , "") ),TRUE, FALSE)

 

This IF statement works fine for checking 2 picklist values of 2 different lead picklist fields. However, I want to add another IF condition such as:

 

IF(AND(ISPICKVAL(Status, "Junk") , ISPICKVAL(junk_reason__c , "Bad Email") ),TRUE, FALSE)

 

How would I combine these 2 IF statements or merge into a Case function? The idea is if either of these 2 IF statements evaluate to True then the Lead Validation rule error message will display.

 

Thanks.

Hello,

I wrote the trigger code below and it works fine. However I feel it can be optimized better to follow best practices. Can you please review it and let me know what enhancements I could have used?

I know 1 best practice is that I shouldn't write all this logic in Trigger but instead use a helper class and let the Trigger call that help class. Any other improvements? Please provide code samples if possible. I am trying to learn.

Thanks in advance...
//Trigger that updates the AnnualAmount Account field based on the most recent Opportunity's AnnualAmount associated with the Account where the Opportunity Owner is not the test user and //AnnualAmount is > $0.

trigger UpdateAnnualAmountAcct on Opportunity (after insert, after update) {
    
    list<Opportunity> lstOpp = new list<Opportunity>();
    
    for(Opportunity o : Trigger.new){
        if(o.AnnualAmount__c > 0 && o.OwnerId != '00580000003mBZb'){ //id of test user
        lstOpp.add(o);
        }     
    }
    
    list<Opportunity> mostRecentOppty = new list<Opportunity>();
    
    if(lstOpp != NULL){
        mostRecentOppty = [SELECT Id, CloseDate, AnnualAmount__c, AccountId FROM Opportunity WHERE Id IN : lstOpp ORDER BY CloseDate DESC LIMIT 1];       
    }
    
    list<Account> acctToUpdate = new list<Account>();
    
    for(Opportunity o : lstOpp){
        Account a = new Account();
        a.Id = o.AccountId;
        a.AnnualAmount__c = o.AnnualAmount__c;
        acctToUpdate.add(a);
    }
    update acctToUpdate;
}

 
Hello,

I am getting the error System.TypeException: Invalid decimal: null after running a test class. The test class (and others) that is failing is inserting an Account and the error is referencing the line a.Annualized_ACV__c = Decimal.valueOf(str); in the snippet of my before update Account trigger code below:

for(Account a : Trigger.new){         
    for (AggregateResult ar : lstOpptyAnnualACV){             
       if(lstOpptyAnnualACV != NULL){                   
          String str = '' + lstOpptyAnnualACV[0].get('sum');                 
          a.Annualized_ACV__c = Decimal.valueOf(str);                           
       }
    }


Any advice on how to fix this? Note the trigger code is working fine and is updating the Annualized_ACV__c correctly through the UI. The error occurs when running test classes that are inserting Accounts

Thanks
Wrote a very simple VF Page and Controller to show the Accounts that voted on certain Ideas. Here is the controller. Just aggregates the Up and Down votes on the Idea excluded internal votes. Pretty straight forward.

public class IdeaVotesByAccountController {

    public Idea thisIdea                                            {get;set;}
    public list<AggregateResult> upResults                          {get;set;}
    public list<AggregateResult> downResults                        {get;set;}

    public IdeaVotesByAccountController() {

        thisIdea = [Select Id, Title 
                    From Idea 
                    Where Id =: system.currentPageReference().getParameters().get('ideaid')];

        upResults = [SELECT Count(Id) Votes, CreatedBy.Contact.Account.Name Name
                    From Vote Where ParentId =: thisIdea.Id And Type = 'up' And CreatedBy.Contact.Account.Name != 'My Company Name' And CreatedBy.Contact.Account.Name != null
                    Group By CreatedBy.Contact.Account.Name 
                    Order By Count(Id) desc, CreatedBy.Contact.Account.Name];

        downResults = [SELECT Count(Id) Votes, CreatedBy.Contact.Account.Name Name
                    From Vote Where ParentId =: thisIdea.Id And Type = 'down' And CreatedBy.Contact.Account.Name != 'My Company Name' And CreatedBy.Contact.Account.Name != null
                    Group By CreatedBy.Contact.Account.Name 
                    Order By Count(Id) desc, CreatedBy.Contact.Account.Name];

    }

    public PageReference returnToIdea() {

        PageReference pg = new PageReference('/' + thisIdea.Id);
        pg.setRedirect(true);
        return pg;

    }
}

My problem is coming when trying to write a unit test. When I say that we are excluding internal votes, basically, we are only counting portal user votes, from portal users that do not have a company name of my company name. So in order to test, I need to be able to test all 3 scenarios scenarios
  1. a vote from within the SF UI, not through the portal (No Issue)
  2. a vote by a portal user outside of my company (ISSUE)
  3. a vote by a portal user inside of my company (ISSUE)

The issue comes with trying to create a vote from a portal user. Here is my test code that I have. The first test method works fine, the second method is throwing an error

@isTest
private class IdeaVotesByAccountControllerTest {

    private static final Profile nonPortalProf = [SELECT Id FROM Profile WHERE Name = 'System Administrator'];
    private static final Profile portalProf = [SELECT Id FROM Profile WHERE Name Like '%portal%' limit 1];
    private static final Account a = TestClassObjectUtility2.accountCreator('Test Account');
    private static final Contact con = TestClassObjectUtility2.contactCreator(a.Id, 'Joe', 'Schmoe');
    public static final Community zone = [Select Id From Community Limit 1];
    public static final PageReference pg = Page.IdeaVotesByAccount;
    public static final User nonPortalUser = TestClassObjectUtility2.userCreator(true, nonPortalProf);
    public static final User portalUser;
    public static IdeaVotesByAccountController controller;

    static {
        portalUser = TestClassObjectUtility2.userCreator(false, portalProf);
        portalUser.ContactId = con.Id;
        insert portalUser;
    }
    //WORKS FINE
    static testmethod void BaseTestNonPortalUser() {

        Idea myIdea = TestClassObjectUtility2.ideaCreator(true, 'Title', 'Body', zone.Id);
        myIdea = [Select Id From Idea Where Id =: myIdea.Id];

        pg.getParameters().put('ideaid', myIdea.id);
        Test.setCurrentPage(pg);

        controller = new IdeaVotesByAccountController();

        system.assertEquals(0, controller.upResults.size());
        system.assertEquals(0, controller.downResults.size());

        system.runAs(nonPortalUser){
            Vote v = TestClassObjectUtility2.voteCreator(true, myIdea.Id, 'up');
        }

        controller = new IdeaVotesByAccountController();
        system.assertEquals(0, controller.upResults.size());

    }
    //FAILS
    static testmethod void BaseTestPortalUser() {

        Idea myIdea = TestClassObjectUtility2.ideaCreator(true, 'Title', 'Body', zone.Id);

        pg.getParameters().put('ideaid', myIdea.id);
        Test.setCurrentPage(pg);

        controller = new IdeaVotesByAccountController();

        system.assertEquals(0, controller.upResults.size());
        system.assertEquals(0, controller.downResults.size());

        system.runAs(portalUser){
             //THIS LINE IS FAILING
             Vote v = TestClassObjectUtility2.voteCreator(true, myIdea.Id, 'up');
        }

        controller = new IdeaVotesByAccountController();
        system.assertEquals(1, controller.upResults.size());

    }
}

It throws the error on the line where I am trying to insert the Vote object. The error is shown below

User-added image

System.DmlException: Insert failed. First exception on row 0; first error: COMMUNITY_NOT_ACCESSIBLE, You do not have permission to access the zone that this entity belongs to. You must be given permission to the zone before you can access this entity.: [ParentId]

So apparently the portal user needs permission to the community. The issue is I have searched around for documentation but I can't seem to find out how to do this. Has anyone seen this before. How can I overcome this error???

Any help is greatly appreciated.

Hello,

 

I need help with getting 100% coverage for my trigger below. Current code coverage is 37% (3/8)

 

trigger RunRules on Lead (After update) {
   string fname = UserInfo.getFirstName();
    for (Lead lead : Trigger.new) {
       if (fname == 'Fred' && (lead.L_Rate__c == 'A' ||lead.L_Rate__c == 'B') && LeadAssignRuleUtil.firstTime && Lead.ISConverted == False && Lead.OwnerID != '00G70000001ifuqFWE' ) {
            Database.DMLOptions dmo = new Database.DMLOptions();
            dmo.assignmentRuleHeader.useDefaultRule= true;
            lead.setOptions(dmo);
            LeadAssignRuleUtil.firstTime = false;
            Database.Update(lead);
       }
    }
}

 

My Question:

 

How do I know what Test Class is doing the code coverage for my Trigger? When I look under Setup -> Develop -> Apex Classes, I don't see any classes with a name close to or similar to the associated trigger name "RunRules" but I know it is getting partially covered (Current code coverage is 37%) by an unknown test class. 

Hello,

 

I need some help.

 

I am trying to automatically populate a date fieId (Expiration_Date__c) by a workflow field update based on multiple values of the Term field (Term__c)

 

So for example,

 

If Term__c  = 1 then the Expiration_Date__c = Start_Date__c + 1 month

If Term__c  = 6 then the Expiration_Date__c = Start_Date__c + 6 months

If Term__c  = 12 then the Expiration_Date__c = Start_Date__c + 12 months

If Term__c  = 24 then the Expiration_Date__c = Start_Date__c + 24 months

 

Please help me create this formula for the workflow field update.

 

Thanks,

Hello all,

 

I have a Lead validation rule using an IF statement that works as follows:

 

IF(AND(ISPICKVAL(Status, "Junk") , ISPICKVAL(junk_reason__c , "") ),TRUE, FALSE)

 

This IF statement works fine for checking 2 picklist values of 2 different lead picklist fields. However, I want to add another IF condition such as:

 

IF(AND(ISPICKVAL(Status, "Junk") , ISPICKVAL(junk_reason__c , "Bad Email") ),TRUE, FALSE)

 

How would I combine these 2 IF statements or merge into a Case function? The idea is if either of these 2 IF statements evaluate to True then the Lead Validation rule error message will display.

 

Thanks.