Tuesday, December 16, 2014

Attach a File to an Object in Apex

I left out the visual force, but here is the apex code.  In this case I'm associating the attachment to a new case that's created.



   1:  public class MyController{
   2:   
   3:      public Attachment attachment {
   4:        get {
   5:            if (attachment == null){
   6:              attachment = new Attachment();
   7:            }
   8:            return attachment;
   9:          }
  10:        set;
  11:      }
  12:      
  13:      
  14:      public void myFunction() {
  15:        try{
  16:              
  17:          Case c = new Case;
  18:          /* Do all the stuffs to the case object */
  19:          INSERT c;
  20:               
  21:          attachment.OwnerId = UserInfo.getUserId();
  22:          attachment.ParentId = c.id;
  23:          attachment.IsPrivate = false;
  24:          try {
  25:            insert attachment;
  26:          } catch (DMLException e) {
  27:            ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Error uploading attachment'));
  28:          } finally {
  29:            attachment = new Attachment(); 
  30:          }  
  31:        }
  32:      }
  33:  }

No comments:

Post a Comment