How to Insert and Update Record Through Trigger in a Custom Object in Salesforce

Hi I have tried the below code

trigger CreateRecord on Account (before insert,before update) {
 List<Account> CreateAcc = new List<Account>();
    For(Account acc:trigger.new)
      {
       acc.Name='abc';
       CreateAcc.add(acc);
      }
    insert CreateAcc;  
 }

but the above code is creating the following error : Review all error messages below to correct your data. Apex trigger CreateRecord caused an unexpected exception, contact your administrator: CreateRecord: execution of BeforeInsert caused by: System.SObjectException: DML statement cannot operate on trigger.new or trigger.old: Trigger.CreateRecord: line 9, column 1enter code here

Please help me through the code as where I am wrong.

1

2 Answers

Why don't you try to call a methods or function from a controller rather than putting your stuffs in trigger ?

On my end, I would do it like this ..

Create a utility controller with a methods that will insert a record

public class UtilityController
{
    @future (callout = true)
    public static void CreateRecord()
    {
       //Put your stuffs here...
    }
}

And then in the trigger, just call that method

trigger Account_CreateNewRecord on Account (before insert,before update) {
    Utility.CreateRecord();
}

Note that you can only call a method/function from another class if it has a future anotation.

I often use triggers like this to call a method on or before/after statement. That way you're trigger was just focus on executing a method/function when it was triggered. See Apex Developers Guide for more information about apex triggers.

Remove the update DML statement at the end. By using the "before" trigger to modify the Trigger.new objects, you don't need to explicitly perform an update, insert a DML statement. When the trigger ends, it will implicitly update or insert the data as you have modified the values.

trigger CreateRecord on Account (before insert,before update) {
 List<Account> CreateAcc = new List<Account>();
    For(Account acc:trigger.new)
      {
       acc.Name='abc';
       CreateAcc.add(acc);
      }
    //insert CreateAcc;  removed this line.
 }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Elena Rostova

Elena Rostova

Lead Health, Wellness & Medical Journalist

Elena Rostova holds a Master's degree in Public Health Journalism. She covers groundbreaking medical research, holistic wellness trends, mental health awareness, and nutritional science.

Share this article
Twitter Facebook Pinterest