• darcusmietz
  • NEWBIE
  • 10 Points
  • Member since 2012

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 4
    Questions
  • 4
    Replies
I have a trigger on a custom object that creates a new opportunity. Everything is working perfectly, except the Market Developer field is showing up with the user' unique IDs, rather than their names. I think I need to create a map and use a select statement from the user object to return the name value, but I'm unsure how to do this. Could you please assist me? I bolded the line that needs to return the name instead of ID.

trigger MDwinning2 on MD_Meeting__c (after update) {
List <Opportunity> oppToInsert = new List <Opportunity> ();
    for (MD_Meeting__c m : Trigger.new) {
        MD_Meeting__c oldMeet = Trigger.oldMap.get(m.Id);
        if (oldMeet.SAL__c != m.SAL__c) {      
        Opportunity o = new Opportunity ();  
        o.OwnerId = m.Sales_Director__c;
        o.Name = m.Name;
        o.StageName = 'Generate Opportunity';
        o.Market_Developer__c = m.Market_Developer__c;
        o.AccountId = m.Account__c;
        o.Type = 'Sales - New Business';
    o.CloseDate = System.Today()+150;
    o.MeetingLookup__c = m.Id;
        oppToInsert.add(o);
        }//end if
    }//end for o
//try {
     insert oppToInsert;
//    } catch (system.Dmlexception e) {
//       system.debug (e);
//    }
}

I'm having trouble writing a text class to cover the AcctOwner Map of my trigger. I'm missing coverage on the boldface lines. Is there something special I need to do in order to get coverage for a map and key?

 

trigger UpdateContactOwnerFromAccount on Account (after update) {
	
	map<Id,Id> AccOwnerMap = new map<Id,Id>();
	
	for(Account a : trigger.new) {
		if(a.OwnerId != trigger.oldMap.get(a.Id).OwnerId) {
			AccOwnerMap.put(a.Id,a.OwnerId);
		}
	}
	
	list<Contact> ContactsToUpdate = new list<Contact>();
	
	for(Contact c: [select Id, OwnerId, AccountId 
	from Contact where AccountId IN :AccOwnerMap.keySet()]) {
		if(AccOwnerMap.containsKey(c.AccountId)) {
			Id AccOwnerId = AccOwnerMap.get(c.AccountId);
			c.OwnerId = AccOwnerId;
			ContactsToUpdate.add(c);
		}
	}
	
	if(ContactsToUpdate.size() > 0) {
		update ContactsToUpdate;
	}

}

 

I'd like to create a workflow that emails a lead owner after 24, 48, an 72 hours of no activity. The stipulation is that I would like these time durations to be business hours rather than standard hours. Has anyone done this before? My initial thoughts are to create three custom fields on the Lead which calculate those times. 

 

Does anyone know of a better way to do it?

I am in need of help with a Test class for my trigger. I'm getting zero test code coverage, because I am an absolute newbie at Apex. 

 

My first question is, do you recommend reading the entire documentation online, or are there any decent books out there regarding Apex code?

 

My second question is, How can I increase my code coverage on the test class below?

 

This is the trigger: 

trigger UpdateContactLeadSource on Opportunity (before update) {
    /*  delete this first part of code and in the query instead of ":oppsToFill" bind to ":trigger.new" or
        ":trigger.newMap.keyset()".
    */
    Set<Id> oppsToFill = new Set<Id>();
    
    for(Opportunity o : trigger.new){
        if(o.LeadSource <> null) {
           oppsToFill.add(o.Id);
      }
    }

    // Now we'll select all possible contacts wasting only 1 query.
    if(!oppsToFill.isEmpty()){
        List<OpportunityContactRole> roles = [SELECT OpportunityId, Contact.Name, Contact.LeadSource
            FROM OpportunityContactRole
            WHERE isPrimary = true AND Contact.LeadSource != null AND OpportunityId IN :oppsToFill];

        if(!roles.isEmpty()){
            for(OpportunityContactRole ocr : roles){
                Opportunity oppToBeFilled = trigger.newMap.get(ocr.OpportunityId);
                System.debug('Changing lead source on ' + oppToBeFilled.Name + ' from ' + oppToBeFilled.LeadSource + ' to ' + ocr.Contact.LeadSource + ' (thx to ' + ocr.Contact.Name + ' being the Primary Contact).');
                oppToBeFilled.LeadSource = ocr.Contact.LeadSource;
            }
        }
    }
   
    // NEEDS TO INCLUDE IF STATEMENT IN CASE NO PRIMARY CONTACT IS LISTED
}

 

This is the Test Class I have so far 

@isTest (SeeAllData = true) 
public with sharing class TestPrimaryContactLeadSrc {

 static testMethod void TestPrimaryContactLeadSrc() 
      {  
       		   Set<Id> oppsToFill = new Set<Id>();
       		   Contact newContact = new Contact( lastname= 'Testerson',
                                        LeadSource = 'Cold Call'
                                       // WhatId = newOpp.id 
                                        );                
                insert newContact;
       		
       		
               Opportunity o = new Opportunity (Name = 'testopp',
               										Set_up_Fee__c = 10, 
               										Term__c = 1,
               										CARR__c = 1,
               										StageName = 'Meeting',
               										ForecastCategoryName = 'Pipeline',
               										CloseDate = date.today(),
               										Type = 'Upsell',
               										LeadSource = 'Sales'
               										//WhatId = Contact.Id
               										);
               									
               insert o;
               
               
               OpportunityContactRole ocr=new OpportunityContactRole(Role='Decision Maker',OpportunityId=o.Id,ContactId=NewContact.Id,Isprimary=true);
     insert ocr;
               
               
                Task newTask = new Task(Description = 'Survey Transaction',
                                        Priority = 'Normal', 
                                        Status = 'Inbound Email', 
                                        Subject = 'Other', 
                                        IsReminderSet = true, 
                                        ReminderDateTime = System.now()+1,
                                        WhatId = o.id 
                                        );                
                insert newTask;
                

                
    }
    
}

 

I'm having trouble writing a text class to cover the AcctOwner Map of my trigger. I'm missing coverage on the boldface lines. Is there something special I need to do in order to get coverage for a map and key?

 

trigger UpdateContactOwnerFromAccount on Account (after update) {
	
	map<Id,Id> AccOwnerMap = new map<Id,Id>();
	
	for(Account a : trigger.new) {
		if(a.OwnerId != trigger.oldMap.get(a.Id).OwnerId) {
			AccOwnerMap.put(a.Id,a.OwnerId);
		}
	}
	
	list<Contact> ContactsToUpdate = new list<Contact>();
	
	for(Contact c: [select Id, OwnerId, AccountId 
	from Contact where AccountId IN :AccOwnerMap.keySet()]) {
		if(AccOwnerMap.containsKey(c.AccountId)) {
			Id AccOwnerId = AccOwnerMap.get(c.AccountId);
			c.OwnerId = AccOwnerId;
			ContactsToUpdate.add(c);
		}
	}
	
	if(ContactsToUpdate.size() > 0) {
		update ContactsToUpdate;
	}

}

 

I am in need of help with a Test class for my trigger. I'm getting zero test code coverage, because I am an absolute newbie at Apex. 

 

My first question is, do you recommend reading the entire documentation online, or are there any decent books out there regarding Apex code?

 

My second question is, How can I increase my code coverage on the test class below?

 

This is the trigger: 

trigger UpdateContactLeadSource on Opportunity (before update) {
    /*  delete this first part of code and in the query instead of ":oppsToFill" bind to ":trigger.new" or
        ":trigger.newMap.keyset()".
    */
    Set<Id> oppsToFill = new Set<Id>();
    
    for(Opportunity o : trigger.new){
        if(o.LeadSource <> null) {
           oppsToFill.add(o.Id);
      }
    }

    // Now we'll select all possible contacts wasting only 1 query.
    if(!oppsToFill.isEmpty()){
        List<OpportunityContactRole> roles = [SELECT OpportunityId, Contact.Name, Contact.LeadSource
            FROM OpportunityContactRole
            WHERE isPrimary = true AND Contact.LeadSource != null AND OpportunityId IN :oppsToFill];

        if(!roles.isEmpty()){
            for(OpportunityContactRole ocr : roles){
                Opportunity oppToBeFilled = trigger.newMap.get(ocr.OpportunityId);
                System.debug('Changing lead source on ' + oppToBeFilled.Name + ' from ' + oppToBeFilled.LeadSource + ' to ' + ocr.Contact.LeadSource + ' (thx to ' + ocr.Contact.Name + ' being the Primary Contact).');
                oppToBeFilled.LeadSource = ocr.Contact.LeadSource;
            }
        }
    }
   
    // NEEDS TO INCLUDE IF STATEMENT IN CASE NO PRIMARY CONTACT IS LISTED
}

 

This is the Test Class I have so far 

@isTest (SeeAllData = true) 
public with sharing class TestPrimaryContactLeadSrc {

 static testMethod void TestPrimaryContactLeadSrc() 
      {  
       		   Set<Id> oppsToFill = new Set<Id>();
       		   Contact newContact = new Contact( lastname= 'Testerson',
                                        LeadSource = 'Cold Call'
                                       // WhatId = newOpp.id 
                                        );                
                insert newContact;
       		
       		
               Opportunity o = new Opportunity (Name = 'testopp',
               										Set_up_Fee__c = 10, 
               										Term__c = 1,
               										CARR__c = 1,
               										StageName = 'Meeting',
               										ForecastCategoryName = 'Pipeline',
               										CloseDate = date.today(),
               										Type = 'Upsell',
               										LeadSource = 'Sales'
               										//WhatId = Contact.Id
               										);
               									
               insert o;
               
               
               OpportunityContactRole ocr=new OpportunityContactRole(Role='Decision Maker',OpportunityId=o.Id,ContactId=NewContact.Id,Isprimary=true);
     insert ocr;
               
               
                Task newTask = new Task(Description = 'Survey Transaction',
                                        Priority = 'Normal', 
                                        Status = 'Inbound Email', 
                                        Subject = 'Other', 
                                        IsReminderSet = true, 
                                        ReminderDateTime = System.now()+1,
                                        WhatId = o.id 
                                        );                
                insert newTask;
                

                
    }
    
}

 

Hello,

 

I have created 3 custom user look-up fields at the Account level to represent the 3 roles in the Account Team.  I have a trigger that is supposed to update the Account Team records when the Account is updated (see below).  The trigger saves fine, but when I edit the Account with values in the 3 custom fields, I get the following error:

 

Error:Apex trigger AccountTeamChanges caused an unexpected exception, contact your administrator: AccountTeamChanges: execution of AfterUpdate caused by: System.DmlException: Insert failed. First exception on row 0; first error: INVALID_ACCESS_LEVEL, : AccountAccessLevel, OpportunityAccessLevel, CaseAccessLevel (Account, Opportunity, Case Levels, Con Levels (Read, Read, Read, Read) are below organization levels (Read, Read, ReadEditTransfer, ControlledByParent)): [AccountAccessLevel, OpportunityAccessLevel, CaseAccessLevel]: Trigger.AccountTeamChanges: line 199, column 1

 

My Triger code is as follows:

 

trigger AccountTeamChanges on Account(after insert, after update)
{
    //list to hold new account team members
     List<AccountTeamMember> acctMembers = new List<AccountTeamMember>();
     
     //list to hold new account sharing rules
     List<AccountShare> acctSharingRules = new List<AccountShare>();
     
     //misc
     Set<String> rmMemberAccts = new Set<String>();
     Map<ID, ID> AccountTeamMap = new Map<ID, ID>();
    
     //iterate through records to find update Account Team values
     for(Account a : Trigger.new)
     {
        //new Account - Client Advisor
        if(Trigger.isInsert && a.Client_Advisor__c != null)
        {
            AccountTeamMember ca = new AccountTeamMember();
            ca.AccountId = a.Id;
            ca.TeamMemberRole = 'Client Advisor';
            ca.UserId = a.Client_Advisor__c;
            acctMembers.add(ca);
            
            AccountShare caSharingRule = new AccountShare();
            caSharingRule.AccountId = a.Id;
            caSharingRule.OpportunityAccessLevel = 'Read';
            caSharingRule.CaseAccessLevel = 'Read';
            caSharingRule.AccountAccessLevel = 'Read';
            caSharingRule.UserOrGroupId = a.Client_Advisor__c;
            acctSharingRules.add(caSharingRule);
        }

        //new Account - Market Director
        if(Trigger.isInsert && a.Market_Director__c != null)
        {
            AccountTeamMember md = new AccountTeamMember();
            md.AccountId = a.Id;
            md.TeamMemberRole = 'Market Director';
            md.UserId = a.Market_Director__c;
            acctMembers.add(md);
            
            AccountShare mdSharingRule = new AccountShare();
            mdSharingRule.AccountId = a.Id;
            mdSharingRule.OpportunityAccessLevel = 'Read';
            mdSharingRule.CaseAccessLevel = 'Read';
            mdSharingRule.AccountAccessLevel = 'Edit';
            mdSharingRule.UserOrGroupId = a.Market_Director__c;
            acctSharingRules.add(mdSharingRule);
        }

        //new Account - Industry Manager
        if(Trigger.isInsert && a.Industry_Manager__c != null)
        {
            AccountTeamMember im = new AccountTeamMember();
            im.AccountId = a.Id;
            im.TeamMemberRole = 'Industry Manager';
            im.UserId = a.Industry_Manager__c;
            acctMembers.add(im);
            
            AccountShare imSharingRule = new AccountShare();
            imSharingRule.AccountId = a.Id;
            imSharingRule.OpportunityAccessLevel = 'Read';
            imSharingRule.CaseAccessLevel = 'Read';
            imSharingRule.AccountAccessLevel = 'Read';
            imSharingRule.UserOrGroupId = a.Industry_Manager__c;
            acctSharingRules.add(imSharingRule);
        }

        //updated Account
        else if(Trigger.isUpdate)
        {
            //old Accoount record
            Account oldAcct = Trigger.oldMap.get(a.Id);
            
            //check to see if the team values have changed and verifies the
            //new values are not null
            if(oldAcct.Client_Advisor__c != a.Client_Advisor__c && a.Client_Advisor__c != null)
            {
                //add old Client Advisor to remove list if one exists
                if(oldAcct.Client_Advisor__c != null)
                {
                    rmMemberAccts.add(oldAcct.Id);
                    AccountTeamMap.put(oldAcct.Id, oldAcct.Client_Advisor__c);
                }
                
                //add new Client Advisor to account team and update sharing rules
                AccountTeamMember ca = new AccountTeamMember();
                ca.AccountId = a.Id;
                ca.TeamMemberRole = 'Client Advisor';
                ca.UserId = a.Client_Advisor__c;
                acctMembers.add(ca);
                
                AccountShare caSharingRule = new AccountShare();
                caSharingRule.AccountId = a.Id;
                caSharingRule.OpportunityAccessLevel = 'Read';
                caSharingRule.CaseAccessLevel = 'Read';
                caSharingRule.AccountAccessLevel = 'Read';
                caSharingRule.UserOrGroupId = a.Client_Advisor__c;
                acctSharingRules.add(caSharingRule);
            }
            else if(oldAcct.Client_Advisor__c != a.Client_Advisor__c && a.Client_Advisor__c == null)
            {
                rmMemberAccts.add(a.Id);
                AccountTeamMap.put(oldAcct.Id, oldAcct.Client_Advisor__c);
            }

            
            //check to see if the team values have changed and verifies the
            //new values are not null
            if(oldAcct.Market_Director__c != a.Market_Director__c && a.Market_Director__c != null)
            {
                //add old Market Director to remove list if one exists
                if(oldAcct.Market_Director__c != null)
                {
                    rmMemberAccts.add(oldAcct.Id);
                    AccountTeamMap.put(oldAcct.Id, oldAcct.Market_Director__c);
                }
                
                //add new Market Director to account team and update sharing rules
                AccountTeamMember md = new AccountTeamMember();
                md.AccountId = a.Id;
                md.TeamMemberRole = 'Market Director';
                md.UserId = a.Market_Director__c;
                acctMembers.add(md);
                
                AccountShare mdSharingRule = new AccountShare();
                mdSharingRule.AccountId = a.Id;
                mdSharingRule.OpportunityAccessLevel = 'Read';
                mdSharingRule.CaseAccessLevel = 'Read';
                mdSharingRule.AccountAccessLevel = 'Read';
                mdSharingRule.UserOrGroupId = a.Market_Director__c;
                acctSharingRules.add(mdSharingRule);
            }
            else if(oldAcct.Market_Director__c != a.Market_Director__c && a.Market_Director__c == null)
            {
                rmMemberAccts.add(a.Id);
                AccountTeamMap.put(oldAcct.Id, oldAcct.Market_Director__c);
            }

            
            //check to see if the team values have changed and verifies the
            //new values are not null
            if(oldAcct.Industry_Manager__c != a.Industry_Manager__c && a.Industry_Manager__c != null)
            {
                //add old Industry Manager to remove list if one exists
                if(oldAcct.Industry_Manager__c != null)
                {
                    rmMemberAccts.add(oldAcct.Id);
                    AccountTeamMap.put(oldAcct.Id, oldAcct.Industry_Manager__c);
                }
                
                //add new Industry Manager to account team and update sharing rules
                AccountTeamMember im = new AccountTeamMember();
                im.AccountId = a.Id;
                im.TeamMemberRole = 'Industry Manager';
                im.UserId = a.Market_Director__c;
                acctMembers.add(im);
                
                AccountShare imSharingRule = new AccountShare();
                imSharingRule.AccountId = a.Id;
                imSharingRule.OpportunityAccessLevel = 'Read';
                imSharingRule.CaseAccessLevel = 'Read';
                imSharingRule.AccountAccessLevel = 'Read';
                imSharingRule.UserOrGroupId = a.Industry_Manager__c;
                acctSharingRules.add(imSharingRule);
            }
            else if(oldAcct.Industry_Manager__c != a.Industry_Manager__c && a.Industry_Manager__c == null)
            {
                rmMemberAccts.add(a.Id);
                AccountTeamMap.put(oldAcct.Id, oldAcct.Industry_Manager__c);
            }

        }
        
        //DML OPERATIONS
        //remove team members from account team if any exist
        if(rmMemberAccts.size() > 0)
        {
            List<AccountTeamMember> removeTeam = new List<AccountTeamMember>();
            for(AccountTeamMember atm : [SELECT Id, UserId, AccountId
            FROM AccountTeamMember
            WHERE (TeamMemberRole='Client Advisor' OR TeamMemberRole='Market Director' OR TeamMemberRole='Industry Manager') AND AccountId IN :rmMemberAccts])
            {
                if(atm.UserId == AccountTeamMap.get(atm.AccountId))
                    removeTeam.add(atm);
            }
            
            delete removeTeam;
        }
        
        system.debug('-->ACCOUNT MEMBERS: ' + acctMembers);
        //insert the new account team members if any exist
        if(acctMembers.size() > 0)
            insert acctMembers; //LINE 100
        
        //insert account sharing rules if any exist
        if(acctSharingRules.size() > 0)
            insert acctSharingRules;
     }
     
}

 

 

Can anyone help me understand why I am getting this error?  Thanks,

  • September 26, 2012
  • Like
  • 0

Hi,

 

This initial quesiton really dosn't have anything to do with Apex but if the answer is no then it will!

 

Is there a built in feature that allows the owner of contacts associated with an account to change with the owner of the acount?  I do not see that as an option in the change owner screen on accounts.  The issue is if a person leaves a department or company and the account is transfered to someone else then later they want to update the contacts associated with the account they can't because the previous employee owned the contacts!

 

So if there isn't a built in SFDC feature I am thinking of a VF page that has a look up field to all active users.  The admin selects a user then all that users contacts are pulled onto the list screen with checkbox's next to them.  The admin can select all or specific users then another pick list to select who will be the new owner is selected and finally a Transfer button to do the Apex work of changing the owner.

 

Now my apex / vf question(s).  At a higlevel I am thnking that I can have a top section with the two look up fields (FROM OWNER and TO OWNER) lets.  Next to the FROM OWNER I will have a button named Get Contacts and next to the TO OWNER I will have a button named Transfer..

 

Can I build a controller that I can use in a VF page as an extension and use the built in SFDC List capability that has the checkbox features?  If so can someone guide me a few examples hwo that is used.  I had one months ago but cannot seem to find it.