简体   繁体   中英

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 1 enter code here

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

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.
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM