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
BillPowell__cBillPowell__c 

Trigger To Prepopulate Records With A Lookup Relationship

I have a custom object "Projects__c" and standard "Opportunities" as a related list to projects via a lookup relationship. 

When a user creates a new Opportunity from the Projects__c object, I would like some values from the Project record to prepopulate in the opportunity when it is created. Is there a way to do this with a lookup relationship and Trigger? I know workflow and PB can only do this on save of the new record which would defeat the purpose, and am trying to avoid a URL hack. 

I don't know code other than the first two lines of the trigger, beyond that I get lost. Any suggestions? 

Kaj E. PetersenKaj E. Petersen
Hi Bill, 

A Trigger much like Workflow and Process Builder only work on the update of the record (e.g. Project__c).  I believe, for your requirement, the best approach is visual workflow.  This button can be initiated from a button on the Project object page.  Pass the information you want to be used for the Opportunity create via parameters.  Then create your opportunity. 

Thanks,
Kaj
BillPowell__cBillPowell__c
Thanks Kaj, i'll give that a whirl. Thank you
SFDC VaibhavSFDC Vaibhav
You can use follwing doing some small changes as per your requirement.
Hopes so this is will solve your problem. 

trigger on Projects__c(after insert){
        set<id> ids=new set<id>();
        for(Projects__c prj:trigger.new){
              ids.add(prj.id);
        }//you will need to make list here
        Projects__c prj=[select id,fieldPrj__c ,lookupFiledName from Projects__c where id in:ids] ;
       Opportunity opty=[select id,field__c from Opportunity where id=:prj.lookupFiledName];
       opty.field__c =prj.fieldPrj__c ;
        update opty;
}

 
BillPowell__cBillPowell__c
Vaibhav, if im not mistaken, a Trigger still wouldnt solve my "prepopulate" problem, correct? I'd have to use visual flow?
Lalitha Trail HeadLalitha Trail Head
A trigger would definitely solve your problem. Use before insert event. Its not a good idea to use after insert event and perform an Update later.
Kaj E. PetersenKaj E. Petersen
Hi Bill,

The trigger solutions to your issue would create the opportunity from the Project object when the project is created.  I believe your requirement is to create the opportunity at some other point.  Because if you wanted the opportunity to be created from the creation of the project, then I would be using process builder not a trigger.  

If you want them to create the opportunity from the project but not have to update the project, then Flow is the best way to go.  If you need any help with the flow or process builder, please feel free to contact me.  

Thanks,
Kaj