如何在Visualforce的apex:commandButton中调用带参数的Apex控制器方法
解决方案
首先明确:Visualforce的action属性绑定的Apex后端方法,不支持直接传递自定义入参,你当前定义的带List<Account>参数的save方法无法被VF按钮直接调用,可通过以下两种方式实现需求:
方案1:利用控制器类属性获取选中值(最推荐,适配StandardSetController场景)
你已经在使用ApexPages.StandardSetController,直接将其定义为控制器的类成员属性,即可在save方法中直接调用内置的getSelected()方法获取选中的记录,不需要从页面传参。
修改后的Apex代码:
public class 你的控制器类名 { // 将StandardSetController定义为带get/set的类成员属性 public ApexPages.StandardSetController ssc {get; set;} public 你的控制器类名(){ List<Account> accountList = [SELECT Name FROM Account LIMIT 20]; ssc = new ApexPages.StandardSetController(accountList); } // 移除save方法的入参,直接从类属性获取选中记录 public PageReference save(){ List<Account> selected = ssc.getSelected(); // 你的业务逻辑代码 if(/* 你的逻辑判断条件 */){ // 执行对应操作 } return null; // 按需替换为跳转的PageReference } }
VF页面无需修改,原按钮代码即可正常生效:
<apex:commandButton action="{!save}" value="Save" id="theButton"/>
方案2:通过参数序列化传递(仅特殊场景使用)
如果确实需要从页面主动传递列表参数,可以将列表序列化为JSON字符串通过apex:param传递,后端再反序列化得到列表:
调整后的Apex代码:
public class 你的控制器类名 { public ApexPages.StandardSetController ssc {get; set;} // 用于接收页面传递的JSON参数 public String selectedAccountsJson {get; set;} public 你的控制器类名(){ List<Account> accountList = [SELECT Name FROM Account LIMIT 20]; ssc = new ApexPages.StandardSetController(accountList); } public PageReference save(){ List<Account> selected = (List<Account>)JSON.deserialize(selectedAccountsJson, List<Account>.class); // 你的业务逻辑代码 return null; } }
调整后的VF按钮代码:
<apex:commandButton action="{!save}" value="Save" id="theButton" reRender="none"> <apex:param name="selectedAccounts" value="{!JSON.serialize(ssc.selected)}" assignTo="{!selectedAccountsJson}"/> </apex:commandButton>
注意:该方案存在JSON序列化长度限制,性能也弱于方案1,非特殊情况不推荐使用。
内容的提问来源于stack exchange,提问作者Ragu C
相关产品推荐
相关产品推荐

