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
Lewis BlauLewis Blau 

Related List Button To Select existing records

The scenario is as follows. On an Opportunity, I have a lookup to a custom object. The corresponding related list on the custom object has a 'New' button to create new Opportunities from the custom object. Users want to click a button on the related list that displays a screen to select an existing Opportunity and associate a selected Opportunity to the related list on the custom object. 
 
Best Answer chosen by Lewis Blau
Zuinglio Lopes Ribeiro JúniorZuinglio Lopes Ribeiro Júnior
Hello,

Not sure if I got it right but here's one way to do it:

I based my example on Account object as I don't have your custom object. Replace Account by your custom object.

1-) Create a custom related list button in Opportunity as shown below:

User-added image


2-) Add the url below to your button:

/apex/AssociateOpportunity?id={!Account.Id}

3-) Add the button to the Opportunity's related list in Account's page layout:

User-added image
User-added image


4-) Create a custom lookup field for Opportunity in Account (this is a trick to get the lookup field of Opportunity working in the Visualforce). This button won't be visible and will not be added to any layouts and won't include any related list.

User-added image


5-) Create a controller class (I named it AssociateOpportunityExtController): 
 
public with sharing class AssociateOpportunityExtController {

    public Account account  { get; set; }
    
    public AssociateOpportunityExtController() {
        
        String accountId = ApexPages.currentPage().getParameters().get('id');
        account = [SELECT Id, Name, Opportunity__c FROM Account WHERE Id =: accountId];
        
    }
    
    public PageReference associate () {
        
        Opportunity opp = new Opportunity ( Id = account.Opportunity__c, AccountId = account.Id);
        
        try {
        	Database.update(opp);
        } catch (Exception error) {
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Error while associating.' + error.getMessage()));
        }
        
        PageReference page = new PageReference('/' + account.Id);
        
        return page.setRedirect(true);
    }
    
    public PageReference cancel () {
        PageReference page = new PageReference('/' + account.Id);
        return page.setRedirect(true);        
    }
    
}

6-) Create a Visualforce (I named it AssociateOpportunity):
 
<apex:page controller="AssociateOpportunityExtController">
    <apex:form>
        <apex:pageblock title="Associate Opportunity to Custom Object">
            <apex:pageMessages />
            <apex:pageblockbuttons location="top">
                <apex:commandbutton value="Associate" action="{!associate}" />
                <apex:commandbutton value="Cancel" action="{!cancel}"/>
            </apex:pageblockbuttons>
            <apex:pageBlockSection>
                <apex:pageBlockSectionItem>
                    <apex:outputLabel>Account Name</apex:outputLabel>
                    <apex:outputText>{!account.Name}</apex:outputText>   
                </apex:pageBlockSectionItem>
              <apex:pageBlockSectionItem>
                    <apex:outputLabel>Opportunity</apex:outputLabel>
                    <apex:inputField value="{!account.Opportunity__c}"/>
                </apex:pageBlockSectionItem>                
            </apex:pageBlockSection>
        </apex:pageblock>
    </apex:form>
</apex:page>

Access a account record and try the button to see if it works. That will do the magic. Let me know if you need further assistance and if it's worked.


Regards.

Don't forget to mark your thread as 'SOLVED' with the answer that best helps you.

All Answers

Zuinglio Lopes Ribeiro JúniorZuinglio Lopes Ribeiro Júnior
Hello,

Not sure if I got it right but here's one way to do it:

I based my example on Account object as I don't have your custom object. Replace Account by your custom object.

1-) Create a custom related list button in Opportunity as shown below:

User-added image


2-) Add the url below to your button:

/apex/AssociateOpportunity?id={!Account.Id}

3-) Add the button to the Opportunity's related list in Account's page layout:

User-added image
User-added image


4-) Create a custom lookup field for Opportunity in Account (this is a trick to get the lookup field of Opportunity working in the Visualforce). This button won't be visible and will not be added to any layouts and won't include any related list.

User-added image


5-) Create a controller class (I named it AssociateOpportunityExtController): 
 
public with sharing class AssociateOpportunityExtController {

    public Account account  { get; set; }
    
    public AssociateOpportunityExtController() {
        
        String accountId = ApexPages.currentPage().getParameters().get('id');
        account = [SELECT Id, Name, Opportunity__c FROM Account WHERE Id =: accountId];
        
    }
    
    public PageReference associate () {
        
        Opportunity opp = new Opportunity ( Id = account.Opportunity__c, AccountId = account.Id);
        
        try {
        	Database.update(opp);
        } catch (Exception error) {
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Error while associating.' + error.getMessage()));
        }
        
        PageReference page = new PageReference('/' + account.Id);
        
        return page.setRedirect(true);
    }
    
    public PageReference cancel () {
        PageReference page = new PageReference('/' + account.Id);
        return page.setRedirect(true);        
    }
    
}

6-) Create a Visualforce (I named it AssociateOpportunity):
 
<apex:page controller="AssociateOpportunityExtController">
    <apex:form>
        <apex:pageblock title="Associate Opportunity to Custom Object">
            <apex:pageMessages />
            <apex:pageblockbuttons location="top">
                <apex:commandbutton value="Associate" action="{!associate}" />
                <apex:commandbutton value="Cancel" action="{!cancel}"/>
            </apex:pageblockbuttons>
            <apex:pageBlockSection>
                <apex:pageBlockSectionItem>
                    <apex:outputLabel>Account Name</apex:outputLabel>
                    <apex:outputText>{!account.Name}</apex:outputText>   
                </apex:pageBlockSectionItem>
              <apex:pageBlockSectionItem>
                    <apex:outputLabel>Opportunity</apex:outputLabel>
                    <apex:inputField value="{!account.Opportunity__c}"/>
                </apex:pageBlockSectionItem>                
            </apex:pageBlockSection>
        </apex:pageblock>
    </apex:form>
</apex:page>

Access a account record and try the button to see if it works. That will do the magic. Let me know if you need further assistance and if it's worked.


Regards.

Don't forget to mark your thread as 'SOLVED' with the answer that best helps you.
This was selected as the best answer
Lewis BlauLewis Blau
This works perfectly. Thanks
Sebastian Röder_CognizantSebastian Röder_Cognizant
Hi ,
iam facing a similar issue. I already tried to customize your idea to solve my problems but somehow it is now working. I Hope somebody can help me out:

Iam trying to Add (existing) contacts on my object "Classes" i already have the releated list "CONTACTS" on this object but i cant figure out how to add existing contacts i only can create new contacts from list ...:(

Best regards
Sebastian
Lewis BlauLewis Blau

Sebastian,
Not sure where you are in the process, but if you follow step by step, you will create a page like this one below:
User-added image

The custom list button on the Contact related list on Classes will display this page. The active Class record is defaulted and a lookup to contacts field allows a user to select and then 'Associate'  existing contacts. The downside of the page is you can only associate one record at a time which was fine for my process. You could create a page that allows you to select more than one.

Hope this helps.
Lewis 
Alexander VishtakAlexander Vishtak

Hello, i used the code provided by Zuinglio Lopes Ribeiro Júnior but i have an issue.

When I click on Assosiate button page just reloads without adding a record. I have two objects: ECS__eCommSource_Order__c and Vehicle__c. Can anybody help me?

public with sharing class AssociateVehicleExtController {

    public ECS__eCommSource_Order__c order  { get; set; }
    
    public AssociateVehicleExtController() {
        
        String orderId = ApexPages.currentPage().getParameters().get('id');
        order = [SELECT Id, Name, Vehicle1__c FROM ECS__eCommSource_Order__c WHERE Id =: orderId];
        
    }
    
    public PageReference associate () {
        
        Vehicle__c vec = new Vehicle__c (Id = order.Vehicle1__c, name = order.Id);
        
        try {
        	Database.update(vec);
        } catch (Exception error) {
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Error while associating.' + error.getMessage()));
        }
        
        PageReference page = new PageReference('/' + order.Id);
        
        return page.setRedirect(true);
    }
    
    public PageReference cancel () {
        PageReference page = new PageReference('/' + order.Id);
        return page.setRedirect(true);        
    }
    
}
 
<apex:page controller="AssociateVehicleExtController">
    <apex:form>
        <apex:pageblock title="Associate Vehicle to Custom Object">
            <apex:pageMessages />
            <apex:pageblockbuttons location="top">
                <apex:commandbutton value="Associate" action="{!associate}" />
                <apex:commandbutton value="Cancel" action="{!cancel}"/>
            </apex:pageblockbuttons>
            <apex:pageBlockSection>
                <apex:pageBlockSectionItem>
                    <apex:outputLabel>Order Name</apex:outputLabel>
                    <apex:outputText>{!order.Name}</apex:outputText>   
                </apex:pageBlockSectionItem>
              <apex:pageBlockSectionItem>
                    <apex:outputLabel>Vehicle</apex:outputLabel>
                    <apex:inputField value="{!order.Vehicle1__c}"/>
                </apex:pageBlockSectionItem>                
            </apex:pageBlockSection>
        </apex:pageblock>
    </apex:form>
</apex:page>

User-added image
Dave DaulDave Daul
I like this list with the search capability but can you provide and example of how the Multiselect could work on this.  In other words, if I want to search for 20 Opportunities to Associate I'd like to select from the lookup list and then associate all records I select there.
Kayla N PattenKayla N Patten
Is there a way to get this result through a flow? I have the same problem and want to have a button on a custom object's related list to select existing records but am wanting to use a flow instead of any code. Is this possible?
Dinesh RajendranDinesh Rajendran
Hello Everyone, 

Is there any way to use Lightning Aura pages instead of VF page in the above scenario. Please confirm.

Thanks