-2

I have a function that has the DML operation inside the for loop due to which I am running into governor limit exception of 150 records. I read about batch apex on Salesforce discussion about not sure how to implement it given the function I already have working. Can someone guide me please? Thanks.

void RunObjectPermissions(String val1, String val2, String testname, String testType, String testDescription)
{
List<Temp_TestResults__c> resList= [select id from Temp_TestResults__c];
//delete resList; 
string qry = 'SELECT Parent.Profile.Name, Parent.ProfileID, ParentID, Parent.Label, Parent.Name FROM ObjectPermissions WHERE SObjectType = :val1 AND  ' + val2 + ' = True';
    List<ObjectPermissions> permSetSR = New List<ObjectPermissions>();
    permSetSR = Database.query(qry);
for(ObjectPermissions psr : permSetSR)
{
            Temp_TestResults__c results = new Temp_TestResults__c();
            {
            If (psr.Parent.ProfileID == null )
            {
                        results.Reference_Name__c =psr.Parent.Name;
                        results.Reference_Type__c = 'Permission Set';
                        results.Reference_ID__c = psr.ParentID;
                        results.Test_Name__c = testname;
                        results.Test_Type__c = testType;
                        results.Test_Description__c = testDescription;
                        insert results;                       
}



        else if(psr.Parent.ProfileID !=null && psr.Parent.Profile.Name != Null) 
            {
                    results.Reference_Name__c = psr.Parent.Profile.Name;
                    results.Reference_Type__c = 'Profile';
                    results.Reference_ID__c = psr.ParentID;
                    results.Test_Name__c = testname;
                    results.Test_Type__c = testType;
                    results.Test_Description__c = testDescription;
                    insert results;
            }
}

}
} 
1

Even in Batch Apex, you're responsible for writing bulkified code that uses governor limits efficiently. But you don't need Batch Apex here, and it's not a solution to this problem.

Here, you simply need to create a List<Temp_TestResults__c> resultsList variable and add each object you create to that list. Then, outside your for loop, do

insert resultsList;

to insert all of these objects in a batch.

This is a standard Apex pattern that you will see and use everywhere. If you're not familiar with it, taking some time to work through the excellent Trailhead materials that cover this topic will pay off as you continue to develop your code - it is absolutely critical to doing development on the Salesforce platform.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.