1

I have created an apex class where I can insert a new record and add an attachment. it works fine when i create a record that has an attachment. But when I don't add the attachment, it does not work. How do I make it not required?

Public class ExtController{
    Public attachment atta{get; set;}
    public String Name {get;set;}
    Public Blob Body {get;set;}
    Public object__c sta{get; set;}


    Public StageExtensionController(apexpages.standardcontroller stdCon){

        obj = new object__c();
        ID id = ApexPages.currentPage().getParameters().get('id');
        obj = (id ==null)? new Stage__c() :
        [Select Name, field__c, Fes__r.Name FROM object__c 
         Where ID = :id];



             }
    public PageReference save(){

        upsert obj;
        atta= new Attachment();
        atta.Name = Name;
        atta.body = body;


        atta.ParentId = obj.id;

        insert atta;


        return null;
    }
}

1 Answer 1

3

Just check to see if Name is null, and if so, don't do anything:

if(Name != null) {
  Attachment atta = new Attachment();
  atta.Name = Name;
  atta.body = body;
  atta.ParentId = obj.id;
  insert atta;
}

As an aside, you're disassocating the standard controller from the record bound to the page, so I suggest you alter your controller:

Public class ExtController{
  // transient to avoid view state size errors
  public transient String Name {get;set;}
  Public transient Blob Body {get;set;}
  public transient String contentType { get; set; } 

  ApexPages.StandardController sc;

  Public StageExtensionController(apexpages.standardcontroller stdCon){
    sc = stdCon;
  }
  public PageReference save(){
    if(sc.save() != null && Name != null) {
      Attachment atta = new Attachment(
        Name = Name, ParentId = sc.getId(), body = body
      );
      insert atta;
    }
    return null;
  }
}
1
  • it works when i add null. however when i altered the controller it fails to insert the record Commented Oct 25, 2017 at 1:11

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .