+ Start a Discussion
ThathulaThathula 

How to insert list of Tasks at once - Apex Classes

Hi All 

I have a list of Tasks which created in a apex class;
Task task1=new Task();
task1.subject;..
...

Task task2=new Task();
task2.subject....
....

etc

myTasklist.add(task1);
myTasklist.add(task2);
......
......

And finally i need to insert all the tasks ( List) ??

How can i do that????

Thanks a lot everyone...
 
Derhyk Doggett -Derhyk Doggett -
Hi Thathula,
To insert you will need a DML statement.
To insert all the tasks in the list, simply:
insert myTasklist;

You can go a level above that and use a try/catch statement for the insert so errors are caught in the debug log, and does not halt users with an error on the page.
More information on try, catch: https://developer.salesforce.com/docs/atlas.en-us.apex_workbook.meta/apex_workbook/apex7_2.htm

Hope that helps.

-derhyk
Sumit Kumar Singh 9Sumit Kumar Singh 9
I am assuming that you have defined  "myTasklist" something like  -
List<Task> myTasklist = new List<Task>();

then, you added your tasks to the list - 

Task task1=new Task();
task1.subject;..
...

Task task2=new Task();
task2.subject....
....

etc

myTasklist.add(task1);
myTasklist.add(task2);

Finally, you need to insert the list only, something like -
if(myTasklist !=null && myTasklist.size()>0){
     insert myTasklist ;
}
Don't forget to assign values to all required fields of the task.
Hope, it will help you.
JAY_PJAY_P
Hey 
You can used array like list in your code 
List <yourobjectname__c> m = new list<yourobjectname__c>();
m.add('value ');