Skip to main content
Joe Hayes asked in #Apex
Hi everyone,

I am fairly new to apex and trigger writing but here goes...

I have a custom object called Course_Sale. Our sales team create new course sale records and then attach an invoice in pdf format. I am trying to create a trigger that will copy the id of the attachment just uploaded to a custom field called AttachmentId__c on the Course Sale object.

This attachment id can then be passed into a custom button which will send an email template with the invoice attachment automatically.

I have started the trigger but I am not confident in writing it, It only needs to run on attachments relating to the course sale object and simply needs to copy the attachment id to attachmentId__c on the custom object.

Please can someone have a look at the code below and tell me where I am going wrong?

trigger AttachmentIDtoCourseSale on Attachment (after insert) {

List course_saleList = new List();

Set course_saleIds = new Set();

for (Attachment att : trigger.New){

if(att.ParentId.getSobjectType() == course_sale.SobjectType){

course_saleIds.add(att.ParentId);

}

}

course_saleList = [select id, from course_sale where id in : course_saleIds];

if(course_saleList!=null && course_saleList.size()>0{

course_sale.AttachmentId__c = "att.Id";

}

update course_saleList;

}

Thank you for your help,

Kind regards

Joe
4 answers
  1. Jun 29, 2016, 4:48 PM
    Hello Joe,

    Try to use following Code.

    Apex Trigger:

    trigger AttachmentIDtoCourseSale on Attachment (after insert) {

    Map<Id, Id> mapCSId = new map<Id, Id>();

    List<Course_Sal__c> lstCSUpdate = new List<Course_Sal__c>();

    String objectName = '';

    for(Attachment atc: trigger.new){

    String myIdPrefix = string.valueOf(atc.ParentId).substring(0,3);

    Map<String, Schema.SObjectType> gd = Schema.getGlobalDescribe();

    for(Schema.SObjectType stype : gd.values()){

    Schema.DescribeSObjectResult r = stype.getDescribe();

    String prefix = r.getKeyPrefix();

    if(prefix!=null && prefix.equals(myIdPrefix)){

    objectName = r.getName();

    }

    }

    if(objectName == 'Course_Sal__c'){

    mapCSId.put(atc.ParentId, atc.id);

    }

    }

    if(!mapCSId.isEmpty()){

    List<Course_Sal__c> lstCourseSal = [select id from Course_Sal__c where id in: mapCSId.keyset()];

    for(Course_Sal__c cs: lstCourseSal){

    cs.AttachmentId__c = mapCSId.get(cs.id);

    }

    if(!lstCourseSal.isEmpty()){

    update lstCourseSal;

    }

    }

    }

    Let me know if you have any question on this. Please mark this "Solved" if it helps.

    Thank You,

    Hitesh Patel

    Email :- hiteshpatel.aspl@gmail.com

    http://mrjavascript.blogspot.in/
0/9000