Question

I am relatively new to Apex and trigger writing. Here is what I'm trying to accomplish:

Is it possible to copy a record in a custom object into a new record that was created within the same object? In my case, when an opportunity is set to "close won" I need to create a new record in the custom object called Project__c. But the kicker is there is an existing record named proj1 that contains default data that needs to be copied into every new record that goes into the object Project__c.

I know how to create a new record after update on Opportunity, but I'm unsure how to grab the record proj1 out of the object Project__c and copy it. Any help would be great!

Was it helpful?

Solution

You can retrieve your default data Project__c record using SOQL and clone it as the basis for the new object that will be inserted. To do this you will want to use the sObject.clone() method.

E.g.

List<Project__c> toUpdate = new List<Project__c>();

// You might want to consider how you identify this template record. 
// E.g. Custom Setting with the record Id or unique name
// Make sure you select the fields you want to clone.
List<Project__c> templateProjects = [Select 
         Id, Name, OtherCustomFields__c, ThatShouldBeCloned__c 
         from Project__c where Name = 'proj1' limit 1];
if(templateProjects.size() == 1) {
    Project__c templateProject = templateProjects[0];
    // The default opt_preserve_id param in clone won't clone the Id.
    Project__c opportunityProject = templateProject.clone();

    // Set any fields based on the Opportunity that weren't cloned from the template record
    opportunityProject.OpportunitySpecificCustomField__c = opp.Name;

    toUpdate.add(opportunityProject);
} else {
     // What should you do if there isn't a template record available?
}

insert toUpdate;

Incidentally, there is a dedicated salesforce.stackexchange.com for Salesforce specific questions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top