+ Start a Discussion
Zoom_VZoom_V 

Custom Notes & Attachment feature for labeling & categorizing an upload

I have what is essentially a custom Notes & Attachment feature which uses a VF page to give the user the ability to leave a Note of his/her attachment as well as choose a category to put the attachment into using a dropdown picklist (Document_Type__c). 

It works fine, but I would like for a user to be able to just enter something into the Notes__c field - and not be forced to include an attachment. 

As this code is, it will create the new record without the attachment - and then go on to create the attachment and then update the record which was created. I essentially need something which would check to see if there is an attachment after initial creation of the record - and then just ending if there is no attachment, and not attempt to uplaod the file.

I think it would have to come in after this line : 
 
return Database.insert(obj);

I can't figure out how to do that. Here is the full code :
 
public class UploadAttachmentControllerProdRev {
    
    public String selectedType {get;set;}
    public Boolean selectedAwesomeness {get;set;}
    public String Note {get;set;}
    private Product_Review__c contact {get;set;} 
    public String fileName {get;set;}
    public Blob fileBody {get;set;}
    
    public String contactproduct {get;set;}
    
    public UploadAttachmentControllerVendorProdRev(ApexPages.StandardController controller) { 
        this.contact = (Product_Review__c)controller.getRecord();
        //contactproduct = contact.Product__c;
    }   
    
    // creates a new Product_Review_Attachment__c record
    private Database.SaveResult saveCustomAttachment() {
        Product_Review_Attachment__c obj = new Product_Review_Attachment__c();
        obj.Product_Review__c = contact.Id; 
        obj.Product__c = contact.Product__c;
        obj.Note__c = Note;
        obj.Document_type__c = selectedType;
        //obj.awesome__c = selectedAwesomeness;
        // fill out cust obj fields
        return Database.insert(obj);
    }
    
    // create an actual Attachment record with the Product_Review_Attachment__c as parent
    private Database.SaveResult saveStandardAttachment(Id parentId) {
        Database.SaveResult result;
        
        Attachment attachment = new Attachment();
        attachment.body = this.fileBody;
        attachment.name = this.fileName;
        attachment.parentId = parentId;
        // inser the attahcment
        result = Database.insert(attachment);
        // reset the file for the view state
        fileBody = Blob.valueOf(' ');
        return result;
    }
    
    /**
    * Upload process is:
    *  1. Insert new Product_Review_Attachment__c record
    *  2. Insert new Attachment with the new Product_Review_Attachment__c record as parent
    *  3. Update the Product_Review_Attachment__c record with the ID of the new Attachment
    **/
    public PageReference processUpload() {
        try {
            Database.SaveResult customAttachmentResult = saveCustomAttachment();
        
            if (customAttachmentResult == null || !customAttachmentResult.isSuccess()) {
                ApexPages.AddMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 
                  'Could not save attachment.'));
                return null;
            }
        
            Database.SaveResult attachmentResult = saveStandardAttachment(customAttachmentResult.getId());
        
            if (attachmentResult == null || !attachmentResult.isSuccess()) {
                ApexPages.AddMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 
                  'Could not save attachment.'));            
                return null;
            } else {
                // update the custom attachment record with some attachment info
                Product_Review_Attachment__c customAttachment = [select id from Product_Review_Attachment__c where id = :customAttachmentResult.getId()];
                customAttachment.name = this.fileName;
                customAttachment.Attachment__c = attachmentResult.getId();
                update customAttachment;
            }
        
        } catch (Exception e) {
            ApexPages.AddMessages(e);
            return null;
        }
        
        return new PageReference('/'+contact.Id);
    }
    
    public PageReference back() {
        return new PageReference('/'+contact.Id);
    }     
}


Thank you for your help. 
Best Answer chosen by Zoom_V
UC InnovationUC Innovation
Hope this works for you
public class UploadAttachmentControllerVendorProdRev {
   
    public String selectedType {get;set;}
    public Boolean selectedAwesomeness {get;set;}
    public String description {get;set;}
    private Product_Review__c contact {get;set;}
    public String fileName {get;set;}
    public Blob fileBody {get;set;}
   
    public String contactproduct {get;set;}
   
    public UploadAttachmentControllerProdRev(ApexPages.StandardController controller) {
        this.contact = (Product_Review__c)controller.getRecord();
       
    
    }  
   
    // creates a new Product_Review_Attachment__c record
   
    private Database.SaveResult saveCustomAttachment() {
  
        Product_Review_Attachment__c obj = new Product_Review_Attachment__c();
        obj.Product_Review__c = contact.Id;
        obj.Product__c = contact.Product__c;
        obj.Description__c = description;
        obj.Document_type__c = selectedType;
        // fill out cust obj fields
        return Database.insert(obj);
    }
   
    // create an actual Attachment record with the Product_Review_Attachment__c as parent
             
    private Database.SaveResult saveStandardAttachment(Id parentId) {
    
        Database.SaveResult result;
       
        Attachment attachment = new Attachment();
        attachment.body = this.fileBody;
        attachment.name = this.fileName;
        attachment.parentId = parentId;
        // insert the attahcment
        result = Database.insert(attachment);
        // reset the file for the view state
        fileBody = Blob.valueOf(' ');
        return result;
    }
   
    /**
    * Upload process is:
    *  1. Insert new Product_Review_Attachment__c record
    *  2. Insert new Attachment with the new Product_Review_Attachment__c record as parent
    *  3. Update the Product_Review_Attachment__c record with the ID of the new Attachment
    **/
    public PageReference processUpload() {
   
        if(description =='')
		{
			ApexPages.AddMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'You must include as least a Description.'));
			
			return null;
		}
   
   
		try {
            Database.SaveResult customAttachmentResult = saveCustomAttachment();
       
            if (!customAttachmentResult.isSuccess()) {
                //ApexPages.AddMessage(new ApexPages.Message(ApexPages.Severity.ERROR,
                  //'Could not save attachment because either filebody was empty or the customAttachmentResult was unsuccessful.'));
                return null;
                system.debug('customattachmentresult **************!!! ');
                return new PageReference('/'+contact.Id);
            }
      
			if (filebody != null) {
				Database.SaveResult attachmentResult = saveStandardAttachment(customAttachmentResult.getId());
		   
				if (attachmentResult == null || !attachmentResult.isSuccess()) {
					//ApexPages.AddMessage(new ApexPages.Message(ApexPages.Severity.ERROR,
					  //'Could not save attachment.'));           
					//return null;
					return new PageReference('/'+contact.Id);
				} else {
					// update the custom attachment record with some attachment info
					Product_Review_Attachment__c customAttachment = [select id from Product_Review_Attachment__c where id = :customAttachmentResult.getId()];
					customAttachment.name = this.fileName;
					customAttachment.Attachment__c = attachmentResult.getId();
					update customAttachment;
				}
			}
       } catch (Exception e) {
          ApexPages.AddMessages(e);
          return null;
       }
       
        return new PageReference('/'+contact.Id);
    }
   
    public PageReference back() {
        return new PageReference('/'+contact.Id);
    }    
}

:

 

All Answers

UC InnovationUC Innovation
Are you saying that once you create the Product_Review_Attachment__c record, if there is no attachment associated with the Product_Review_Attachment__c record, then just return to the contact page?  If so, how do we determine if there's no attachment?  Can we assume that this.fileBody or this.fileName is null or empty?  If so, we can use one of those fields to check for null or empty at before line 60 above.  If it's not null/empty, then process line 60 to 72.  It would look something like:
 
if (!String.isBlank(this.fileBody)) {     
	Database.SaveResult attachmentResult = saveStandardAttachment(customAttachmentResult.getId());

	if (attachmentResult == null || !attachmentResult.isSuccess()) {
		ApexPages.AddMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 
		  'Could not save attachment.'));            
		return null;
	} else {
		// update the custom attachment record with some attachment info
		Product_Review_Attachment__c customAttachment = [select id from Product_Review_Attachment__c where id = :customAttachmentResult.getId()];
		customAttachment.name = this.fileName;
		customAttachment.Attachment__c = attachmentResult.getId();
		update customAttachment;
	}
}

 
Zoom_VZoom_V
Thank you very much for your response. I'm confused exactly where you are talking about putting that code you have. The error that I am getting when there is no attachment is coming from line 34. That is where filebody is referred to for the first time. In the debug log it is showing up as null.

Are you suggesting putting it into line 43 ? If so, that would be after the line producing the error.

Thanks again.
 
UC InnovationUC Innovation
The full code would look like this:
 
public class UploadAttachmentControllerProdRev {
    
    public String selectedType {get;set;}
    public Boolean selectedAwesomeness {get;set;}
    public String Note {get;set;}
    private Product_Review__c contact {get;set;} 
    public String fileName {get;set;}
    public Blob fileBody {get;set;}
    
    public String contactproduct {get;set;}
    
    public UploadAttachmentControllerVendorProdRev(ApexPages.StandardController controller) { 
        this.contact = (Product_Review__c)controller.getRecord();
        //contactproduct = contact.Product__c;
    }   
    
    // creates a new Product_Review_Attachment__c record
    private Database.SaveResult saveCustomAttachment() {
        Product_Review_Attachment__c obj = new Product_Review_Attachment__c();
        obj.Product_Review__c = contact.Id; 
        obj.Product__c = contact.Product__c;
        obj.Note__c = Note;
        obj.Document_type__c = selectedType;
        //obj.awesome__c = selectedAwesomeness;
        // fill out cust obj fields
        return Database.insert(obj);
    }
    
    // create an actual Attachment record with the Product_Review_Attachment__c as parent
    private Database.SaveResult saveStandardAttachment(Id parentId) {
        Database.SaveResult result;
        
        Attachment attachment = new Attachment();
        attachment.body = this.fileBody;
        attachment.name = this.fileName;
        attachment.parentId = parentId;
        // inser the attahcment
        result = Database.insert(attachment);
        // reset the file for the view state
        fileBody = Blob.valueOf(' ');
        return result;
    }
    
    /**
    * Upload process is:
    *  1. Insert new Product_Review_Attachment__c record
    *  2. Insert new Attachment with the new Product_Review_Attachment__c record as parent
    *  3. Update the Product_Review_Attachment__c record with the ID of the new Attachment
    **/
    public PageReference processUpload() {
        try {
            Database.SaveResult customAttachmentResult = saveCustomAttachment();
        
            if (customAttachmentResult == null || !customAttachmentResult.isSuccess()) {
                ApexPages.AddMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 
                  'Could not save attachment.'));
                return null;
            }

			if (!String.isBlank(this.fileBody)) {   // REPLACE THIS CONDITION WITH CORRECT CONDITION TO CHECK IF ATTACHMENT EXISTS 
				Database.SaveResult attachmentResult = saveStandardAttachment(customAttachmentResult.getId());
			
				if (attachmentResult == null || !attachmentResult.isSuccess()) {
					ApexPages.AddMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 
					  'Could not save attachment.'));            
					return null;
				} else {
					// update the custom attachment record with some attachment info
					Product_Review_Attachment__c customAttachment = [select id from Product_Review_Attachment__c where id = :customAttachmentResult.getId()];
					customAttachment.name = this.fileName;
					customAttachment.Attachment__c = attachmentResult.getId();
					update customAttachment;
				}
			}
        
        } catch (Exception e) {
            ApexPages.AddMessages(e);
            return null;
        }
        
        return new PageReference('/'+contact.Id);
    }
    
    public PageReference back() {
        return new PageReference('/'+contact.Id);
    }     
}


For the following line:

if (!String.isBlank(this.fileBody)) { // REPLACE THIS CONDITION WITH CORRECT CONDITION TO CHECK IF ATTACHMENT EXISTS

I'm assuming that we can use this.fileBody to determine if an attachment exists.  Since you said that the debug log is showing null for this.fileBody in line 34, then this condition will most likely work.  Basically, the updated code says that if the attachment doesn't exist (or isn't specified), then skip the code that creates the standard attachment and update the already created Product_Review_Attachment__c record.  Thus, line 34 will never get called if there's no attachment.

Hope that makes sense.
 
Zoom_VZoom_V

UC - thank you very much for this. It makes sense to me. I can see what you are attempting in your reference to the filebody (although I'm wondering if filename would be a better reference). 

I am attempting to implement the changes but am getting some errors.The current error I am getting is a "Variable does not exist : String at line 61 column 18". I can't see what is causing that problem.

Some other questions :

- Why have you created a Note string (line 5) and a Note__c field (line 23) ?

- Does line 61 need another condition to be put there ? I would like for the code to just end if there is no attachment, so would this be correct to put into the line once it is working  : ?

 

return new PageReference('/'+contact.Id);
 

Thank you very much.
 

Zoom_VZoom_V
Another question : Once it is properly saved, won't your code still produce an error from line 34 when run ?
UC InnovationUC Innovation
If filename works better, use that instead.  I think you'll need to paste the code you are actually using to see what line 61 is for you.  Line 61 on the code I pasted references:

    Database.SaveResult attachmentResult = saveStandardAttachment(customAttachmentResult.getId());

Is that the same line for your code?

As for your question:

"Why have you created a Note string (line 5) and a Note__c field (line 23) ?"

That was just a cut and paste from your original code.

For your question:

"Does line 61 need another condition to be put there ? I would like for the code to just end if there is no attachment, so would this be correct to put into the line once it is working  : ?"

I don't think so.  If there's no attachment, then the following statement should be false:

"if (!String.isBlank(this.fileBody))"

If it's false, then lines 61-73 would not be executed.  The next code statement to execute afterwards would be line 81, which is:

"return new PageReference('/'+contact.Id);"

Finally, for your last question:

"Another question : Once it is properly saved, won't your code still produce an error from line 34 when run ?"

No, it won't be executed if there's no attachment.  Line 34 is within the function saveStandardAttachment().  That fuction won't get called if there's no attachment.

Hope that helps.
Zoom_VZoom_V
UC - thank you again, really appreciate it. Let me show you where I am at right now. As it is, this will prevent a new Proudct_Review_Attachment__c record from being included if there is no Description AND no file included.

 
public class UploadAttachmentControllerVendorProdRev {
   
    public String selectedType {get;set;}
    public Boolean selectedAwesomeness {get;set;}
    public String description {get;set;}
    private Product_Review__c contact {get;set;}
    public String fileName {get;set;}
    public Blob fileBody {get;set;}
   
    public String contactproduct {get;set;}
   
    public UploadAttachmentControllerProdRev(ApexPages.StandardController controller) {
        this.contact = (Product_Review__c)controller.getRecord();
       
    
    }  
   
    // creates a new Product_Review_Attachment__c record
   
    private Database.SaveResult saveCustomAttachment() {
  
        Product_Review_Attachment__c obj = new Product_Review_Attachment__c();
        obj.Product_Review__c = contact.Id;
        obj.Product__c = contact.Product__c;
        obj.Description__c = description;
        obj.Document_type__c = selectedType;
        // fill out cust obj fields
        return Database.insert(obj);
    }
   
    // create an actual Attachment record with the Product_Review_Attachment__c as parent
             
    private Database.SaveResult saveStandardAttachment(Id parentId) {
    
        Database.SaveResult result;
       
        Attachment attachment = new Attachment();
        attachment.body = this.fileBody;
        attachment.name = this.fileName;
        attachment.parentId = parentId;
        // insert the attahcment
        result = Database.insert(attachment);
        // reset the file for the view state
        fileBody = Blob.valueOf(' ');
        return result;
    }
   
    /**
    * Upload process is:
    *  1. Insert new Product_Review_Attachment__c record
    *  2. Insert new Attachment with the new Product_Review_Attachment__c record as parent
    *  3. Update the Product_Review_Attachment__c record with the ID of the new Attachment
    **/
    public PageReference processUpload() {
   
        if(description =='' & filebody==null)
                {
                ApexPages.AddMessage(new ApexPages.Message(ApexPages.Severity.ERROR,
                'You must include either a file or a Description.'));
                    return null;
                }
   
   
    try {
            Database.SaveResult customAttachmentResult = saveCustomAttachment();
       
            if (!customAttachmentResult.isSuccess()) {
                //ApexPages.AddMessage(new ApexPages.Message(ApexPages.Severity.ERROR,
                  //'Could not save attachment because either filebody was empty or the customAttachmentResult was unsuccessful.'));
                return null;
                system.debug('customattachmentresult **************!!! ');
                return new PageReference('/'+contact.Id);
            }
      
            Database.SaveResult attachmentResult = saveStandardAttachment(customAttachmentResult.getId());
       
            if (attachmentResult == null || !attachmentResult.isSuccess()) {
                //ApexPages.AddMessage(new ApexPages.Message(ApexPages.Severity.ERROR,
                  //'Could not save attachment.'));           
                //return null;
                return new PageReference('/'+contact.Id);
            } else {
                // update the custom attachment record with some attachment info
                Product_Review_Attachment__c customAttachment = [select id from Product_Review_Attachment__c where id = :customAttachmentResult.getId()];
                customAttachment.name = this.fileName;
                customAttachment.Attachment__c = attachmentResult.getId();
                update customAttachment;
            }
       
       } catch (Exception e) {
          ApexPages.AddMessages(e);
          return null;
       }
       
        return new PageReference('/'+contact.Id);
    }
   
    public PageReference back() {
        return new PageReference('/'+contact.Id);
    }    
}





I would like the system to create a new record if the user at leasts includes a Description. Right now, I can't figure out how to do that because it keeps trying to create the Attachment every time. If you can't help me do that I'll be set.

Thanks again for any help you could give. 
UC InnovationUC Innovation
Hope this works for you
public class UploadAttachmentControllerVendorProdRev {
   
    public String selectedType {get;set;}
    public Boolean selectedAwesomeness {get;set;}
    public String description {get;set;}
    private Product_Review__c contact {get;set;}
    public String fileName {get;set;}
    public Blob fileBody {get;set;}
   
    public String contactproduct {get;set;}
   
    public UploadAttachmentControllerProdRev(ApexPages.StandardController controller) {
        this.contact = (Product_Review__c)controller.getRecord();
       
    
    }  
   
    // creates a new Product_Review_Attachment__c record
   
    private Database.SaveResult saveCustomAttachment() {
  
        Product_Review_Attachment__c obj = new Product_Review_Attachment__c();
        obj.Product_Review__c = contact.Id;
        obj.Product__c = contact.Product__c;
        obj.Description__c = description;
        obj.Document_type__c = selectedType;
        // fill out cust obj fields
        return Database.insert(obj);
    }
   
    // create an actual Attachment record with the Product_Review_Attachment__c as parent
             
    private Database.SaveResult saveStandardAttachment(Id parentId) {
    
        Database.SaveResult result;
       
        Attachment attachment = new Attachment();
        attachment.body = this.fileBody;
        attachment.name = this.fileName;
        attachment.parentId = parentId;
        // insert the attahcment
        result = Database.insert(attachment);
        // reset the file for the view state
        fileBody = Blob.valueOf(' ');
        return result;
    }
   
    /**
    * Upload process is:
    *  1. Insert new Product_Review_Attachment__c record
    *  2. Insert new Attachment with the new Product_Review_Attachment__c record as parent
    *  3. Update the Product_Review_Attachment__c record with the ID of the new Attachment
    **/
    public PageReference processUpload() {
   
        if(description =='')
		{
			ApexPages.AddMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'You must include as least a Description.'));
			
			return null;
		}
   
   
		try {
            Database.SaveResult customAttachmentResult = saveCustomAttachment();
       
            if (!customAttachmentResult.isSuccess()) {
                //ApexPages.AddMessage(new ApexPages.Message(ApexPages.Severity.ERROR,
                  //'Could not save attachment because either filebody was empty or the customAttachmentResult was unsuccessful.'));
                return null;
                system.debug('customattachmentresult **************!!! ');
                return new PageReference('/'+contact.Id);
            }
      
			if (filebody != null) {
				Database.SaveResult attachmentResult = saveStandardAttachment(customAttachmentResult.getId());
		   
				if (attachmentResult == null || !attachmentResult.isSuccess()) {
					//ApexPages.AddMessage(new ApexPages.Message(ApexPages.Severity.ERROR,
					  //'Could not save attachment.'));           
					//return null;
					return new PageReference('/'+contact.Id);
				} else {
					// update the custom attachment record with some attachment info
					Product_Review_Attachment__c customAttachment = [select id from Product_Review_Attachment__c where id = :customAttachmentResult.getId()];
					customAttachment.name = this.fileName;
					customAttachment.Attachment__c = attachmentResult.getId();
					update customAttachment;
				}
			}
       } catch (Exception e) {
          ApexPages.AddMessages(e);
          return null;
       }
       
        return new PageReference('/'+contact.Id);
    }
   
    public PageReference back() {
        return new PageReference('/'+contact.Id);
    }    
}

:

 
This was selected as the best answer
Zoom_VZoom_V
That did the trick. Thank you very much UC !
UC InnovationUC Innovation
No problem.  Good luck!