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
Alexander VishtakAlexander Vishtak 

Associate a record from 1 custom object in the related list of 2 custom object

I have two custom objects: x__c and y__c.  i have multiple records in y__c object. This object is displaying as a related list on x__c object.

I want to create a button which will take records from y__c object and SHOW them on x__c object related list. This button should not create any records. Just showing already existing information. Any help will be appreaciated.
The code below: the button opens a lookup search but after i pick a record it just refreshes the page, not adding any recotrds into related list.

Thank You

Alex

 

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>