0

I have below requirement to Create a VF page – ‘Registration Form’ in Account Object having

1.Name field

2.Attachment area – where we can browse and add any document there

Expected UI-

enter image description here

Below is my VF code-

<apex:page standardController="Account" extensions="InputFileControllerExtension"> 
<apex:messages /> 
<apex:form id="theForm"> 
    <apex:pageBlock >
        <apex:pageBlockSection columns="2" showHeader="true" title="Personal Details" >
            <apex:inputField value="{!Account.Name}" />
        </apex:pageBlockSection>
        <apex:pageBlockSection >
            <apex:inputFile value="{!attachment.body}" filename="{!attachment.name}"/>
            <apex:commandButton value="Upload and save" action="{!save}"/> 
        </apex:pageBlockSection> 
        </apex:pageBlock> 
</apex:form> 

Below is the APEX Class-

 public class InputFileControllerExtension
{
    private final Account acct;
    public Attachment attachment {get;set;}
    public PageReference save()
    {
        attachment.parentid = acct.id;
        insert attachment;
        return stdController.save();
    }
    public InputFileControllerExtension(ApexPages.StandardController stdController)
    { 
        attachment = new Attachment();
        this.acct = (Account)stdController.getRecord();
        this.stdController = stdController;
    } 
    ApexPages.StandardController stdController;
}

Error I am getting-

Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [Parent]: [Parent] Error is in expression '{!save}' in component in page file_upload_test: Class.InputFileControllerExtension.save: line 8, column 1

could you please help me to resolve this?

Thanks

0

The problem is, your account doesn't exist yet. So the id is not populated yet. You didn't insert it.

But there's also a problem of communication between your visualforce page variable and your extension.

First, you have to make your account variable public, with a getter and a setter, to be accessed from your visualforce page:

public final Account acct {get; set;}

Then, you'll have to use this variable is your visualforce page to link your inputfield to the account name:

<apex:inputField value="{!acct.Name}" />

Finally, you have to insert the account before inserting the attachment:

    public PageReference save()
    {
        if(acct.Name != null){
           insert acct;    

           attachment.parentid = acct.id;
           insert attachment;
        }

        return null;
    }

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.