• Christan G 4
  • SMARTIE
  • 570 Points
  • Member since 2019

  • Chatter
    Feed
  • 17
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 180
    Replies
Hello,

There is an old trigger in our org that needs to be deactivated. However, the trigger's test class only has 65% code coverage. I did not write this code and do not have a background in development. Could anyone offer clear edits to make so that I can successfully deploy the deactivated trigger to production?

Trigger:
trigger AccountTrigger on Account (before delete, before insert, before update,after insert) {
    AccountTriggerHandler.execute(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap, 
                          Trigger.isInsert, Trigger.isUpdate, Trigger.isDelete, Trigger.isBefore, Trigger.isAfter);
    AccountTriggerHandler.executeLeadLink(Trigger.new,Trigger.old,Trigger.isUpdate,Trigger.isBefore,Trigger.isInsert,Trigger.isAfter);
}
The Class referenced in the trigger:
public with sharing class AccountTriggerHandler {
	
	static RecordType applicantRecordType;
	static Profile adminProfile;
	static {
		applicantRecordType = [Select Id From RecordType Where Name = 'Applicants' and sobjecttype = 'Account']; 
		adminProfile = [Select Id, Name From Profile Where Name = 'System Administrator'];
	}
	
	public static void execute(List<Account> newList, Map<Id, Account> newMap,
                               List<Account> oldList, Map<Id, Account> oldMap,
                               Boolean isInsert, Boolean isUpdate, Boolean isDelete, Boolean isBefore, Boolean isAfter) {    
    	List<Account> accList = new List<Account>();
    	if (isDelete) {
    		for (Account acc : oldList)
    			accList.add(acc);
    	}
    	else {
    		for (Account acc : newList)
    			accList.add(acc);
    	}    	
    	for (Account acc : accList)	{
    		if (isBefore) {
	    		if (acc.RecordTypeId == applicantRecordType.Id && 
	    			System.Userinfo.getProfileId() != adminProfile.Id) {	    		
	    			acc.addError('Only System Administrators may create, edit, or delete Applicants');		
	    		}
    		}
    	}		                           	
    }
    
	public static Map<String,Lead> GetLeadsWithAccountEmailAddress(List<Account> accounts){
        Map<String,Lead> mappedLeads=new Map<String,Lead>();
        Set<String> accountEmails=new Set<String>();
        for(Account a:accounts){
			accountEmails.add(a.PersonEmail.toLowerCase());
        }
        List<Lead> leads = [Select l.IsConverted, l.Id, l.Email,l.Account__c,l.Application_Status__c
                            From Lead l
                            where l.IsConverted = false and l.Email in:accountEmails];   		
        for(Lead lead:leads){
           mappedLeads.put(lead.Email.toLowerCase(),lead);
        }
        return mappedLeads;
    }

	public static Map<String,Lead> GetLeadsWithAccountExternalReference(List<Account> accounts){
        Map<String,Lead> mappedLeads=new Map<String,Lead>();
        Set<String> accountExternalRef=new Set<String>();
        for(Account a:accounts){
            if (!String.isBlank(a.ExternalReference__c)){
                accountExternalRef.add(a.ExternalReference__c);
            }			
        }
        List<Lead> leads = [Select l.IsConverted, l.Id, l.Email,l.Account__c,l.Application_Status__c
                            From Lead l
                            where l.IsConverted = false and l.Id in:accountExternalRef];   	
        for(Lead lead:leads){
           mappedLeads.put(String.valueOf(lead.Id),lead);           
        }
        return mappedLeads;
    }    
    
    public static Map<String,Lead> GetLeadsWithAccountRelation(List<Account> accounts){
		Set<Id> leadIds=new Set<Id>();
        Map<String,Lead> mappedLeads=new Map<String,Lead>();   
        for(Account acc:accounts){
            leadIds.add(acc.Related_Lead__c);
        }        
		List<Lead> leads = [Select l.IsConverted, l.Id, l.Email,l.Account__c,l.Application_Status__c
                            From Lead l
                            where l.IsConverted = false and l.Id in:leadIds];	
        for(Lead lead:leads){
           mappedLeads.put(String.valueOf(lead.Id),lead);           
        }   
        return mappedLeads;
    }
    
	public static void CreateLeadLinkAndUpdateLeadData(List<Account> newList,Boolean updateAccount){
        Map<String,Lead> mappedLeadsByExternalReference=GetLeadsWithAccountExternalReference(newList);
        Map<String,Lead> mappedLeads=GetLeadsWithAccountEmailAddress(newList);
        
        if (mappedLeads.size()==0 &&  mappedLeadsByExternalReference.size()==0){
            return;
        }        
        List<Lead> updatedLeads=new List<Lead>();
        for(Account acc:newList){   
            //Check the external ref first
            Lead lead=mappedLeadsByExternalReference.get(acc.ExternalReference__c);
            if (lead==null){
                lead=mappedLeads.get(acc.PersonEmail.toLowerCase());
            } 
            if (lead!=null){ 
                if (updateAccount && lead.Account__c==null){
                    acc.Related_Lead__c=lead.id;
                }                
                FieldMapperHelper.AccountToLeadMapping(lead,acc); 
                updatedLeads.add(lead);
            }
        }
        if (updatedLeads.size()>0){
            System.debug('Account insert/update updating lead');                
            update updatedLeads;
        }
    } 
	
    public static void UpdateLeadData(List<Account> accList){
        Map<String,Lead> mappedLeads=GetLeadsWithAccountRelation(accList);
        
		List<Lead> updatedLeads=new List<Lead>();
        for(Account acc:accList){   
            Lead lead=mappedLeads.get(acc.Related_Lead__c);
            if (lead!=null){           
                FieldMapperHelper.AccountToLeadMapping(lead,acc); 
                updatedLeads.add(lead);
            }
        }  
		if (updatedLeads.size()>0){
            System.debug('Account insert/update updating lead');                
            update updatedLeads;
        }        
    }
    
	public static void executeLeadLink(List<Account> newList, List<Account> oldList,Boolean isUpdate,Boolean isBefore,Boolean isInsert,Boolean isAfter){      
        if(isInsert && isBefore){     
            Map<String,Lead> mappedLeadsByExternalReference=GetLeadsWithAccountExternalReference(newList);
            Map<String,Lead> mappedLeads=GetLeadsWithAccountEmailAddress(newList);      
            for(Account acc:newList){                
                Lead lead=mappedLeadsByExternalReference.get(acc.ExternalReference__c);
                if (lead==null){
                    lead=mappedLeads.get(acc.PersonEmail.toLowerCase());
                }  
                //Check if lead is not null and lead does not have an account already associated with it
                if (lead!=null && lead.Account__c==null){
                    acc.Related_Lead__c=lead.Id;
                }
                acc.RecordTypeId = FieldMapperHelper.MarkPlusApplicants(acc);
            }
        } 
        if (isInsert && isAfter){           
            CreateLeadLinkAndUpdateLeadData(newList,false);
        }        
        if (isBefore && isUpdate){
			List<Account> accWithNoLeads=new List<Account>();
			List<Account> accWithLeads=new List<Account>();			
		    for(Account acc:newList)
		 	{
		       	acc.RecordTypeId = FieldMapperHelper.MarkPlusApplicants(acc);		       
				if (acc.Related_Lead__c==null){
					accWithNoLeads.add(acc);						
		       	}
		       	else{
		       		accWithLeads.add(acc);
		       	}
		 	}
         	
         	//Send the accounts that do not have leads - we need to search if leads exists and then link the lead
			CreateLeadLinkAndUpdateLeadData(accWithNoLeads,true);	
            
            //If the account already has a lead, just update the lead no need to relink the accounts
            UpdateLeadData(accWithLeads);
        }
    }    
}

Test Class:
@isTest
private class Test_AccountTriggerHandler {

	static RecordType applicantRecordType;
	
	static {
		applicantRecordType = [Select Id From RecordType Where Name = 'Applicants' and sobjecttype = 'Account']; 
	}

    static testMethod void testAccountError() {
        test.startTest();
        
        Account acc = CreateTestData.createAccount('U_testAccount@tntp.org','externalRef');              
        acc.FirstName = 'Test Account3';
        update acc;
        delete acc;
        test.stopTest();
    }
    
    static testMethod void Account_Gets_Linked_To_Lead_Based_On_Account_ExternalReference_But_With_Different_Emails() {
        test.startTest();
        
        //Create a lead
        Lead lead= CreateTestData.createLead('U_test2@tntp.org'); 
        String externalRef=String.valueOf(lead.Id);
		
        //Createa a an account with different email address
        Account acc  = CreateTestData.createAccount('U_test1@tntp.org',externalRef); 
        
        //Get account from database
        List<Account> accounts = [Select a.PersonEmail,a.Id,a.Related_Lead__c From Account a Where a.PersonEmail ='U_test1@tntp.org'];			

        test.stopTest();
    }    
    
	static testMethod void Account_Gets_Linked_To_Lead_Based_On_Account_Email() {
        test.startTest();
        
        //Create a lead
        Lead lead= CreateTestData.createLead('U_test1@tntp.org'); 

        //Createa a an account with same email address
        Account acc  = CreateTestData.createAccount('U_test1@tntp.org','someinvalidId'); 
        
        //Get Lead from database
        List<Lead> leads = [Select l.Id,Account__c From Lead l Where l.Email ='U_test1@tntp.org'];	
        
        //Get account from database
        List<Account> accounts = [Select a.PersonEmail,a.Id,a.Related_Lead__c From Account a Where a.PersonEmail ='U_test1@tntp.org'];			
        
        test.stopTest();
    }    
    
    static testMethod void Account_Doesnot_Get_Linked_To_Lead_Because_Of_Missing_Account_ExternalReference() {
        test.startTest();
        
        //Create a lead
        Lead lead= CreateTestData.createLead('U_test1@tntp.org'); 

        //Createa a an account with different email address
        Account acc  = CreateTestData.createAccount('U_test2@tntp.org','someinvalidId'); 
        
        //Get Lead from database
        List<Lead> leads = [Select l.Id From Lead l Where l.Email ='U_test1@tntp.org'];	
        
        //Get account from database
        List<Account> accounts = [Select a.PersonEmail,a.Id,a.Related_Lead__c From Account a Where a.PersonEmail ='U_test2@tntp.org'];			
		
        //Should find no match
        System.assertEquals(accounts[0].Related_Lead__c, null);
        
        test.stopTest();
    } 
}

Thank you in advance for any assistance you can provide. 
 
Hello, 

I need help Writting a test class since it's the first time i try it for real. I've done trailhead but i don't really see how it can apply to my trigger. 

Can someone can help me correct it and reach at least 75% of coverage code? I'm currently at 59%. 

Here is my Trigger : 
trigger UpdateCommune on Commune__c (before insert, before update) {
    //Store all Canton Codes in newly created records for Commune__c
    List<String> cantonCode = new List<String>();
    
    for (Commune__c a:Trigger.new){
        cantonCode.add(a.CodeCanton4Chiffres__c);
    }

    //Loop to update each Commune__c record with the proper CantonId__c
    List <Canton__C> CantonList = [Select ID, Name, CodeCanton4Chiffres__c from Canton__C where CodeCanton4Chiffres__c in :cantonCode];
    
    for (Integer i = 0; i <Trigger.new.size(); i++){
        if (CantonList.size() > 0 && Trigger.new[i].CodeCanton4Chiffres__c !=null){
            for (Canton__C c:CantonList){
                if (Trigger.new[i].CodeCanton4Chiffres__c == c.CodeCanton4Chiffres__c){
                    Trigger.new[i].CantonId__c = c.ID;
                  }
            }
        }
       else{
       Trigger.new[i].CantonId__c = null;
       System.System.debug('La référence Canton n\' pas pu être trouvée. Mise à jour impossible de la commune ');
        }
        
        // once the commune is updated with Canton ID, we need to update its "RegionAdministrative__c" fields regarding its "RegionCode__c" field value
    switch on Trigger.new[i].CodeRegion__c {
        when '82', '83' {
            Trigger.new[i].RegionAdministrative__c = 'AUVERGNE-RHONE-ALPES';
        }
        when '26', '43' {
            Trigger.new[i].RegionAdministrative__c = 'BOURGOGNE-FRANCHE-COMTE';
        }
        when '53' {
            Trigger.new[i].RegionAdministrative__c = 'BRETAGNE';
        }
        when '24' {
            Trigger.new[i].RegionAdministrative__c = 'CENTRE-VAL DE LOIRE';
        }
        when '94' {
            Trigger.new[i].RegionAdministrative__c = 'CORSE';
        }
        when '21','41', '42' {
            Trigger.new[i].RegionAdministrative__c = 'GRAND EST';
        }
        when '22', '31' {
            Trigger.new[i].RegionAdministrative__c = 'HAUTS-DE-FRANCE';
        }
        when  '11' {
            Trigger.new[i].RegionAdministrative__c = 'ILE-DE-FRANCE';
        }
        when '25', '23' {
            Trigger.new[i].RegionAdministrative__c = 'NORMANDIE';
        }        
        when '54', '74', '72' {
            Trigger.new[i].RegionAdministrative__c = 'NOUVELLE-AQUITAINE';
        }
        when '73', '91' {
            Trigger.new[i].RegionAdministrative__c = 'OCCITANIE';
        }
        when '52' {
            Trigger.new[i].RegionAdministrative__c = 'PAYS DE LA LOIRE';
        }
        when '93' {
            Trigger.new[i].RegionAdministrative__c = 'PROVENCE-ALPES-COTE D\'AZUR';
        }
    }
    }

}

Here is my Test Class : 
@isTest
private with sharing class UpdateCommune_TEST {
    private static testMethod void updateCommuneTEST() {
        // Create 2 Cantons then add them to a list that we will insert in Canton__c
        List<Canton__c> cantonList = new List<Canton__c>();

        Canton__c canton1 = new Canton__c(Name='Test Canton 2', CodeInseeCanton__c='12345', CodeCanton__c='01', CodeDepartement__c='12' );
        cantonList.add(canton1) ;
        Canton__c canton2 = new Canton__c(Name='Test Canton 2',  CodeInseeCanton__c='12543', CodeCanton__c='02', CodeDepartement__c='12' );
        cantonList.add(canton2) ;
        

        // Create 2 cities then add them to a list that we will insert in Commune__c
        List<Commune__c> communeList = new List<Commune__c>();
        Commune__c commune1 = new Commune__c(Name='Commune 1', CodeInseeCommune__c='12264', CodeDepartement__c='12', CodeCanton__c='01', CodeRegion__c='73');
        communeList.add(commune1);
        Commune__c commune2 = new Commune__c(Name='Commune 2', CodeInseeCommune__c='12265', CodeDepartement__c='12', CodeCanton__c='02', CodeRegion__c='73');
        communeList.add(commune2);
        
        test.startTest();
        insert cantonList;
        insert communeList;
        test.stopTest();

        // Retrieve the new communes
        List<Commune__c> createdCommunes = new List<Commune__c>([Select Name, Id, CodeInseeCommune__c, CodeDepartement__c, CodeCanton__c, CodeCanton4Chiffres__c, CodeRegion__c,Departement__c,CantonId__c, RegionAdministrative__c from Commune__c Where  CodeCanton4Chiffres__c='1201' OR CodeCanton4Chiffres__c='1202']);
       
        for (Integer i=0; i < createdCommunes.size(); i++) {
            System.debug('Value of canton after trigger fired: ' + createdCommunes[i].CantonId__c);
            // Test that the trigger correctly updated the RegionAdministrative
            System.assertEquals('OCCITANIE', createdCommunes[i].RegionAdministrative__c);
        }    
    }
}

Ty in advance for your help. 

 
Hello Developers

i am new to the apex development, i have been given a task for creating Triggers to prevent duplicate records on multiple fields , i know this is can be achived through Duplicate Rules, but still i want to try with the Apex trigger

Assignedto__c (Lookup(User)

Quater_Year__c(Picklist)

Month__c(Picklist)

i want to create a Duplication rule on these 3 fields, 

i refered the below link, but i could not get the correct code

https://www.mstsolutions.com/technical/preventing-duplicate-records-based-on-multiple-fields-in-salesforce/

 

Hi all,
I have written a trigger on Tenant_Details__c object which has a lookup relationship to Room_Details__c object. Every time a new record is inserted, I want to update a field in Room_Details__c and all the Tenants present in that Room in which that tenant has been added. My trigger is working when I insert an individual record, but when I try to enter multiple records simultaneously, then it throws an error. The reason is that it is not bulkified. Con someone please help me bulkify this code.

trigger addTenant on Tenant_Details__c (after insert) 
{   
    List<Tenant_Details__c> tenantDetailList = [select Contribution__c, Stays_in__c from Tenant_Details__c where id in :Trigger.new];
    
    List<Tenant_Details__c> tenantDetailListToUpdate = new List<Tenant_Details__c>();
    List<Room_Details__c> roomDetailListToUpdate = new List<Room_Details__c>();
    
    for(Tenant_Details__c tenant : tenantDetailList)
    {
        Room_Details__c rooms=[select Rent__c, Sharing_Capacity__c, Present_Tenant_Count__c from Room_Details__c where id = :tenant.Stays_in__c];
        
        System.debug('Trigger.isInsert');
        System.debug('Previous tenant count:'+rooms.Present_Tenant_Count__c);
        if(rooms.Present_Tenant_Count__c<rooms.Sharing_Capacity__c)
        {
            rooms.Present_Tenant_Count__c=rooms.Present_Tenant_Count__c+1;//3. updating tenant count 
            
        }
        else
        {
            System.debug('Maximum tenant count reached');
            Trigger.oldMap.get(rooms.Id).addError('Cannot add tenants to this room.');//4. add error on max capacity
        }
        
        //5. increase rent of each tenant
        System.debug('New tenant count: '+rooms.Present_Tenant_Count__c);
        Double contri = rooms.Rent__c/rooms.Present_Tenant_Count__c;
        tenant.Contribution__c=contri;     
        
        for(Tenant_Details__c allTenants:[select Contribution__c from Tenant_Details__c where Stays_in__c=:tenant.Stays_in__c])
        {
            allTenants.Contribution__c=contri;
            tenantDetailListToUpdate.add(allTenants);
        }
		
        roomDetailListToUpdate.add(rooms);
    }
    update roomDetailListToUpdate;
    update tenantDetailListToUpdate;
	
}
Hello, I've got a trigger, which causes that I am unable to delete records. This shows up:

There's a problem saving this record. You might not have permission to edit it, or it might have been deleted or archived. Contact your administrator for help.

 
trigger QuoteLineItemEmailBeforeDelete on QuoteLineItem (before delete) {
    Set<Id> quids = new Set<Id>();
    for(QuoteLineItem qli :Trigger.Old) {
        quids.add(qli.QuoteId);
    }
    Quote[] quo = [Select Id from Quote Where id In :quids];
  Messaging.reserveSingleEmailCapacity(trigger.size);
    List<Messaging.SingleEmailMessage> emails = new List<Messaging.SingleEmailMessage>();
    for (QuoteLineItem qli : Trigger.old) {
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
        email.setToAddresses(new String[] {'test@example.com'});
        email.setSubject('Oznámení o změně nabídky');
        email.setPlainTextBody('Došlo ke změně nabídky' + Quo[0].Name + '.<br>' + 'Pro otevření záznamu v Salesforce klikněte na následující odkaz:<br>' +  URL.getSalesforceBaseUrl().toExternalForm() + '/' + qli.Id);
        emails.add(email);
    }
    Messaging.sendEmail(emails);
}

 
Hello Everyone,

I need help with my requirements.

Need help in writing a trigger between Opportunity and Project(Custom Object) to create Project wit specified Template(Record).

I have three objects.
Opportunity (Three Checkboxes)(Temp 60, Temp 90, Temp 120)
      ||
Project (Record Type -- ST Templates) Records(Temp 60, Temp 90, Temp 120)
      ||
MIlestones


criterias..,

1. When the Opportunity Stage is ClosedWon, create a Project.
2. The opportunity has three checkboxes names
    (Three Checkboxes -- Temp 60, Temp 90, Temp 120)
3. The project has Record Type as (Record Type -- DC Project Templates)
   These are the ST templates (Means records in Project Object with Record Type -- DC Project Templates) -- Temp 60, Temp 90, Temp 120.

Now, Whenever Opportunity is ClosedWon and Checkbox Temp 60 is true.
Create a New Project with Selecting Temp60 as the default template for Project because Temp 60 has Child Records(28 Milestones in Milestones Object.)



Please Help me in providing a trigger for two objects.

Trigger :
Opportunity Stage:  ClosedWon && Temp 60 Checkbox is true 
Create a Project with  Dc Project Template (Temp 60) as default.

If I select Temp 60 checkbox in Opportunity Temp 60 Record from Project is to be the default. Because of Every Template(Record) in the DC Project Template as a certain number of unique Child Records.

If I select Temp 90 checkbox in Opportunity Temp 90 Record from Project is to be the default. Because of Every Template(Record) in the DC Project Template as a certain number of unique Child Records.

If I select Temp 120 checkbox in Opportunity Temp 120 Record from Project is to be the default. Because of Every Template(Record) in the DC Project Template as a certain number of unique Child Records.


Please Provide me the trigger for this scenario.

Thanks and Regards,
Azar Khasim.



 
Hi, I have custom Status__c picklist field on Account. I have a need when account gets inactivated with value pick "Inactive" then all contacts related to the account should also get inactive (contact also have  picklist custom field Contact_Status__c with one of the value as "Active". Apparently, combination of PB and Flow is not working. I would like to tackle this with trigger.

*Also can this be reversble also if account her reactivated again then contacts gets active? 
  • February 14, 2020
  • Like
  • 0
I am trying to return either a string or a date field using the following apex, but i'm getting an error 'illegal assignment from date to string'.

public String RatingRelease {get;set;}
public Date Today {get;set;}
Today = System.today();

        //Returns the Rating Release date or the 'rating pending'
        IF (Today < currentQRpCase.Rating_Externally_Visible_Date__c){
            RatingRelease = 'Rating Pending';
        } else IF(Today > currentQRpCase.Rating_Externally_Visible_Date__c){
            RatingRelease = currentQRpCase.Rating_Externally_Visible_Date__c;
        } else {
            RatingRelease = '';
        }


 
Trigger for tick "customer access" by defaulton Files
Hello, 

I am currently having an issue, we have a custom object in salesforce named Applications. I deally when that records gets created, it gets created with Files attached to the record. Then someone internally would manually change the owner of that record to a community plus user to have ownership of that record. the issue here is, once the record owner is changed the community plus user will have access to the record as the sharing model of the object is private. the issue is that even though the record owner is owned by a community plus user they do not have access to view the files attached to that record, because i am the owner of the file and the "customer access" is not checked automatically when the record owner is changed to that community user, there will be times when the Application record will be owned by an internal user and they will have access to view the files attached to the record,. but when the record is created  by an internal person and also when an internal perosn attach a file against the record , a community user wont have access to the files even if we make them the record owner. What i am trying to build is when the application record owner is changed to a community plus user or a community user, as they do have access to the record make them see the files attached to the record too. I logged this case with Salesforce and they said the only way is to build this Via a Trigger.
Would appreciate if someone could help me please build this.

Thanks
please see screenshot below. at the moment we have to do this manually to make them see the  files attached to that record once

Hi All,

Thought this would be easy, but I cannot get past this Error.

User-added image

Thanks in advance.

 

Robert

Hello,
I send out mass emails (through Apex) monthly, and the "from" person changes based on who the email is going to. Currently, if any recipients of the email reply, the reply comes to my inbox. Is there a way to set the address where replies should go? Any help is greatly appreciated. 
Hi, want to modifying this trigger to include only specific records. So basically I have number of contacts for the account shown on account record. This is calculated via the below trigger: There is a custom number field on account Number_of_contacts and the number is pushed via this trigger on account. Now, I have a need where I only need to push number of contacts that are checked (Motivator on Board - a custom checkbox field) on contact records not all contacts. I can make customer number field on account such as "Number of Total MOBs" but I want a trigger to push it. 
 
trigger ContactTickerTrigger on Contact (After insert, After delete, After undelete, After Update) {
    Set<Id> parentIdsSet = new Set<Id>();
    List<Account> accountListToUpdate = new List<Account>();
    IF(Trigger.IsAfter){
        IF(Trigger.IsInsert || Trigger.IsUndelete  || Trigger.isUpdate){
            FOR(Contact c : Trigger.new){
                if(c.AccountId!=null){   
                   parentIdsSet.add(c.AccountId);
                   If(Trigger.isUpdate){
                       if(Trigger.oldMap.get(c.Id).AccountId != c.AccountId){
                          parentIdsSet.add(Trigger.oldMap.get(c.Id).AccountId);
                       }
                    }
                }
            }
        }
        IF(Trigger.IsDelete){
            FOR(Contact c : Trigger.Old){
                if(c.AccountId!=null){   
                   parentIdsSet.add(c.AccountId); 
                }
            }
        }
    }
    System.debug('#### parentIdsSet = '+parentIdsSet);
    List<Account> accountList = new List<Account>([Select id ,Name, Number_of_Contacts__c, (Select id, Name From Contacts) from Account Where id in:parentIdsSet]);
    FOR(Account acc : accountList){
        List<Contact> contactList = acc.Contacts;
        acc.Number_of_Contacts__c = contactList.size();
        accountListToUpdate.add(acc);
    }
    try{
        update accountListToUpdate;
    }catch(System.Exception e){
        
    }
}


Thank you!!


 
  • February 06, 2020
  • Like
  • 0
We integrate some data from our ERP over to Salesforce for better visibilty and reporting of our customers.  I'm bringing over the order lines from the ERP database nightly using Jitterbit.  However I don't have a solid data association between the Account objects and the Orders yet.  We bring over the Account Number of the ERP system into the Orders object; and we have the ERP Account number 'stamped' on the Salesforce Accounts that we've done business with; but presently there isn't any hard linkage between these two objects.

I'm wondering what type of relationship would suffice here.  Looking through the various types (Lookup, Master-Detail, Hierarchical) none of them are a match for what I'm after.  I don't want this to have to be user driven; I'd rather it associated itself to the other record if there was a match.  In my previous experience you can't assoicate two records in Salesforce based on an external key.  All associations must be done with SFIDs for things... is that the case?  And if so, any recommendations on how to associate this data with the minimal amount of overhead?  
I created a visualforce and a apex class to display junction object child records on an account page. It is working as expected, but i was wonder how can update my apex class to allow the junction object child records to be updated from the account page? I'm not sure how to accomplish this so i am reaching out to the community to see if anyone could help me update my class to support this function. My VF page and class is below.

VF Page:
<apex:page standardController="Account" extensions="VF_SiteServicePartnerLandController" lightningStylesheets="true"  >


<style>
       th{ width: 50%;}       
   </style>
 
    <apex:form > 
  


     <apex:pageBlock >
    
        
        <apex:pageBlockTable cellpadding="5" width="100%" columns="2" value="{!sspList}" var="item">
 
           <apex:column >
           <apex:outputField value="{!item.Supported_Trade__c}"/><br></br>
           <apex:outputLabel value=""><b>Service Partner Assigned to Site</b></apex:outputLabel><br></br>
                <apex:outputField value="{!item.Service_Partner__c}"/><br></br>
                <apex:outputLabel value=""><b>Service Partner Primary Contact</b></apex:outputLabel><br></br>
                <apex:outputField value="{!item.Primary_Field_Contact__c}"/><br></br>
                <apex:outputLabel value=""><b>Primary Field  Cell</b></apex:outputLabel><br></br>
                <apex:outputField value="{!item.Primary_Field_Mobile__c}"/><br></br>
                <apex:outputLabel value=""><b>Primary Field Email</b></apex:outputLabel><br></br>
                <apex:outputField value="{!item.Primary_Field_Email__c}"/><br></br>
                <apex:outputLabel value=""><b>Secondary Contact</b></apex:outputLabel><br></br>
                <apex:outputField value="{!item.Secondary_Field_Contact__c}"/><br></br>
                <apex:outputLabel value=""><b>Secondary Cell</b></apex:outputLabel><br></br>
                <apex:outputField value="{!item.Secondary_Field_Mobile__c}"/><br></br>
                <apex:outputField value="{!item.Secondary_Field_Email__c}"/>
            
            </apex:column>
           
           
           <apex:column >
           
           <apex:outputLabel value=""><b>Service Partner Owner</b></apex:outputLabel><br></br>
                <apex:outputField value="{!item.Service_Partner_Owner__c}"/><br></br>
                <apex:outputLabel value=""><b>Service Partner Owner Cell</b></apex:outputLabel><br></br>
                <apex:outputField value="{!item.Service_Partner_Owner_Mobile__c}"/><br></br>
                <apex:outputLabel value=""><b>Service Partner Main Phone</b></apex:outputLabel><br></br>
                <apex:outputField value="{!item.Service_Partner_Main_Phone__c}"/><br></br>
                <apex:outputLabel value=""><b>Service Partner Owner Email</b></apex:outputLabel><br></br>
                <apex:outputField value="{!item.Service_Partner_Owner_Email__c}"/><br></br>
                <apex:outputLabel value=""><b>Service Provider Start Date</b></apex:outputLabel><br></br>
                <apex:outputField value="{!item.Service_Partner_Start_Date__c}"/><br></br>
                <apex:outputLabel value=""><b>Service Provider End Date</b></apex:outputLabel><br></br>
                <apex:outputField value="{!item.Service_Partner_End_Date__c}"/>
            
            </apex:column>
            
      </apex:pageBlockTable>
   </apex:pageBlock>
 </apex:form>   
 </apex:page>

Apex Class:
// Used on the account page updated 1-31-2020
Public Class VF_SiteServicePartnerLandController{
   private Account acc;
   public List<Site_Service_Partner__c> sspList {get;set;}
   
   public VF_SiteServicePartnerLandController(ApexPages.StandardController sp){
       acc = (Account)sp.getRecord();
       sspList = new List<Site_Service_Partner__c>();
       sspList = [SELECT Id,Name,Site_Account__c,Primary_Field_Contact__c,Service_Partner__c,
                  Service_Partner_Owner__c,Service_Partner_Owner_Mobile__c,Service_Partner_Owner_Email__c,
                  Primary_Field_Email__c,Primary_Field_Mobile__c,Service_Partner_Site_Status__c, 
                  Contracted_Services__c,Secondary_Field_Contact__c,Secondary_Field_Email__c,Secondary_Field_Mobile__c,
                  Service_Partner_Start_Date__c,Service_Partner_End_Date__c,Service_Partner_Main_Phone__c,Trade__c,Supported_Trade__c  FROM Site_Service_Partner__c WHERE Site_Account__c =: acc.Id AND Site_Account__r.Trade__c includes('Land') AND Service_Partner_Site_Status__c = 'Active' ];

    
    Set<Id> bidId = new  Set<Id>();  
    for(Site_Service_Partner__c bs:sspList){
       bidId.add(bs.Id);
    }
     
   }

}

 
  • February 05, 2020
  • Like
  • 0

 

I am trying to put the id from database.saveresult return values and then the matching value from the citylist list into this map below, but I get an error "Method does not exist or incorrect signature: void put(sumchans__City_Master__c, Id) from the type Map<String,String>"
 
Database.SaveResult[] saveCityMaster = Database.Insert(cityList, false);
        Map<String,String> findCityId = new Map<String,String>();
        for (Database.SaveResult sr : saveCityMaster) {
            if (!sr.isSuccess()) {
                findCityId.put(cityList.get(0),sr.getId());
            }
        }

 
So I found out that I cannot disable the automatic outgoing emails that is sent after a user record is created in Salesforce.
(We enables SSO in out environment, so it isn't necessary for the automatically generated email confirmation to be sent to users after they've been created in SF). Enetually, we'd like to sent out a custom email instead.

I was thinking to create a SF Apex rigger on the User object that somehow "deleted" the outbound email that is send after a user record is created.
Is this possible? Could someone assist with the code? I have very little experiece writing Apex triggers (but very eager to learn!)
Hi,
I need some help... 

I have an idea, but am not sure how to accomplish it using an Apex trigger... 

User Action: Create a new Lead
Step #1: Enter the lead's first name, last name, email, etc.
Step #2: Select the comapny name from a custom lookup field
Step #3: Save the new lead.

Here's the issue, Company is a standard required field when creating a new Lead. I would like two things to happen during this action. The first is to check the Company field, and if it is blank, check if there is a value in the custom lookup field. If there in a value in the custom lookup field, then copy the value to the Company field. 

Can this be done using an Apex trigger? If so, can you show me how?

Thanks.
invalid. Ask your admin to check the individual record type configurations in Setup. Class.HealthCloudGA.MoiConfiguration: line 639, column 1 Class.HealthCloudGA.MoiConfiguration: line 593, column 1 Class.HealthCloudGA.MoiConfiguration.loadIndividualRecordTypeMapping: line 546, column 1 Class.HealthCloudGA.MoiConfiguration: line 734, column 1 Class.HealthCloudGA.MoiConfiguration.isRecordOfTypeIndividual: line 807, column 1 Class.HealthCloudGA.AccountTriggerHandler.onBeforeInsert: line 31, column 1 Class.HealthCloudGA.MoiBaseTriggerHandler.handleEvent: line 120, column 1 Trigger.HealthCloudGA.AccountTrigger: line 12, column 1
 
This my code i used(anything i need to modify,please let me know).
import { LightningElement, track, api,wire } from 'lwc';
import { getRecord,getFieldValue  } from 'lightning/uiRecordApi';
@track recType; 
@api recordId;
@track LjobsValue;
@track CjobsValue;
@track MjobsValue;
@wire(getRecord, { recordId: '$recordId', layoutTypes: ['Full'], modes: ['View'] })
    wiredRecord({data,error}) {
       if (data) { 
       var result = JSON.parse(JSON.stringify(data)); 
       this.recType=result.recordTypeId;
       this.LjobsValue=getFieldValue(data,'Loan__c.Total_Jobs_Lost__c');
       this.MjobsValue=getFieldValue(data,'Loan__c.Total_Jobs_Maintained__c');
       this.CjobsValue=getFieldValue(data,'Loan__c.Total_Jobs_Created__c');
       }
       else{
         this.error=error;  
         console.log(error);
       }
   }
i used this code it throws error in console

this cause error:User-added image
Hi,

I have to perform Excel IRR Function Calculation in Apex class.
https://exceljet.net/excel-functions/excel-irr-function

Thanks,
Foram Rana
Hello,

There is an old trigger in our org that needs to be deactivated. However, the trigger's test class only has 65% code coverage. I did not write this code and do not have a background in development. Could anyone offer clear edits to make so that I can successfully deploy the deactivated trigger to production?

Trigger:
trigger AccountTrigger on Account (before delete, before insert, before update,after insert) {
    AccountTriggerHandler.execute(Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap, 
                          Trigger.isInsert, Trigger.isUpdate, Trigger.isDelete, Trigger.isBefore, Trigger.isAfter);
    AccountTriggerHandler.executeLeadLink(Trigger.new,Trigger.old,Trigger.isUpdate,Trigger.isBefore,Trigger.isInsert,Trigger.isAfter);
}
The Class referenced in the trigger:
public with sharing class AccountTriggerHandler {
	
	static RecordType applicantRecordType;
	static Profile adminProfile;
	static {
		applicantRecordType = [Select Id From RecordType Where Name = 'Applicants' and sobjecttype = 'Account']; 
		adminProfile = [Select Id, Name From Profile Where Name = 'System Administrator'];
	}
	
	public static void execute(List<Account> newList, Map<Id, Account> newMap,
                               List<Account> oldList, Map<Id, Account> oldMap,
                               Boolean isInsert, Boolean isUpdate, Boolean isDelete, Boolean isBefore, Boolean isAfter) {    
    	List<Account> accList = new List<Account>();
    	if (isDelete) {
    		for (Account acc : oldList)
    			accList.add(acc);
    	}
    	else {
    		for (Account acc : newList)
    			accList.add(acc);
    	}    	
    	for (Account acc : accList)	{
    		if (isBefore) {
	    		if (acc.RecordTypeId == applicantRecordType.Id && 
	    			System.Userinfo.getProfileId() != adminProfile.Id) {	    		
	    			acc.addError('Only System Administrators may create, edit, or delete Applicants');		
	    		}
    		}
    	}		                           	
    }
    
	public static Map<String,Lead> GetLeadsWithAccountEmailAddress(List<Account> accounts){
        Map<String,Lead> mappedLeads=new Map<String,Lead>();
        Set<String> accountEmails=new Set<String>();
        for(Account a:accounts){
			accountEmails.add(a.PersonEmail.toLowerCase());
        }
        List<Lead> leads = [Select l.IsConverted, l.Id, l.Email,l.Account__c,l.Application_Status__c
                            From Lead l
                            where l.IsConverted = false and l.Email in:accountEmails];   		
        for(Lead lead:leads){
           mappedLeads.put(lead.Email.toLowerCase(),lead);
        }
        return mappedLeads;
    }

	public static Map<String,Lead> GetLeadsWithAccountExternalReference(List<Account> accounts){
        Map<String,Lead> mappedLeads=new Map<String,Lead>();
        Set<String> accountExternalRef=new Set<String>();
        for(Account a:accounts){
            if (!String.isBlank(a.ExternalReference__c)){
                accountExternalRef.add(a.ExternalReference__c);
            }			
        }
        List<Lead> leads = [Select l.IsConverted, l.Id, l.Email,l.Account__c,l.Application_Status__c
                            From Lead l
                            where l.IsConverted = false and l.Id in:accountExternalRef];   	
        for(Lead lead:leads){
           mappedLeads.put(String.valueOf(lead.Id),lead);           
        }
        return mappedLeads;
    }    
    
    public static Map<String,Lead> GetLeadsWithAccountRelation(List<Account> accounts){
		Set<Id> leadIds=new Set<Id>();
        Map<String,Lead> mappedLeads=new Map<String,Lead>();   
        for(Account acc:accounts){
            leadIds.add(acc.Related_Lead__c);
        }        
		List<Lead> leads = [Select l.IsConverted, l.Id, l.Email,l.Account__c,l.Application_Status__c
                            From Lead l
                            where l.IsConverted = false and l.Id in:leadIds];	
        for(Lead lead:leads){
           mappedLeads.put(String.valueOf(lead.Id),lead);           
        }   
        return mappedLeads;
    }
    
	public static void CreateLeadLinkAndUpdateLeadData(List<Account> newList,Boolean updateAccount){
        Map<String,Lead> mappedLeadsByExternalReference=GetLeadsWithAccountExternalReference(newList);
        Map<String,Lead> mappedLeads=GetLeadsWithAccountEmailAddress(newList);
        
        if (mappedLeads.size()==0 &&  mappedLeadsByExternalReference.size()==0){
            return;
        }        
        List<Lead> updatedLeads=new List<Lead>();
        for(Account acc:newList){   
            //Check the external ref first
            Lead lead=mappedLeadsByExternalReference.get(acc.ExternalReference__c);
            if (lead==null){
                lead=mappedLeads.get(acc.PersonEmail.toLowerCase());
            } 
            if (lead!=null){ 
                if (updateAccount && lead.Account__c==null){
                    acc.Related_Lead__c=lead.id;
                }                
                FieldMapperHelper.AccountToLeadMapping(lead,acc); 
                updatedLeads.add(lead);
            }
        }
        if (updatedLeads.size()>0){
            System.debug('Account insert/update updating lead');                
            update updatedLeads;
        }
    } 
	
    public static void UpdateLeadData(List<Account> accList){
        Map<String,Lead> mappedLeads=GetLeadsWithAccountRelation(accList);
        
		List<Lead> updatedLeads=new List<Lead>();
        for(Account acc:accList){   
            Lead lead=mappedLeads.get(acc.Related_Lead__c);
            if (lead!=null){           
                FieldMapperHelper.AccountToLeadMapping(lead,acc); 
                updatedLeads.add(lead);
            }
        }  
		if (updatedLeads.size()>0){
            System.debug('Account insert/update updating lead');                
            update updatedLeads;
        }        
    }
    
	public static void executeLeadLink(List<Account> newList, List<Account> oldList,Boolean isUpdate,Boolean isBefore,Boolean isInsert,Boolean isAfter){      
        if(isInsert && isBefore){     
            Map<String,Lead> mappedLeadsByExternalReference=GetLeadsWithAccountExternalReference(newList);
            Map<String,Lead> mappedLeads=GetLeadsWithAccountEmailAddress(newList);      
            for(Account acc:newList){                
                Lead lead=mappedLeadsByExternalReference.get(acc.ExternalReference__c);
                if (lead==null){
                    lead=mappedLeads.get(acc.PersonEmail.toLowerCase());
                }  
                //Check if lead is not null and lead does not have an account already associated with it
                if (lead!=null && lead.Account__c==null){
                    acc.Related_Lead__c=lead.Id;
                }
                acc.RecordTypeId = FieldMapperHelper.MarkPlusApplicants(acc);
            }
        } 
        if (isInsert && isAfter){           
            CreateLeadLinkAndUpdateLeadData(newList,false);
        }        
        if (isBefore && isUpdate){
			List<Account> accWithNoLeads=new List<Account>();
			List<Account> accWithLeads=new List<Account>();			
		    for(Account acc:newList)
		 	{
		       	acc.RecordTypeId = FieldMapperHelper.MarkPlusApplicants(acc);		       
				if (acc.Related_Lead__c==null){
					accWithNoLeads.add(acc);						
		       	}
		       	else{
		       		accWithLeads.add(acc);
		       	}
		 	}
         	
         	//Send the accounts that do not have leads - we need to search if leads exists and then link the lead
			CreateLeadLinkAndUpdateLeadData(accWithNoLeads,true);	
            
            //If the account already has a lead, just update the lead no need to relink the accounts
            UpdateLeadData(accWithLeads);
        }
    }    
}

Test Class:
@isTest
private class Test_AccountTriggerHandler {

	static RecordType applicantRecordType;
	
	static {
		applicantRecordType = [Select Id From RecordType Where Name = 'Applicants' and sobjecttype = 'Account']; 
	}

    static testMethod void testAccountError() {
        test.startTest();
        
        Account acc = CreateTestData.createAccount('U_testAccount@tntp.org','externalRef');              
        acc.FirstName = 'Test Account3';
        update acc;
        delete acc;
        test.stopTest();
    }
    
    static testMethod void Account_Gets_Linked_To_Lead_Based_On_Account_ExternalReference_But_With_Different_Emails() {
        test.startTest();
        
        //Create a lead
        Lead lead= CreateTestData.createLead('U_test2@tntp.org'); 
        String externalRef=String.valueOf(lead.Id);
		
        //Createa a an account with different email address
        Account acc  = CreateTestData.createAccount('U_test1@tntp.org',externalRef); 
        
        //Get account from database
        List<Account> accounts = [Select a.PersonEmail,a.Id,a.Related_Lead__c From Account a Where a.PersonEmail ='U_test1@tntp.org'];			

        test.stopTest();
    }    
    
	static testMethod void Account_Gets_Linked_To_Lead_Based_On_Account_Email() {
        test.startTest();
        
        //Create a lead
        Lead lead= CreateTestData.createLead('U_test1@tntp.org'); 

        //Createa a an account with same email address
        Account acc  = CreateTestData.createAccount('U_test1@tntp.org','someinvalidId'); 
        
        //Get Lead from database
        List<Lead> leads = [Select l.Id,Account__c From Lead l Where l.Email ='U_test1@tntp.org'];	
        
        //Get account from database
        List<Account> accounts = [Select a.PersonEmail,a.Id,a.Related_Lead__c From Account a Where a.PersonEmail ='U_test1@tntp.org'];			
        
        test.stopTest();
    }    
    
    static testMethod void Account_Doesnot_Get_Linked_To_Lead_Because_Of_Missing_Account_ExternalReference() {
        test.startTest();
        
        //Create a lead
        Lead lead= CreateTestData.createLead('U_test1@tntp.org'); 

        //Createa a an account with different email address
        Account acc  = CreateTestData.createAccount('U_test2@tntp.org','someinvalidId'); 
        
        //Get Lead from database
        List<Lead> leads = [Select l.Id From Lead l Where l.Email ='U_test1@tntp.org'];	
        
        //Get account from database
        List<Account> accounts = [Select a.PersonEmail,a.Id,a.Related_Lead__c From Account a Where a.PersonEmail ='U_test2@tntp.org'];			
		
        //Should find no match
        System.assertEquals(accounts[0].Related_Lead__c, null);
        
        test.stopTest();
    } 
}

Thank you in advance for any assistance you can provide. 
 
Trigger for tick "customer access" by defaulton Files
Hello, 

I am currently having an issue, we have a custom object in salesforce named Applications. I deally when that records gets created, it gets created with Files attached to the record. Then someone internally would manually change the owner of that record to a community plus user to have ownership of that record. the issue here is, once the record owner is changed the community plus user will have access to the record as the sharing model of the object is private. the issue is that even though the record owner is owned by a community plus user they do not have access to view the files attached to that record, because i am the owner of the file and the "customer access" is not checked automatically when the record owner is changed to that community user, there will be times when the Application record will be owned by an internal user and they will have access to view the files attached to the record,. but when the record is created  by an internal person and also when an internal perosn attach a file against the record , a community user wont have access to the files even if we make them the record owner. What i am trying to build is when the application record owner is changed to a community plus user or a community user, as they do have access to the record make them see the files attached to the record too. I logged this case with Salesforce and they said the only way is to build this Via a Trigger.
Would appreciate if someone could help me please build this.

Thanks
please see screenshot below. at the moment we have to do this manually to make them see the  files attached to that record once
Hi, my code has passed the step 4 check, but when I try the search by boat type no boats appear on the BoatSearchResults component. I have done some debugging and found that it is not entering into the aura:iteration and can't figure out why. Hopefully someone can help me.

The string "going to AuraIteration" appears on the screen, but nothing else. The variable v.boats contains the right amount of items (I am testing it with Sailboat type and it has 2 items. It also has the right values in each object.

Here is my code: 


BoatSearchResults.cmp
<aura:component controller="BoatSearchResults">
    <aura:attribute name="boatTypeId" type="String" />
    <aura:method name="search" description="gets the boatTypeId from BoatSearch component and runs the search"
                 action="{!c.doSearch}">
        <aura:attribute name="boatTypeId" type="String" />
    </aura:method >
    <aura:attribute name="boats" type="Boat__c[]" />
    <lightning:layout multipleRows="true" verticalAlign="center" horizontalAlign="center">
        <aura:if isTrue="{!v.boats.length &gt; 0}">
            going to AuraIteration
            <aura:iteration items="{!v.boats}" var="boatItem">
                <lightning:layoutItem flexibility="grow" class="slds-m-right_small">
                    <h3>calling BoatTile</h3>
                    <c:BoatTile boat="{!boatItem}"/>
                </lightning:layoutItem>
            </aura:iteration>
            <aura:set attribute="else">
                <lightning:layoutItem class="slds-align_absolute-center" flexibility="auto">
                    <h3>No boats found</h3>
                </lightning:layoutItem>
            </aura:set>
        </aura:if>
    </lightning:layout>
</aura:component>

Also, can someone tell me how to post code so it looks like code (lined and with the option to copy, etc)

Thanks!