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
Emmanuel CoronaEmmanuel Corona 

attachment on new record

Greetings!

 

I have a custom object and a visualforce page for it.

 

On the page i would like to let the user create a new record and upload 2 files (2 attachments)

 

But i don't know how to catch the record id and then add the file to it....

 

Here is my code... I'll really appreciate your help.

 

Page:

 

<apex:page standardController="Arco__c" extensions="myArcoExtension,reCAPTCHA,AttachmentUploadController" title="Captura de Referenciados" showHeader="false" standardStylesheets="false">
    <apex:composition template="{!$Site.Template}">
        <apex:define name="body">
            <apex:form >

                <apex:messages id="error" styleClass="errorMsg" layout="table" style="margin-top:1em; background-color: #FF9300" />
                <apex:pageBlock title="" mode="edit" id="sider2_header" >
                    <apex:pageBlockButtons rendered="{!(verified)}">
                        <apex:commandButton value="Enviar" action="{!savearco}" />

                    </apex:pageBlockButtons>
                    <apex:pageBlockSection title="Programa de Referenciados" collapsible="true" columns="1"  >         

 
Por favor, captura los datos de la persona que referencias:
                        <apex:inputField value="{!Arco__c.Name}" label="Nombre (s)" required="True" style="width: 200px; height: auto; background-color:  #E0FFFF" styleclass="input"/>
                      <apex:inputCheckbox value="{!Arco__c.Aceptaci_n__c}"/>
 <apex:outputText value="Arco: "/><apex:inputText value="{!parentId}"/><br/>
        <apex:outputText value="Archivo:  "/><apex:inputFile value="{!attach.body}" filename="{!attach.name}"/><br/>
        <apex:commandButton value="Adjuntar" action="{!upload}"/>

 

Class

 

public class myArcoExtension
    {
   
      private final Arco__c webarco;
      public myArcoExtension(ApexPages.StandardController stdController)
      {
         webarco = (Arco__c)stdController.getRecord();
      }
      
        public myArcoExtension(){}
       
        public PageReference saveArco()
      {
         try {
         insert(webarco);
      }
        catch(System.DMLException e)
        {
             ApexPages.addMessages(e);
             return null;
        }
        PageReference p = Page.informacion_enviada;
        p.setRedirect(true);
       return p;
      }

 

ublic with sharing class AttachmentUploadController
{

    public AttachmentUploadController(ApexPages.StandardController controller) {

    }

    public String parentId {get;set;}
    public Attachment attach {get;set;}
 
    public AttachmentUploadController()
    {
        attach = new Attachment();
    }
 
    
    public ApexPages.Pagereference upload()
    {
       

        attach.ParentId = parentId;
        insert attach;
       
        return new ApexPages.Standardcontroller(attach).view();  
    }
}

Best Answer chosen by Admin (Salesforce Developers) 
Avidev9Avidev9
Am sweating now I guess I said this to you in earlier post "just copy the stuff to the other controller and add this line in the constructor "attach = new Attachment();""

this means you have to add the code inside this

public myArcoExtension(ApexPages.StandardController stdController)
{
webarco = (Arco__c)stdController.getRecord();
attach = new Attachment();
}

All Answers

Avidev9Avidev9
Ahh thats really simple!
Whenever you are doing a insert call on a sobject, the Id gets automatically updated in the Sobject Id Field

So after insert call you will get id in "webarco.Id"
Emmanuel CoronaEmmanuel Corona

Hello Avidev9!

 

Thank you for you response, so I only need to to replace the parent id for webarco.id???

Avidev9Avidev9
Yes thats It!!!
Just make sure you do it after insert call.
Emmanuel CoronaEmmanuel Corona

mmmm maybe i'm not understanding ....

 

I change :

 

attach.ParentId = parentId; on the AttachmentUploadController class and i get a compilation error Variable does not exist: webarco.id 

 

Or maybe i'm not explaining well...

 

I have a class for insert the new record called myArcoExtension.... at this time this only insert.

I have another class called AttachmentUploadController... it only works if i have the record id.

 

On the page i have only a field (at the moment) asking for the Arco Name, and a field for one attachment... when i press the save button i get an error because i don't have the record id to attach the file...

 

I'll really appreciate if you can explain me more a detail.

 

Avidev9Avidev9
Well you can merge the functionality in the same controller and reuse them in both the pages. This way you will be able to access "webarco"
Emmanuel CoronaEmmanuel Corona

Ok let me try to do that :)  i really appreciate your help with this thing, maybe is so easy but i'm new in sfdc and visualforce world XD

 

 

Emmanuel CoronaEmmanuel Corona

Hello Friend!

 

Please can you tell me if the logic is now ok before move the code ?

 

public class myArcoExtension
{
public Id recId
{ get;set; }
private final Arco__c webarco;
public myArcoExtension(ApexPages.StandardController stdController)
{
webarco = (Arco__c)stdController.getRecord();
}

public Attachment attach {get;set;}
public myArcoExtension(){}

public PageReference saveArco()
{
try {
insert(webarco);
attach = new Attachment();
attach.ParentId = webarco.id;

insert attach;

return new ApexPages.Standardcontroller(attach).view();
}
catch(System.DMLException e)
{
ApexPages.addMessages(e);
return null;
}
PageReference p = Page.informacion_enviada;
p.setRedirect(true);
return p;
}

 

/* Clase testMethod para validar el código y cubrir el porcentaje de cobertura */
public static testMethod void myTest() {
Lead lead = new Lead();
lead.FirstName = 'Emmanuel';
lead.LastName = 'Corona';
lead.Company = 'MCM Telecom';
insert lead;

//Create the controller
ApexPages.StandardController sc = new ApexPages.StandardController(lead);

//Create the instances of the controller
myArcoExtension myPageTest = new myArcoExtension();

myArcoExtension myPageTestSC = new myArcoExtension(sc);
myPageTestSC.saveArco();
}
}

Avidev9Avidev9
Well not really where is your upload method ?
Just merge all the functions and variables keep everything intact.

and replcae the parent with "webarco.id"
Emmanuel CoronaEmmanuel Corona

I'm doing things wrong... i get errors when i merge the class...

Here is the class for insert

public class myArcoExtension
{
public Id recId
{ get;set; }
private final Arco__c webarco;
public myArcoExtension(ApexPages.StandardController stdController)
{
webarco = (Arco__c)stdController.getRecord();
}

public myArcoExtension(){}

public PageReference saveArco()
{
try {
insert(webarco);
}
catch(System.DMLException e)
{
ApexPages.addMessages(e);
return null;
}
PageReference p = Page.informacion_enviada;
p.setRedirect(true);
return p;
}

/* Clase testMethod para validar el código y cubrir el porcentaje de cobertura */
public static testMethod void myTest() {
Lead lead = new Lead();
lead.FirstName = 'Emmanuel';
lead.LastName = 'Corona';
lead.Company = 'MCM Telecom';
insert lead;

//Create the controller
ApexPages.StandardController sc = new ApexPages.StandardController(lead);

//Create the instances of the controller
myArcoExtension myPageTest = new myArcoExtension();

myArcoExtension myPageTestSC = new myArcoExtension(sc);
myPageTestSC.saveArco();
}
}


Here is the class to upload

public with sharing class AttachmentUploadController
{

public AttachmentUploadController(ApexPages.StandardController controller) {

}
public String parentId {get;set;}
public Attachment attach {get;set;}

public AttachmentUploadController()
{
attach = new Attachment();
}


public ApexPages.Pagereference upload()
{
attach.ParentId = parentId;

insert attach;

return new ApexPages.Standardcontroller(attach).view();
}
}


I get error like the public upload function is not correct and other like unexpected token

Can you explaine me? :)

Avidev9Avidev9
public String parentId {get;set;}
public Attachment attach {get;set;}


public ApexPages.Pagereference upload()
{
attach.ParentId = parentId;
insert attach;
return new ApexPages.Standardcontroller(attach).view();
}

just copy the stuff to the other controller and add this line in the constructor "attach = new Attachment();"
Emmanuel CoronaEmmanuel Corona

Ok i have this now

 

public class myArcoExtension
{
public Id recId
{ get;set; }
private final Arco__c webarco;
public myArcoExtension(ApexPages.StandardController stdController)
{
webarco = (Arco__c)stdController.getRecord();
}

public myArcoExtension(){}

public PageReference saveArco()
{
try {
insert(webarco);
}
catch(System.DMLException e)
{
ApexPages.addMessages(e);
return null;
}
PageReference p = Page.informacion_enviada;
p.setRedirect(true);
return p;
}


public String parentId {get;set;}
public Attachment attach {get;set;}

public ApexPages.Pagereference upload()
{
attach.ParentId = parentId;
insert attach;
return new ApexPages.Standardcontroller(attach).view();
}


/* Clase testMethod para validar el código y cubrir el porcentaje de cobertura */
public static testMethod void myTest() {
Lead lead = new Lead();
lead.FirstName = 'Emmanuel';
lead.LastName = 'Corona';
lead.Company = 'MCM Telecom';
insert lead;

//Create the controller
ApexPages.StandardController sc = new ApexPages.StandardController(lead);

//Create the instances of the controller
myArcoExtension myPageTest = new myArcoExtension();

myArcoExtension myPageTestSC = new myArcoExtension(sc);
myPageTestSC.saveArco();
}
}

 

 

The record is now inserted.... but the attachment is not there... i don't get any error message...  :(

Avidev9Avidev9
Grrrrrrrrrrrrrrrrrrrrr...
I thought we replaced this line "attach.ParentId = parentId;" with the record id (webarco .Id)

And how are you calling the upload method ?
Emmanuel CoronaEmmanuel Corona

The class is:

 

public class myArcoExtension
{

private final Arco__c webarco;
public myArcoExtension(ApexPages.StandardController stdController)
{
webarco = (Arco__c)stdController.getRecord();
}

public myArcoExtension(){}

public PageReference saveArco()
{
try {
insert(webarco);
}
catch(System.DMLException e)
{
ApexPages.addMessages(e);
return null;
}
PageReference p = Page.informacion_enviada;
p.setRedirect(true);
return p;
}


public String parentId {get;set;}
public Attachment attach {get;set;}

public ApexPages.Pagereference upload()
{
attach.ParentId = webarco.id;
insert attach;
return new ApexPages.Standardcontroller(attach).view();
}


/* Clase testMethod para validar el código y cubrir el porcentaje de cobertura */
public static testMethod void myTest() {
Lead lead = new Lead();
lead.FirstName = 'Emmanuel';
lead.LastName = 'Corona';
lead.Company = 'MCM Telecom';
insert lead;

//Create the controller
ApexPages.StandardController sc = new ApexPages.StandardController(lead);

//Create the instances of the controller
myArcoExtension myPageTest = new myArcoExtension();

myArcoExtension myPageTestSC = new myArcoExtension(sc);
myPageTestSC.saveArco();
}
}

 

And in the page i have this...

 

<apex:page standardController="Arco__c" extensions="myArcoExtension" title="Interesado en Contratar Servicios de MCM" showHeader="false" standardStylesheets="true">
<apex:composition template="{!$Site.Template}">
<apex:define name="body">
<apex:form >
<apex:messages id="error"
styleClass="errorMsg"
layout="table"
style="margin-top:1em;"/>
<apex:pageBlock title="" mode="edit">
<apex:pageBlockButtons >
<apex:commandButton value="Save"
action="{!savearco}"/>
</apex:pageBlockButtons>
<apex:pageBlockSection title="Contact Us"
collapsible="false"
columns="1">
<apex:inputField value="{!Arco__c.Name}"/>

<apex:outputText value="Archivo: "/><apex:inputFile value="{!attach.body}" filename="{!attach.name}"/><br/>

</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:define>
</apex:composition>
</apex:page>

Avidev9Avidev9
Did you noticed you never called the upload method ?
that essentially means you never inserted the attachment
Emmanuel CoronaEmmanuel Corona

I thought that the save method will call it in automatic...

 

So what do you suggest me??? i don't know how i could call the upload method :(

Avidev9Avidev9
just add upload(); after insert call !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Emmanuel CoronaEmmanuel Corona

is possible to add two action in one single button???? i tried it but i i could not make it possible ... Thank you so much for your support and patience

Avidev9Avidev9

Use this 

public PageReference saveArco()
{
try {
insert(webarco); 
upload(); } catch(System.DMLException e) { ApexPages.addMessages(e); return null; } PageReference p = Page.informacion_enviada; p.setRedirect(true); return p; }

 

Emmanuel CoronaEmmanuel Corona
God!!! at the end is not so easy... lol

I get the next error

Attempt to de-reference a null object
El error está en la expresión '{!savearco}' del componente <apex:page> en page arco2

public PageReference saveArco()
{
try {
insert(webarco);
upload();
}


and here

attach.ParentId = webarco.id;
Avidev9Avidev9
Am sweating now I guess I said this to you in earlier post "just copy the stuff to the other controller and add this line in the constructor "attach = new Attachment();""

this means you have to add the code inside this

public myArcoExtension(ApexPages.StandardController stdController)
{
webarco = (Arco__c)stdController.getRecord();
attach = new Attachment();
}
This was selected as the best answer
Emmanuel CoronaEmmanuel Corona

My friend you are a master!!!!

 

Is working now!!! 

 

Thank you thank you thank you so much!!!! I really appreciate your help :D