I'm uploading an attachment via "sforce" following the example here:

Upload attachment in VisualForce without reloading the whole page

However I'm having problems getting a value for ParentId. I first tried to instantiate a new custom object in my controller constructor like this:

public Custom_object__c attachmentParent {get; set;}

public MyControllerConstructor() {
        attachmentParent = new Custom_object__c(Name="temp");
        insert attachmentParent;

But when I'm in the visualforce page and I try to set the parentId field to {!attachmentParent.Id} it comes back blank. How am I supposed to do this?

  • A record won't have an ID until it's inserted to the database. You can't add an Attachment to a record that hasn't been saved yet. – Thomas Taylor May 27 '16 at 20:25
  • Right, and I realize that, but even when I add "Insert attachmentParent" into my constructor I still don't get the Id in the page. I think it might be because insertions (DML) are not allowed in the constructor. So I'm still stuck. – asolberg May 27 '16 at 20:37

You cannot perform any DML in the constructor. If you really want to create a new parent on the fly for this page, use the action attribute on your page tag.

<apex:page controller="MyController" action="{!createParent}">

Then in your controller:

public PageReference createParent()
    attachmentParent = new Custom_object__c(Name="temp");
    insert attachmentParent;
    return null;
  • I've heard this approach will not pass the security review. I'm trying to figure out if there is a better approach to what I'm doing and end up with something that will pass security review. My end goal is to be able to save attachments to objects using sforce.connection.create but I need to know the "approved" way to get a parentId to pass in – asolberg May 27 '16 at 21:22
  • You are right, but I don't think dummy parent records for your attachment records will anyway. Can you explain in more detail why you need a dummy record? – Adrian Larson May 27 '16 at 21:24
  • Is there an actual parent already in the database and you just need to find it? – Adrian Larson May 27 '16 at 21:25
  • It's not a dummy attachment record, I'm pulling the file object from an input field and using readAsBinaryString (in the link I posted for the example). For every file the user uploads I want to save it as an attachment to a new record in Custom_object__c. Thanks for trying to help. – asolberg May 27 '16 at 21:28
  • Dummy parents. You could create one via RemoteAction instead. @asol – Adrian Larson May 27 '16 at 22:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.