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
raj_sfdccraj_sfdcc 

List of Records inserting one by one?

Hi,
 
I have a strange problem..
 
I have a class where I'm inserting the records to an object from that class.
Lets say the object is Data__c..
 
I have all records in one list variable. Suppose i have 5 records in that list..
 
so., if i wrote
 insert data;(data is a list variable) all 5 records are inserted successfuly.. But I have a trigger on that object(before insert)..
 
For five records trigger is firing only once.. That trigger is firing only for the last record..
 
How to do an insert in which for all the records trigger will fire one by one..
 
Thanks
Raj
Deepak Pandey 13Deepak Pandey 13
Hi  basavaraju halaharvi,Share your Trigger.
David @ ConfigeroDavid @ Configero
First off, it is a best practice that you insert all of your records at once, usually in batch sizes up to 200 records per transaction.

There is absolutely no reason why you should want to insert one record at a time and execute the trigger with only one record.

You are doing the correct thing, and in your trigger for Data__c you need to loop these new records.
 
trigger MyDataTriggerName on Data__c (before insert) {
    for (Data__c data : Trigger.new) {
        System.debug('Single data record inside for loop here > ' + data);
        // do action for single data record here
    }
}

https://developer.salesforce.com/page/Apex_Code_Best_Practices

Please mark this as the correct answer if this has helped you.