0

I get multiple records from the records list and now I want to insert as new records in an object. Should I create a map or should I do that?

records output is

checklistTemplate__c:{Name= Test, Id = xxxxx}, checklistTemplate__c:{Name= Test2, Id = xxxxx2}


trigger CopyChecklistIntoLegitimation on Legitimation__c(after insert){

  //Get the related account's legalstructure of the legitimation
  Set<String> legalStructures = new Set<String>();
  for (Account record : [[Select LegalStructure__c from Account Where Id in 
                                (Select Account__c from Legitimation__c Where Id 
  in :Trigger.New)])
  {
    legalStructures.add(record.LegalStructure__c);
  }

 //Get the checklist templates related with the legal structure from the account related to the legitimization
 List<CustomObject__c> records = [
    Select name from ChecklistTemplate__c Where Entity__c = 'legitimation' And LegalStructure__c IN: legalStructures];

}

I am trying to achieve something like this

List<Checklist__c> newCheckLists = new List<CheckList__c>();
for(records:r){
newCheckLists.add(new CheckList__c(Name = r.Name, Status = "open", 
                                    LegitimationId__c = Trigger.New));
insert newCheckLists ;

//this inserts new Checklist records

  • Any answer please? – user3920709 Apr 25 at 5:57
  • Can you post your code using Map, as based on LegalStructure__c you need to insert CustomObject__c records. – Santanu Boral Apr 25 at 5:58
0

When you get a list of records from the query you can list of Checklist__c for each CustomObject__c as below, no need to create a map.

List<ChecklistTemplate__c> records = [SELECT Id,Name FROM ChecklistTemplate__c WHERE Entity__c = 'legitimation' AND LegalStructure__c IN: legalStructures];
List<Checklist__c> newCheckLists = new List<CheckList__c>();

for(CustomObject__c customObj: records){
    Checklist__c checkListObj = new Checklist__c(
        Name = customObj.Name,
        Status = 'open',
        LegitimationId__c = customObj.id;
    );
    newCheckLists.add(newCheckLists);
}

insert newCheckLists;
  • 1
    Hi, thanks for the answer but here LegitimationId__c cannot be obj.id that it does not come from the records list , but it should come from the legitimation Id which is Trigger.New. – user3920709 Apr 25 at 6:41
  • Hi rahul, Can I write like this, this worked but not sure.. List<ChecklistTemplate__c> records = [SELECT Id,Name FROM ChecklistTemplate__c WHERE Entity__c = 'legitimation' AND LegalStructure__c IN: legalStructures]; for(legitimation__c l : Trigger.New) { – user3920709 Apr 25 at 7:25
  • @user3920709 is there any relation between? Legitimation__c and ChecklistTemplate__c ? is LegalStructure__c is unique for all Legitimation__c records? – rahul gawale Apr 25 at 7:39

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.