function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
jameskCAjameskCA 

Need help updating related object in beforeupdate trigger.

I'm very new to apex and have been working on a custom 'proposal object.'  The object is related to the lead object through a lookup field.  There are a number of fields the sales person has to fill in on the proposal object in order to generate a proposal (using loop document generation).  Once all fields are filled in and values are calculated, I want to push a number (at least 10) fields back to the related lead.  

I don't really know how to do this.  I'm trying to use the put method, but it doesn't seem to be working.  Here is the relevant code:
 
for(Proposal__c p:Trigger.new){
	        
	        Lead lead = mLead.get(p.Lead__c);

lead.put('Panel_Type__c',p.Panel_Type__c);
Any advice would be appreciated.  Thanks in advance.  
 
Ajay GautamAjay Gautam
1. Collect the Lead Ids using the loop variable, like you're doing in Row1-3
2. While collecting values, also prepare a Map<Id, Id> that is LeadId --> Proposal__c Id. This will help you to point the Proposal record in nextStep.
3. Query the Lead using that ID and prepare a List to be updated. Based on Map created in step2, find the corresponding ProposalID and using newMap get the Proposal record. 
4. Push the Lead into system.


Note: for Step 2. instead of Query you can directly create/assign Lead e.g. Lead objLead = new Lead(Id=p.Lead__c); and prepare a List for the same. You save a SOQL here, but unsure if leadId is correct and will pass the Validation or Lookup filter in next step. Anyways, do the first method only for now. Rest you will be learning soon!

Good Luck!
 
jameskCAjameskCA
I'm having trouble understanding where in the trigger I do this.  I'm doing all my proposal calculations in the for(Proposal__c p:Trigger.new) loop.  Do I do the SOQL query for the lead inside this loop? Also, do I have to query every field on the lead that I want udpated?  

Also, in step 3, why do I need the proposal record if I'm already accessing it in the for loop?  

Any code examples for step 3 would help greatly.  Let me know if you need any more info from me.  I'd post my entire current trigger but it's ~ 500 lines of code.  
jameskCAjameskCA
I think a very basic code example would help as I'm not understanding what's required to access a related record and update field values from a certain object.  

E.G. I'm in the proposal update trigger, how do I access, modify, and update a lead if I have the lead id?