salesforceapexvisualforce

How to Pass Selected Record IDs from a Custom Object List View to an Apex Controller?


I am a developer who is relatively new to Salesforce. In my current project, I need to pass the selected record IDs from the list view of a custom object called MyClass__c as parameters to an Apex controller, but I’m not sure how to do this.

From my research, it seems I need to use an Apex controller and Visualforce, but I don’t know how to implement this. Could someone help me with the code for this?

**Create APEXContorller **

public class AccountController {
    public List<String> accountIds { get; set; }
    public AccountController() {
        accountIds = ApexPages.currentPage().getParameters().get('ids') != null
                     ? ApexPages.currentPage().getParameters().get('ids').split(',')
                     : new List<String>();
        System.debug('Account IDs: ' + accountIds);
    }

    public void processAccounts() {
        System.debug('Processing Accounts with IDs: ' + accountIds);
        List<Account> selectedAccounts = [SELECT Id, Name FROM Account WHERE Id IN :accountIds];
    }
}

**Create VisualForce **

<apex:page controller="AccountController">
    <apex:form>
        <apex:pageMessages />
        <apex:commandButton value="Process Selected Accounts" action="{!processAccounts}" rerender="resultPanel"/>
        
        <apex:outputPanel id="resultPanel">
            <apex:repeat value="{!accountIds}" var="accId">
                <p>Selected Account ID: {!accId}</p>
            </apex:repeat>
        </apex:outputPanel>
    </apex:form>
</apex:page>

Add Link to ListView Custom Button /apex/AccountControllerPage?ids={!GETRECORDIDS($ObjectType.Account)}


Solution

  • You have a listview button, you hope to tick-tick-tick some checkboxes, click the button and have the VF do something with selected records?

    Ditch the GETRECORDIDS, we won't be needing it.

    Read up about "Standard Set Controller".

    If you modify your class to accept a public AccountController(ApexPages.StandardSetController ssc){... object (your current constructor doesn't accept any parameters) and instruct the VF to use this variant (<apex:page standardController="Account" recordSetVar="accounts" extensions="AccountController") then ssc.getSelected() will contain the IDs user ticked.

    Here's a full working example: https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_quick_start_massupdate.htm