Salesforce 开发者笔记

Salesforce Study Notes & Apex tips

修改User Profile 和License

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
String userId = '0051i000001L23u';

String NewProfileId = '00eD0000001AseK';

user u =[select id,ProfileId,UserPermissionsMarketingUser from user where id= : userId];

List<permissionsetassignment> PSAList = [select AssigneeId ,PermissionSetId from permissionsetassignment where AssigneeId =:userId and PermissionSet.License.Name !='Salesforce' ];
List<permissionsetassignment> NewPSAList = new List<permissionsetassignment> ();

for(permissionsetassignment psa : PSAList){
NewPSAList.add(new permissionsetassignment(AssigneeId = userId, PermissionSetId = psa.PermissionSetId ) );
}

system.debug('user ');
system.debug(u);

u.ProfileId =NewProfileId;
u.UserPermissionsMarketingUser = false;

update u;

insert NewPSAList;

SQL: select AssigneeId ,PermissionSetId from permissionsetassignment where AssigneeId = ‘0051i000001L23u’

Apex如何remove 乱七八糟符号

1
2
3
String strText = 'Welcome - to! % $sale&sforce \\ /code # crack %';
strText = strText.replaceAll('[^a-zA-Z0-9\\s+]', '');
System.debug('strText ======> '+strText);

Check if user is Frozen

Please find below SQL, so that you can query related user if needed

1
SELECT  UserId,IsFrozen ,IsPasswordLocked  FROM UserLogin WHERE   UserId ='XXXXXXXX'

复制A user permission 到 B User

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45


String OldUserId = '005D00000023koO';
String NewUserId = '0051i000001KHkT';

//****************Copy Permission Set Assignment*******************

List <PermissionSetAssignment> PSAList=[select id,AssigneeId,PermissionSetId,PermissionSet.Name from PermissionSetAssignment where AssigneeId=: OldUserId and PermissionSet.Name like 'XXX%'];

List <PermissionSetAssignment> NewPSAList = new List <PermissionSetAssignment>();
set<String> NewPermissionSetId = new set<String> ();

List <PermissionSetAssignment> NewPermissionList=[select id,AssigneeId,PermissionSetId,PermissionSet.Name from PermissionSetAssignment where AssigneeId=: NewUserId and PermissionSet.Name like 'XXX%'];
for (PermissionSetAssignment PSA :NewPermissionList){
NewPermissionSetId.add(PSA.PermissionSetId);
}

for (PermissionSetAssignment PSA :PSAList){
if(!NewPermissionSetId.contains(PSA.PermissionSetId )){
PermissionSetAssignment temp = new PermissionSetAssignment(AssigneeId = NewUserId,PermissionSetId = PSA.PermissionSetId );
NewPSAList.add(temp);
}
}
system.debug(NewPSAList);
if(NewPSAList.size()>0){
insert NewPSAList;
}

//***************Public Group*******************

List <GroupMember> NewGMList = new List <GroupMember>();
set<String> NewGroupSetId = new set<String> ();
List <GroupMember> OldGroupMemberList = [select GroupId,Group.Name,UserOrGroupId from GroupMember where UserOrGroupId =: OldUserId and Group.Name like 'XXX%'];

List <GroupMember> NewGroupMemberList = [select GroupId,Group.Name,UserOrGroupId from GroupMember where UserOrGroupId =: NewUserId and Group.Name like 'XXX%'];
for(GroupMember gm :NewGroupMemberList ){
NewGroupSetId.add(gm.GroupId );
}
for(GroupMember gm :OldGroupMemberList ){
if(!NewGroupSetId.contains(gm.GroupId)){
GroupMember temp = new GroupMember(GroupId = gm.GroupId ,UserOrGroupId = NewUserId );
NewGMList.add(temp);
}
}
insert NewGMList;

如何得到月尾的最后一天?

1
2
3
Date selectedDate = Date.today().addDays(4);
Date firstDate = selectedDate.toStartOfMonth();
p.Date__c =firstDate.addDays(date.daysInMonth(selectedDate.year() , selectedDate.month()) - 1);

把string 改为 date

1
2
Date x = Date.valueOf('2015-8-11'); 
system.debug('Now '+ x );

Scheduled Job每15分钟跑一次

1
2
3
4
  System.schedule('Scheduled Job 1', '0 0 * * * ?', new ScheduledClass());
System.schedule('Scheduled Job 2', '0 15 * * * ?', new ScheduledClass());
System.schedule('Scheduled Job 3', '0 30 * * * ?', new ScheduledClass());
System.schedule('Scheduled Job 4', '0 45 * * * ?', new ScheduledClass());

可编辑字段(一)

如何获得对象中的可编辑字段

1
2
3
4
5
6
Map<String, Schema.SObjectField> map = Schema.SObjectType.Custom1__c.fields.getMap();
for(String fieldName : map.keySet()) {
if(map.get(fieldName).getDescribe().isUpdateable()) {
custom1.put(fieldName , 'some value');
}
}

可编辑字段(二)

下面function获得对象中的所有可编辑字段

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public static String GetUpdateableField(String ObjectName){
String QueryStr= 'select ';
String[] types = New List<String>();
types.add(ObjectName);
Schema.DescribeSobjectResult[] results = Schema.describeSObjects(types);
for(string apiName : results[0].fields.getMap().keySet()){
Schema.SObjectField field = results[0].fields.getMap().get(apiName);
Schema.DisplayType FldType = field.getDescribe().getType();
//system.debug('apiName : '+ apiName + ' || FldType:'+FldType + '|| is editable : '+field.getDescribe().isUpdateable() );
if(field.getDescribe().isUpdateable()){
QueryStr += apiName + ',';
}
}
QueryStr = QueryStr.subString(0, QueryStr.length() - 1) + ' from '+ObjectName;
return QueryStr;
}

常用代码注释模板

如下提供几个模板仅供参考:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/*
+-----------------------+------------------------------------------------------------------------------------+
| Author | Your name
+-----------------------+------------------------------------------------------------------------------------+
| Description | For what?
| |
| - Object(s) | table name
| - Description | what you are doing here?
+-----------------------+------------------------------------------------------------------------------------+
| Creation Date | 23/12/2016
+-----------------------+------------------------------------------------------------------------------------+
| Modifications | 2/2/2017 who - doing what?
+-----------------------+------------------------------------------------------------------------------------+
| Governor informations |
+-----------------------+------------------------------------------------------------------------------------+
*/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
* @name 名字
* @abstract 申明变量/类/方法
* @access 指明这个变量、类、函数/方法的存取权限
* @author 函数作者的名字和邮箱地址
* @category 组织packages
* @copyright 指明版权信息
* @const 指明常量
* @deprecate 指明不推荐或者是废弃的信息MyEclipse编码设置
* @example 示例
* @exclude 指明当前的注释将不进行分析,不出现在文挡中
* @final 指明这是一个最终的类、方法、属性,禁止派生、修改。
* @global 指明在此函数中引用的全局变量
* @include 指明包含的文件的信息
* @link 定义在线连接
* @module 定义归属的模块信息
* @modulegroup 定义归属的模块组
* @package 定义归属的包的信息
* @param 定义函数或者方法的参数信息
* @return 定义函数或者方法的返回信息
* @see 定义需要参考的函数、变量,并加入相应的超级连接。
* @since 指明该api函数或者方法是从哪个版本开始引入的
* @static 指明变量、类、函数是静态的。
* @throws 指明此函数可能抛出的错误异常,极其发生的情况
* @var 定义说明变量/属性。
* @version 定义版本信息
*/
1
2
3
4
5
6
7
8
 / *
* 文件名:[文件名]
* 作者:〈版权〉
* 描述:〈描述〉
* 修改人:〈修改人〉
* 修改时间:YYYY-MM-DD
* 修改内容:〈修改内容〉
*/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
 / *
* 文件名:LogManager.java
* 版权:Copyright 2000-2001 Huawei Tech. Co. Ltd.  All Rights Reserved.
* 描述: WIN V200R002 WEBSMAP 通用日志系统
* 修改人:张三
* 修改时间:2001-02-16
* 修改内容:新增
* 修改人:李四
* 修改时间:2001-02-26
* 修改内容:。。。。。。
* 修改人:王五
* 修改时间:2001-03-25
* 修改内容:。。。。。。
 */

获得字段信息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
Map < String, Schema.SObjectType > schemaMap = Schema.getGlobalDescribe();

Schema.SObjectType ObjectSchema = schemaMap.get('Account_Interface__c');

Map < String, Schema.SObjectField > fieldMap = ObjectSchema.getDescribe().fields.getMap();
for (String fieldName: fieldMap.keySet()) {
String fName = fieldMap.get(fieldName).getDescribe().getLabel();
system.debug('|| fName:'+fName);
}
```








## 获得字段类型


```Java
Map < String, Schema.SObjectType > schemaMap = Schema.getGlobalDescribe();
Schema.SObjectType ObjectSchema = schemaMap.get('Account_Interface__c');

Map < String, Schema.SObjectField > fieldMap = ObjectSchema.getDescribe().fields.getMap();
for (String apiName: fieldMap.keySet()) {
Schema.SObjectField field = fieldMap.get(apiName);
Schema.DisplayType FldType = field.getDescribe().getType();
system.debug(FldType);
}

获得某一个对象的字段类型

1
2
3
4
5
6
7
public static String GetFieldType(Schema.SObjectType ObjectSchema , String FieldAPIName){
Map < String, Schema.SObjectField > fieldMap = ObjectSchema.getDescribe().fields.getMap();
system.debug('FieldAPIName : '+FieldAPIName);
Schema.SObjectField field = fieldMap.get(FieldAPIName.toLowercase());
Schema.DisplayType fName = field.getDescribe().getType();
return String.valueOf(fName);
}

动态更新Sobject

1
2
3
4
5
6
7
8
9
10
public static void dynamicUpsert(List<SObject> records, SObjectType sObjectType)
{
if (sObjectType != null)
{
String listType = 'List<' + sObjectType + '>';
List<SObject> castRecords = (List<SObject>)Type.forName(listType).newInstance();
castRecords.addAll(records);
upsert castRecords;
}
}

This also works with Database.upsert for the following signatures:
Database.upsert(List records)
Database.upsert(List records, SObjectField externalIdField)
Database.upsert(List records, Boolean allOrNone)
It does not work for the following signature because it causes a compile fail:
Database.upsert(List records, SObjectField externalIdField, Boolean allOrNone)

新建File

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public static void UploadIntoFile(Blob requestBody,String FileName){ 
try{ // select id,Title from ContentDocument
//String yourFiles = FileBody;//Lets assume this is your binary string of the files';
datetime myDateTime = datetime.now();
ContentVersion conVer = new ContentVersion();
conVer.ContentLocation = 'S'; // S specify this document is in SF, use E for external files
conVer.PathOnClient = 'File.txt'; // The files name, extension is very important here which will help the file in preview.
conVer.Title = FileName + String.valueOf(myDateTime) ; // Display name of the files
conVer.VersionData = requestBody;//EncodingUtil.base64Decode(yourFiles); // converting your binary string to Blog
insert conVer;
}catch(dmlException e){
system.debug(e.getMessage());
}

}

Reference : https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_objects_contentdocument.htm

1
2
3
4
5
6
7
8
ContentVersion cont = new ContentVersion();

cont.Title = 'Title for this contentVersion';
cont.PathOnClient = 'file_' + Datetime.now().getTime() + '.txt';
cont.VersionData = Blob.valueOf('My Content in file_' + Datetime.now().getTime() + '.txt');
cont.Origin = 'H';

insert cont;

SQL –>List–> Map

1
map<id, User> userMap = new map<id, User>([select ID,ManagerId,Manager.Email from User where id in : OwnerIdSet]);

Tell the Day of the Week of a Date

1
2
3
4
5
Date d = System.today();
Datetime dt = (DateTime)d;
String dayOfWeek = dt.format('EEEE');

system.debug('dayOfWeek : '+dayOfWeek);
1
2
3
4
5
Date d = System.today();
Datetime dt = (DateTime)d;
String dayOfWeek = dt.format('u');

System.debug('~~~~~~~~~ ::'+dayOfWeek);