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
vpmvpm 

how to get ParentID

Hi,

 

I have a custom object which has lookup relationship with account. For attachment info, ParentId is required. How can I get parentId?

 

http://blog.jeffdouglas.com/2010/04/28/uploading-an-attachment-using-visualforce-and-a-custom-controller/

 

I tried the above link. I got errors like,

 

  • Required fields are missing: [Parent]
  • Error uploading attachment

 

Please suggest me to rectify my error.

Best Answer chosen by Admin (Salesforce Developers) 
asish1989asish1989

Try this code and let me know it works or not 

public with sharing class AttachmentUploadController {

	private id bioId;
	public Bio_Briefing__c bioBriefing{get;set;}
	public AttachmentUploadController(ApexPages.StandardController controller) {

		this.bioId = ApexPages.currentPage().getParameters().get('id');
		bioBriefing = new Bio_Briefing__c();
		bioBriefing = [Select Id from Bio_Briefing__c where id=:bioId];

	}

	public Attachment attachment {
		get {
			if (attachment == null)
			attachment = new Attachment();
			return attachment;
		}
		set;
	}

	

	public PageReference wew() {

		attachment.OwnerId = UserInfo.getUserId();
		attachment.ParentId = bioBriefing.Id; // the record the file is attached to
		attachment.IsPrivate = true;

		try {
			insert attachment;
		} catch (DMLException e) {
			ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Error uploading attachment'));
			return null;
		} finally {
			attachment = new Attachment();
		}

		ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO,'Attachment uploaded successfully'));
		PageReference ReturnPage = new PageReference('/'+ApexPages.currentPage().getParameters().get('id'));
		ReturnPage.setRedirect(true);
		return ReturnPage;
	}

}

 

All Answers

Avidev9Avidev9

Well the ParentId is the Id of object to which you are attaching the Attachment. So here it will be Id of you custom object

 

public with sharing class AttachmentUploadController {
 
  public Attachment attachment {
  get {
      if (attachment == null)
        attachment = new Attachment();
      return attachment;
    }
  set;
  }
 
  public PageReference upload() {
 
    attachment.OwnerId = UserInfo.getUserId();
    attachment.ParentId = '0037000000lFxcw'; // the record the file is attached to, You may need to do a query to get your parent recordid
    attachment.IsPrivate = true;
 
    try {
      insert attachment;
    } catch (DMLException e) {
      ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Error uploading attachment'));
      return null;
    } finally {
      attachment = new Attachment(); 
    }
 
    ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO,'Attachment uploaded successfully'));
    return null;
  }
 
}

 

vpmvpm
Hi,
Thanks for your reply.
I got the below error. Please point my mistake. Bio_Briefing__c is my custom object.
Error: Compile Error: Variable does not exist: Bio_Briefing__c at line 27 column 26

//Controller
public with sharing class AttachmentUploadController {

private id bioId;
public AttachmentUploadController(ApexPages.StandardController controller) {

this.bioId=ApexPages.currentPage().getParameters().get('id');

}

public Attachment attachment {
get {
if (attachment == null)
attachment = new Attachment();
return attachment;
}
set;
}

public Bio_Briefing__c getId(){

return[Select id from Bio_Briefing__c where id=:bioId];
}

public PageReference wew() {

attachment.OwnerId = UserInfo.getUserId();
attachment.ParentId =Bio_Briefing__c.getId(); // the record the file is attached to
attachment.IsPrivate = true;

try {
insert attachment;
} catch (DMLException e) {
ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Error uploading attachment'));
return null;
} finally {
attachment = new Attachment();
}

ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO,'Attachment uploaded successfully'));
PageReference ReturnPage = new PageReference('/'+ApexPages.currentPage().getParameters().get('id'));
ReturnPage.setRedirect(true);
return ReturnPage;
}

}
asish1989asish1989

Try this code and let me know it works or not 

public with sharing class AttachmentUploadController {

	private id bioId;
	public Bio_Briefing__c bioBriefing{get;set;}
	public AttachmentUploadController(ApexPages.StandardController controller) {

		this.bioId = ApexPages.currentPage().getParameters().get('id');
		bioBriefing = new Bio_Briefing__c();
		bioBriefing = [Select Id from Bio_Briefing__c where id=:bioId];

	}

	public Attachment attachment {
		get {
			if (attachment == null)
			attachment = new Attachment();
			return attachment;
		}
		set;
	}

	

	public PageReference wew() {

		attachment.OwnerId = UserInfo.getUserId();
		attachment.ParentId = bioBriefing.Id; // the record the file is attached to
		attachment.IsPrivate = true;

		try {
			insert attachment;
		} catch (DMLException e) {
			ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Error uploading attachment'));
			return null;
		} finally {
			attachment = new Attachment();
		}

		ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO,'Attachment uploaded successfully'));
		PageReference ReturnPage = new PageReference('/'+ApexPages.currentPage().getParameters().get('id'));
		ReturnPage.setRedirect(true);
		return ReturnPage;
	}

}

 

This was selected as the best answer
Avidev9Avidev9

Your error was in calling the method "getId()"

You have defined a method that returns "Bio_Briefing__c" and you were not calling it properly.

 

The call should be

 

 

public with sharing class AttachmentUploadController {

    private id bioId;
    public AttachmentUploadController(ApexPages.StandardController controller) {

        this.bioId = ApexPages.currentPage().getParameters().get('id');

    }

    public Attachment attachment {
        get {
            if (attachment == null)
                attachment = new Attachment();
            return attachment;
        }
        set;
    }
    //give it a better name, something like getBioBriefing
    public Bio_Briefing__c getId() {

        return [Select id from Bio_Briefing__c where id = : bioId];
    }

    public PageReference wew() {

        attachment.OwnerId = UserInfo.getUserId();
        attachment.ParentId = getId().Id; 
        attachment.IsPrivate = true;

        try {
            insert attachment;
        } catch (DMLException e) {
            ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR, 'Error uploading attachment'));
            return null;
        } finally {
            attachment = new Attachment();
        }

        ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO, 'Attachment uploaded successfully'));
        PageReference ReturnPage = new PageReference('/' + ApexPages.currentPage().getParameters().get('id'));
        ReturnPage.setRedirect(true);
        return ReturnPage;
    }

}

 

vpmvpm

Thanks. It is working.
I want to display the image file in custom object detail view page. How can i set this attachment ==that custom field?

 Like "Attach File" button in Notes and Attachments.

 

//My vf Page:

<apex:page standardController="Bio_Briefing__c" extensions="AttachmentUploadController">
  <apex:form >
  <apex:pageBlock title="Attach File" >
 
  <h1>1.Select the File</h1>
  <p>Type the path of the file or click the Browse button to find the file </p>
  <apex:outputLabel for="fileName"/>
  <apex:inputText value="{!attachment.body}"  id="fileName"/>
  <apex:commandButton value="Browse" action="{!browse}"/><br/>
 
 
 
  <h1>2.Click the "Attach File" button.</h1>
  <p>Repeat steps 1 and 2 to attach multiple files </p>
  <p>(When the upload is completed the file information will appear below)</p><br/>
  <apex:commandButton value="Attach File" action="{!upload}"/>
 
  <br/>
  <h1>3.Click the Done button to return to the previous page</h1>
  <p>(This will cancel an in-progress upload. )</p><br/>
  <apex:commandButton value="Done" action="{!saveFile}"/>
 
  </apex:pageBlock>
  </apex:form>
</apex:page>

 

1.Browse button is to call local machine folder Without using <apex:inputFile>

2.Attachment should be done by using attach file button.

3.Done button is to return to detail page of my record with the attachment in my custom field.

vpmvpm
Hi,

I got this error.

System.NullPointerException: Argument cannot be null.
Error is in expression '{!saveFile}' in page attachfile

My code:
//vf
<apex:page standardController="Bio_Briefing__c" extensions="upLoadExtension" showHeader="false" sidebar="false">

<apex:form >
<apex:pageMessages />
<apex:pageBlock title="Attach File" >

<h1>1.Select the File</h1>
<p>Type the path of the file or click the Browse button to find the file </p>
<apex:inputFile value="{!attachment.body}" filename="{!attachment.name}" fileSize="{!attachment.bodyLength}" contentType="{!attachment.contentType}" id="file"/>
<br/>




<h1>2.Click the "Attach File" button.</h1>
<p>Repeat steps 1 and 2 to attach multiple files </p>
<p>(When the upload is completed the file information will appear below)</p><br/>
<apex:commandButton value="Attach File" action="{!upload}"/>

<br/>
<h1>3.Click the Done button to return to the previous page</h1>
<p>(This will cancel an in-progress upload. )</p><br/>
<apex:commandButton value="Done" action="{!saveFile}"/>

</apex:pageBlock>
</apex:form>


</apex:page>

//controller

public class upLoadExtension{

private id bioId;
public blob photo;
public String image;
public Bio_Briefing__c bioBriefing{get;set;}
public uploadExtension(ApexPages.StandardController controller) {

this.bioId = ApexPages.currentPage().getParameters().get('id');
bioBriefing = new Bio_Briefing__c();
bioBriefing = [Select Id,Biographic_Photo__c from Bio_Briefing__c where id=:bioId];

}

public Attachment attachment {
get {
if (attachment == null)
attachment = new Attachment();
return attachment;
}
set;
}
public PageReference upload() {

attachment.OwnerId = UserInfo.getUserId();
attachment.ParentId = bioBriefing.Id; // the record the file is attached to
attachment.IsPrivate = true;

try {
insert attachment;
} catch (DMLException e) {
ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Error uploading attachment'));
return null;
} finally {
attachment = new Attachment();
}

return null;

}
public PageReference saveFile(){

photo=attachment.body;
image=bioBriefing.Biographic_Photo__c;
if(image==null){
image=EncodingUtil.base64Encode(photo);
}
insert biobriefing;
PageReference ReturnPage = new PageReference('/'+ApexPages.currentPage().getParameters().get('id'));
ReturnPage.setRedirect(true);
return ReturnPage;
}
}
asish1989asish1989

Try this...

give id of Bio_Briefing__c object in the url

//controller

public class upLoadExtension{

    private id bioId;
    public blob photo;
    public String image;
    public Bio_Briefing__c bioBriefing{get;set;}
    public uploadExtension(ApexPages.StandardController controller) {

        this.bioId = ApexPages.currentPage().getParameters().get('id');
        bioBriefing = new Bio_Briefing__c();
        bioBriefing = [Select Id,Biographic_Photo__c from Bio_Briefing__c where id=:bioId];
 
    }

    public Attachment attachment {
        get {
            if (attachment == null)
            attachment = new Attachment();
            return attachment;
        }
        set;
    }
    public PageReference upload() {

        attachment.OwnerId = UserInfo.getUserId();
        attachment.ParentId = bioBriefing.Id; // the record the file is attached to
        attachment.IsPrivate = true;

        try {
            insert attachment;
        } catch (DMLException e) {
            ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Error uploading attachment'));
            return null;
        } finally {
        attachment = new Attachment();
        }

        return null;

    }
    public PageReference saveFile(){

        photo=attachment.body;
        image=bioBriefing.Biographic_Photo__c;
        if(image==null){
            image=EncodingUtil.base64Encode(photo);
        }
        upsert biobriefing;
        PageReference ReturnPage = new PageReference('/'+ApexPages.currentPage().getParameters().get('id'));
        ReturnPage.setRedirect(true);
        return ReturnPage;
    }
}

vpmvpm
Thanks. That is not working. I'm getting this error, after i click the"Done" button.

Visualforce Error
Help for this Page

System.NullPointerException: Argument cannot be null.
Error is in expression '{!saveFile}' in page attachfile

An unexpected error has occurred. Your solution provider has been notified. (system)
asish1989asish1989

Remove that finally block just below catch and then try it.

please delete this

    finally {
        attachment = new Attachment();
        }

I hope It will work.

asish1989asish1989

Hi

please give kudos(click on star icon) for the post which seems to be helpful for you so that others get benifited in some situations.

 

Thanks

 

vpmvpm
Hi asish1989,
I want to display the image in vf page from attachments. I tried it
{!URLFOR($Action.Attachment.Download, p.Id)}
I couldn't able to get the image.
Thanks.
asish1989asish1989

<img src="{!URLFOR($Action.Attachment.Download, attachmentId)}" />
<a href="{!URLFOR($Action.Attachment.Download, attachmentId)}" >blah blah</a>

<apex:outputText >
<a href="{!URLFOR($Action.Attachment.Download, returnAttachmentID )}">View File</a>
</apex:outputText>

<!-- or -->

<apex:outputText >
<a href="{!URLFOR($Action.Attachment.Download, 'returnAttachmentID' )}">View File</a>
</apex:outputText>