You need to sign in to do that
Don't have an account?
Inserting mutliple records without repeating field assignments over and over
I'm trying to insert multiple records with many field assignments - mostly all the same with only one field that distinguishes one record from the next, in other words:
<my_obejct__c> mo;
if (some_condition) {
mo = new my_object__c(field1__c = 1, field2__c = 'test', field3__c = 'banana', field4__c = 3.14, field5__c = variableA);
mosToInsert.add(mo);
}
if (some_condition2) {
mo = new my_object__c(field1__c = 1, field2__c = 'test', field3__c = 'banana', field4__c = 3.14, field5__c = variableB);
mosToInsert.add(mo);
}
if (some_condition3) {
mo = new my_object__c(field1__c = 1, field2__c = 'test', field3__c = 'banana', field4__c = 3.14, field5__c = variableC);
mosToInsert.add(mo);
}
if (mosToInsert.size>0) insert mosToInsert;
Any way to define a "baseline" record for fields 1-4 and avoid all the repeated field assignments?
Thanks,
Pete
<my_obejct__c> mo;
if (some_condition) {
mo = new my_object__c(field1__c = 1, field2__c = 'test', field3__c = 'banana', field4__c = 3.14, field5__c = variableA);
mosToInsert.add(mo);
}
if (some_condition2) {
mo = new my_object__c(field1__c = 1, field2__c = 'test', field3__c = 'banana', field4__c = 3.14, field5__c = variableB);
mosToInsert.add(mo);
}
if (some_condition3) {
mo = new my_object__c(field1__c = 1, field2__c = 'test', field3__c = 'banana', field4__c = 3.14, field5__c = variableC);
mosToInsert.add(mo);
}
if (mosToInsert.size>0) insert mosToInsert;
Any way to define a "baseline" record for fields 1-4 and avoid all the repeated field assignments?
Thanks,
Pete
mo = new my_object__c(field1__c = 1, field2__c = 'test', field3__c = 'banana', field4__c = 3.14);
if (some_condition2) {
mo.field5__c = variableB;
}
if (some_condition3) {
mo.field5__c = variableC;
}
if (some_condition2 || some_condition3) {
mosToInsert.add(mo);
}
if (mosToInsert.size>0) insert mosToInsert;
Regards
note that when more than one condition is met, it seems to assign the same Id to field5__c (last in, I think?), resulting in a "Before Insert or Upsert list must not have two identically equal elements" error. I don't get it. Once "mo" is added to my list, why should it matter if I then change "mo" afterwards?
Thanks,
Pete
You also need to use a "set" with the field that is the key for preventing the duplicates.
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_set.htm
Regards.