+ Start a Discussion
Rory McDonnellRory McDonnell 
Hi I have created the following Trigger that creates ten opportunities when an account has more than 99 employees. It is working as expected and the opps are being created, only issue is that they are not being linked to the account record. Any idea why that is the case?
 
trigger CreateTenOpps on Account (before insert, before update) {
    
    List<Opportunity> TenOpps = New List<Opportunity>();
    
    for (Account acc : Trigger.new) {
        if (acc.NumberOfEmployees > 99) {
            for (Integer i = 0; i < 10; i++) {
                Opportunity opp = New Opportunity(CloseDate = date.today(), 
                                                  StageName = 'Prospecting', 
                                                  Name = 'Trigger Opp',
                                                  AccountId = acc.Id);
                TenOpps.add(opp);
            }
            insert TenOpps;
        }
    }

}

 
Best Answer chosen by Rory McDonnell
Danish HodaDanish Hoda
Hi Rory,
Before update will work, but it is recommended to work on After trigger events when you are working on other related/un-related records.
Rory McDonnellRory McDonnell 
Hi I am somewhat of a novice when it comes to apex and can't seem to work out what the problem is with line 7 of my code. I am building a practice trigger that creates 10 identical opportunities whenever an account has more than 99 employees.

I think I have set up the for loop correctly but in the developer console 'Problem' there are a number of messages on line 7
- Expecting ';' but was a '<'
- Expecting ';' but was a ','
- Expecting ';' but was a ')'

Any suggestions?
trigger CreateTenOpps on Account (before insert) {
    
    List<Opportunity> TenOpps = New List<Opportunity>();
    
    for (Account acc : Trigger.new) {
        if (acc.NumberOfEmployees > 100) {
            for (Integer i = 0, i < 10, i++) {
                Opportunity opp = New Opportunity(CloseDate = date.today(), 
                                                  StageName = 'Prospecting', Name = 'Trigger Opp');
                TenOpps.add(opp);
            }
            insert TenOpps;
        }
    }

}

 
Best Answer chosen by Rory McDonnell
Maharajan CMaharajan C
Hi Rory,

In Line no: 7   you have to use the Semi Colon " ; "  don't use the comma in for loop.

trigger CreateTenOpps on Account (before insert) {
    
    List<Opportunity> TenOpps = New List<Opportunity>();
    
    for (Account acc : Trigger.new) {
        if (acc.NumberOfEmployees > 100) {
            for (Integer i = 0; i < 10; i++) {       /// use the Semi colon here .
                Opportunity opp = New Opportunity(CloseDate = date.today(), 
                                                  StageName = 'Prospecting', Name = 'Trigger Opp');
                TenOpps.add(opp);
            }
            insert TenOpps;
        }
    }

}

Thanks,
Maharajan.C  
Sarah PaulsonSarah Paulson 

Hello, I wrote a trigger to check if the url = 'https://sig-cb--Full.cs88.my.salesforce.com' and the profile of the current user is a specific profile (SIG-FSM-Super User) and if so the trigger shows an error message and also an image which I included in the addError function, it looks like this:

trigger ContactCreationForServiceMaxUsers on Contact (Before insert) {
   
       String baseURL = String.valueof(URL.getSalesforceBaseUrl());
      
       system.debug('<<baseURL>>' + baseURL);
       Boolean isBaseURL = baseURL.contains('https://sig-cb--Full.cs88.my.salesforce.com');
       System.debug(' >> String.valueof(URL.getSalesforceBaseUrl()) >>'+baseURL ); 
       User currentUser = [SELECT Id, Profile.Name FROM USER WHERE Id =:UserInfo.getUserId()]; 
      
       Contact c = new Contact(); 
      
       System.debug(' >> isBaseURL >>'+isBaseURL ); 
       System.debug(' >> currentUser.Profile.Name>>'+currentUser.Profile.Name ); 
   
     for(Contact c : Trigger.New){ 
          if(isBaseURL == TRUE  && currentUser.Profile.Name == 'SIG-FSM-Super User'){
           c.addError(' <p style="color:red; font-size: 20px;">Service contact creation is only allowed from “Account” tab using the blue button “Create Contact” after selecting a account”</p><img id="theImage" src="https://sig-cb--full--c.cs88.content.force.com/servlet/servlet.FileDownload?file=0159E0000002tNp" width="850px" height="100px" alt="Description of image here"/> ', false); 
          } 
     } 
}


Can anyone help me with how to build the test class for the trigger? At least theoretical.

1. First I need to create a contact
2. I need to create a user with a profile = 'super-user'
3. somehow i need to check the addError function..

Something like this...

Best Answer chosen by Sarah Paulson
Maharajan CMaharajan C
Hi Sarah,

Please use the below test class:
 
@isTest
public class ContactCreationForServiceMaxUsersTest {
    
    Static testmethod void ServiceMaxUserstest(){
        Profile p = [SELECT Id FROM Profile WHERE Name='SIG-FSM-Super User'];
        User UserObj= new User(Alias = 'Test', Email='SIGFSMSuper@testorg.com',
                               EmailEncodingKey='UTF-8', LastName='SIGFSMSuper', LanguageLocaleKey='en_US',
                               LocaleSidKey='en_US', ProfileId = p.Id,
                               TimeZoneSidKey='America/Los_Angeles', UserName='SIGFSMSuper@testorg.com');
        insert UserObj;
		System.runAs(UserObj) {
        // Add the mandatory fields to create the contact record in below line.
        Contact c = new Contact(LastName ='Test Contact',Email='SIGFSMSuper@testemails.com');
        Database.SaveResult result = Database.insert(c, false);
		}
        
    }
}



Thanks,
Maharajan.C
Pamela DujovnePamela Dujovne 
i am trying to pass the "Add Your Branding to Embedded Chat" Trailhead, but after follow the instructions, the live agent chat stays in "loadin" and after that come back to "chat with an expert". 
I added the visualforce.com to the white list in cors, i also changed it to http in stead of https,  but still not working. can anyone help me?
User-added image
Best Answer chosen by Pamela Dujovne
Pamela DujovnePamela Dujovne
i found the answe! i added to the CORS white list also the http://*.visualforce.com and the https://*.visualforce.com
this solved the issue. Because in the code is with https and in cors i need also the http
Rory McDonnellRory McDonnell 
Hi I am learning how to build triggers and am trying to do the following.

When a new lead is created with a specific company name, update two fields on the lead record and also create a new task. 

My understanding is that since it is a new record I would need to use an AFTER INSERT trigger as the task will need the newly created lead ID as a reference in the WhatID. But seeing as I also need to update fields on the lead record it doesn't seem that the After Insert will allow that.

Am I stuck with choosing between a Before Insert so I can update my lead record, and an After Insert if I want to create a task.

I'm pretty sure there is a simple solution but still very new to Apex.
Best Answer chosen by Rory McDonnell
Danish HodaDanish Hoda
hi Rory,
Please refer below code:
trigger LeadTrigger on Lead (after insert,before insert) {
	
	if(Trigger.isInsert){
		List<Task> tasks = new List<Task>();
		for(Lead leadObj : Trigger.New){
			if(trigger.isBefore){
				//set the field values you want
			}
			if(trigger.isAfter){
				//create Task as below
				Task taskObj = new Task(WhoId = leadObj.Id, ..set other task fields..);
				tasks.add(taskObj);
			}
		}
	}
	if(!tasks.isEmpty())	insert tasks;
}

 
Michael MMichael M 
Hello, I have a process builder set up that posts a chatter notification to the Owner of the Lead when a certain custom field gets updated. How can I @mention that user in the body of the chatter post FROM process builder? The reason I need to do so is because I want the user to receive an alert (both a bell on the chatter and an email) when this chatter post gets posted?  FYI the person is always the User-Owner of the Lead record. Your help is greatly appreciated. 
Best Answer chosen by Michael M
AbhishekAbhishek (Salesforce Developers) 
Hi Michael,

You can go through the below blogs which might answer your query,

https://automationchampion.com/tag/mention-related-user-in-a-post-to-chatter-action-process-builder-salesforce/

https://jenwlee.com/2017/12/12/automate-chatter-post-that-mentions-several-users/

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks.
Sarthak Patil 15Sarthak Patil 15 
Hi everybody,
I am trying to write the following trigger on contact.
"When a new contact is created for a existing account then set contact otherphone as account phone."

I have written this which is working fine.

Trigger TestNewCon on Contact (before insert){        
        for(Contact c : Trigger.new){
        for(Account acc: [Select id,phone from Account where id = :c.AccountId]){
            c.otherphone = acc.phone; 
        }
        }

Is there any other way to write this trigger because i want to avoid writing SOQL query inside for loop(NOT a best practise).
My plan is to fetch all the Accounts which are related to contacts first.
Best Answer chosen by Sarthak Patil 15
Danish HodaDanish Hoda
Hi Sarthak,
You are right, you must not use SOQL inside a loop and always use trigger so as to process bulk data.
Please refer below code for your understanding:
Trigger TestNewCon on Contact (before insert){        
        /*for(Contact c : Trigger.new){
        for(Account acc: [Select id,phone from Account where id = :c.AccountId]){
            c.otherphone = acc.phone; 
        }
        }*/
		Map<Id, Acount> mapAcc = new Map<Id, Acount>();
		for(Contact c : Trigger.New){
			mapAcc.put(c.AccountId, null);
		}
		for(Account acc : [SELECT Id, Phone FROM Account WHERE Id IN :mapAcc.keySet()]){
			mapAcc.put(acc.Id, acc);
		}
		for(Contact c : Trigger.New){
			c.otherPhone = mapAcc.get(c.AccountId).Phone;
		}
}

 
Michael MMichael M 
Hello, I have a trigger that updates a Lead field checkbox (to true.) When that checkbox is checked off, I need to send a chatter notification to the owner of that record. What is the best way to do that? Can it be done with workflow rules? I'm afraid if I use process builder, it will fire off several times, because my Lead process is set to fire whenever a record is updated, which I think can sometimes fire more than once even if a field is only update once (unless there's a way to prevent that?) Can it be done in the trgiger itself? What would you recomend?
Best Answer chosen by Michael M
VinayVinay (Salesforce Developers) 
Hi Michael,

You can use email alert and set notication whenever check box is false.

Below are few links which gives you more information.

https://help.salesforce.com/articleView?id=customize_wfalerts.htm&type=0
https://help.salesforce.com/articleView?id=customize_wfalerts_recipienttypes.htm&type=5
https://www.salesforcetutorial.com/salesforce-workflow-automation-workflow-management/

 Please mark as Best Answer if above information was helpful so that it can help others in the future.

Thanks,
Vinay Kumar
Shiree SayadShiree Sayad 
There was an unexpected error while verifying this challenge. Usually this is due to some pre-existing configuration or code in the challenge Org. We recommend using a new Developer Edition (DE) to check this challenge. If you're using a new DE and seeing this error, please post to the developer forums and reference error id: HZJWGPUH. Can anyone help so I can get past this error?
Best Answer chosen by Shiree Sayad
AbhishekAbhishek (Salesforce Developers) 
Hi,

For all the Trailhead issues please report it here,

https://trailhead.salesforce.com/help?support=home#

So that our trailhead support engineers will look into it and get back to you.

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Regards,
​​​​​​​Salesforce Support.
Steve Connelly 5Steve Connelly 5 
Good morning all,

I am trying to build a trigger that will create a related custom object  record when an Opportyunity is created or updated.

This is my code so far:
trigger createOpenQuarter on Opportunity (after insert,after update) {
     
    List <Open_Quarter__c> createOpenQuarter = new List <Open_Quarter__c> ();
        
    
        Open_Quarter__c oq = new Open_Quarter__c ();
        Quarter_Number__c qn = new Quarter_Number__c ();
    	Opportunity o = new Opportunity ();
    
         
        oq.Amount_Per_Quarter__c = o.Amount_per_Quarter__c; 
        oq.Close_Date__c = o.CloseDate;
        oq.Name = o.Quarter_Created__c;
        oq.Opportunity_Name__c = o.Name;
        oq.Quarters_Spanned__c = o.Quarters_Spanned__c;
         
        createOpenQuarter.add(oq);
         
    try {
        insert createOpenQuarter;
    } catch (system.Dmlexception e) {
        system.debug (e);
    }
}

I am trying to get this a step at a time. So I just want the first step to work.

The trigger is active in my sandbox so i was hoping that when I created a new Opp or updated an existing one that the trigger would create the custom record but nothing happens.

Can you let me know what I am missing or have done wrong? Once this part works i will work on the next step. Just trying to learn as i go.

I am brand new to coding so i appreciate your patience and any help i can get. I do not get any errors with the obove code, but nothing happens either.

Best regards,
Steve
Best Answer chosen by Steve Connelly 5
Khushmeet KaurKhushmeet Kaur

Hi Steve,

As your using an instance variable for the opportunity that will not contain any value. You might be getting the expectation that the required fields are missing, please refer to the code that might help you.
 
trigger createOpenQuarter on Opportunity (after insert,after update) {

    List <Open_Quarter__c> createOpenQuarter = new List <Open_Quarter__c> ();
      

     for(Opportunity opportunityList : trigger.New){
        
       Open_Quarter__c oq = new Open_Quarter__C();

        oq.Amount_Per_Quarter__c = opportunityList.Amount_per_Quarter__c; 
        oq.Close_Date__c = opportunityList.CloseDate;
        oq.Name = opportunityList.Quarter_Created__c;
        oq.Opportunity_Name__c = opportunityList.Name;
        oq.Quarters_Spanned__c = opportunityList.Quarters_Spanned__c;
        createOpenQuarter.add(oq);

     }
 
    try {
            insert createOpenQuarter;
    } 
    catch (system.Dmlexception e) {
        system.debug (e);
    }
}