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
HTANIRSHTANIRS 

How to pass Opportunity id in SOQL for below trigger.

Hi, 
I need help in passing opportunity id in the below soql query for Trigger. Am using this trigger to copy attachments from opportunity to Quote whenever the quote is created from opportunity. I have hard coded the record id and i need to how to get the record id in the query.

trigger CloneAtt on Quote (after insert) {    
    
    Attachment[] attList = [SELECT id, name, body, parentid
                              FROM Attachment 
                              WHERE ParentId = '0060K00000Ra3Ei'];

    
    Attachment[] insertAttList = new Attachment[]{};
    
    for(Attachment a: attList){
        Attachment att = new Attachment(name = a.name, body = a.body, parentid = Trigger.new[0].id);
        insertAttList.add(att);
    }
    
    if(insertAttList.size() > 0){
        insert insertAttList;
    }
}
Best Answer chosen by HTANIRS
Arunkumar RArunkumar R
Hi,

Try with the below code and it will work. 
 
trigger CloneAtt on Quote (after insert) {    
    Set<Id> opportunitiesIds = new Set<Id>();
    for(Quote currQuote : Trigger.New){
        opportunitiesIds.add(currQuote.OpportunityId);
    }
    
    Map<Id, List<Attachment>> attMap = new Map<Id, List<Attachment>>();
    if(!opportunitiesIds.isEmpty()){
        for(Attachment att: [SELECT id, name, body, parentid FROM Attachment WHERE ParentId IN:opportunitiesIds]){
            if(!attMap.containsKey(att.parentid)){
                attMap.put(att.parentid, new List<Attachment>{att});
            }
            else{
                List<Attachment> attList = attMap.get(att.parentid);
                attList.add(att);
                attMap.put(att.parentid, attList);
            }
        }
    }
    
    List<Attachment> insertAttList = new List<Attachment>();
    for(Quote currQuote : Trigger.New){
        if(attMap.containsKey(currQuote.OpportunityId)){
            for(Attachment a: attMap.get(currQuote.OpportunityId)){
                Attachment att = new Attachment(name = a.name, body = a.body, parentid = currQuote.id);
                insertAttList.add(att);
            }
        }
    }
    
    if(insertAttList.size() > 0){
        insert insertAttList;
    }
}

When writing a trigger, always write a bulk code.