我很难理解在我的变量和方法中使用 public、static 和 global 关键字。
下面是我的代码片段。我想做的是在页面加载时,在我的构造函数中创建用户有权访问的一组 accountID(8-33 这是有效的)。该集合将用于过滤后面方法中使用的查询。
我发现公共(public) pageReference runSearch() 可以访问“terrAccSet”,但公共(public)静态列表 getsearchAccounts 无权访问它。
如果我将其更改为 public static Set terrAccSet,我在任何一个 system.debugs 中都无法获取数据 - 我该怎么办?
global with sharing class MyClass {
public static List<FRM_Metrics_gne__c> accountSearchGmap {get; set;}
public Set<Id> terrAccSet;
public List<String> terrIdList;
//Constructor
public MyClass() {
terrAccSet = new Set<Id>();
terrIdList = new List<String>();
Set<Id> grpIdSet = new Set<Id>();
Id uid = '00570000001R95e'; //member of TWO territories
//UserTerritory Utid = [SELECT TerritoryId FROM UserTerritory where UserId = :userInfo.getUserId()];
List<UserTerritory> Utid = [SELECT TerritoryId FROM UserTerritory where UserId =: uid ];
for(UserTerritory usrTerr: Utid){
terrIdList.add(usrTerr.TerritoryId);
}
List<Group> grp = [Select Id from Group where RelatedID IN :terrIdList];
for (Group eachgroupd : grp ){
grpIdset.add(eachgroupd.Id);
}
List<AccountShare> accountidList = [SELECT AccountId,UserOrGroupId FROM AccountShare where UserOrGroupId in :grpIdset];
//all accounst that the user has access according to territory hiearchy
for(AccountShare eachas:accountidList ){
terrAccSet.add(eachas.AccountId);
}
}
public PageReference runSearch() {
//Has Data
system.debug('**terrAccSet runSearch** '+terrAccSet);
}
public static List<Custom_Object__c> getsearchAccounts(String multiSearchString) {
//terrAccSet variable is missing
system.debug('**terrAccSet getSearchAccounts** '+terrAccSet);
//logic
return accountSearchGmap;
}
}
最佳答案
Below is a snippet of my code. What I'm trying to do is upon page load, in my constructor create a Set of accountIDs that the user has access to (8-33 this is working). This set will be used to filter queries used in later methods.
这个集合应该是一个实例属性,而不是静态的。 当您想要创建一个不影响 Controller 或类的状态的方法时,请使用 static,例如。文本解析器-文本输入文本输出。
如果您想要创建包并使您的类在包外部可用,以便其他 Apex 代码可以调用它,或者如果您的类将创建要公开的 webService 或 REST 方法,则应该将该类设置为全局。
应使用 Public 将属性公开给将使用这些属性的 VisualForce 页面。否则,仅使用私有(private)方法和属性进行 Controller 端处理。
public static List getsearchAccounts(String multiSearchString) { //terrAccSet variable is missing system.debug('terrAccSet getSearchAccounts '+terrAccSet); //logic return accountSearchGmap; }
此方法不应该是静态的,因为它访问实例属性(它读取状态)。
简单的经验法则,如果它是 Visualforce 页面 + Controller ,则不需要任何静态内容来完成查询数据库并将数据返回到页面的正常工作。
关于Salesforce (SFDC) - 公共(public)、静态、全局关键字 - 为整个类(class)使用一个列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13021208/