FLS 为 Salesforce 对象创建

FLS Create for Saleforce Object

有没有办法将 FLS 创建检查 - Schema.sObjectType.Account.fields.Name.isCreateable() 应用于以下内容?

public static Account createAccount() {
    return new Account(
        Name = 'Test',
        OwnerId = UserInfo.getUserId()
    );
}

想知道有没有不用重写就可以申请的方法:

public static Account createAccount() {
    Account a = new Account();
    if (Schema.sObjectType.Account.fields.Name.isCreateable()) {
        a.Name = 'Test';
    }
    if (Schema.sObjectType.Account.fields.OwnerId.isCreateable()) {
        a.OwnerId = UserInfo.getUserId();
    }
    insert a;
}

您可以创建一个通用方法来迭代每个字段以检查 FLS。

  • 如果可以访问则保留
  • 如果访问不可用,则从对象实例中删除特定字段。

我创建了一个通用方法来截断不可写的字段,如下所示:

    public static List<SObject> truncateNotWriteableFields(List<SObject> listSObject){

    Set<String> readOnlyFields = new Set<String>();
    List<SObject> listSObjectNew = new List<SObject>();
    if(listSObject.size() < 1){
        return listSObjectNew;
    }
    Schema.SObjectType sObjType = listSObject.getSObjectType();

    for(SObjectField field : sObjType.getDescribe().fields.getMap().values()){
        if(field.getDescribe().isAccessible() && !field.getDescribe().isUpdateable() && !field.getDescribe().isCreateable()){
            readOnlyFields.add(String.valueOf(field));
        }
    }
    readOnlyFields.remove('Id'); // avoid removal in update
    for(SObject obj : listSObject){
        Map<String, Object> objMap = (Map<String, Object>) JSON.deserializeUntyped( JSON.serialize( obj ) );
        objMap.keySet().removeAll(readOnlyFields);
        SObject objWithoutNotWritableFields = (SObject) JSON.deserialize( JSON.serialize( objMap ), SObject.class );
        system.debug('objWithoutNotWritableFields=>'+objWithoutNotWritableFields);
        listSObjectNew.add(objWithoutNotWritableFields);
    }
    
    return listSObjectNew;
}