Wednesday 12 October 2016

How to check field permission(FLS) based on profile via Apex or SOQL in Salesforce

Let's take an example, you are developing a visualforce page with custom controller, And you have to display the field as either input or output mode based on the FLS permission for the specific field at the profile level who is running the page.


  1. Boolean hasEditInvoiceField = false;

  2. List<FieldPermissions> invoiceOrderNumberFLS = [SELECT SobjectType, Field, PermissionsRead, PermissionsEdit, Parent.ProfileId FROM FieldPermissions where SobjectType = 'Opportunity' and Field='Opportunity.Invoice_OrderNumber__c' AND Parent.ProfileId=:Userinfo.getProfileId()];

  3. if(!invoiceOrderNumberFLS.isEmpty()){
  4.     hasEditInvoiceField = invoiceOrderNumberFLS[0].PermissionsEdit;
  5.     System.debug('####'+hasEditInvoiceField);
  6. }


Note: 
1. Invoice_OrderNumber__c is the custom field on Opportunity Object. 
2. If the profile does not have permission(Visible, ReadOnly), then query will return zero results.
3. PermissionsEdit field on FieldPermission object will return the Boolean value as below,
  • If field have Visible access alone for the specified field then it return TRUE.
  • If field have Visible and Read only access for the specified field then it return FALSE.

Reference:

Tuesday 11 October 2016

How to convert List to Map in Salesforce

Here is the simple way to convert list of sobject records to map.

Assigning query result to List:

  1. //Assigning return query result to the list.
  2. List<Lead> leadList = [SELECT Id, Name FROM Lead];

Assigning query result to Map:

  1. //Directly assigning return query result to the map.
  2. Map<Id, Lead> leadMap = new Map<Id, Lead>([SELECT Id, Name FROM Lead]);

Converting List to Map:

  1. //Converting list to map
  2. Map<Id, Lead> mapFromList = new Map<Id, Lead>(leadList);

How to create or generate a csv file in apex code Salesforce (Generate Setup Audit Trail records as CSV file)

Here is the sample code to create or generate a CSV file using apex code. The below code will query all SetupAuditTrail object records and stored the generated CSV file in document object folder. 

Usually Setup Audit Log in salesforce will provide only last six month of data. But when we need a specific range of logs, then we have to go for a custom logic. 

The below query will provide specific date range of Audit logs,

  1. SELECT CreatedDate, CreatedBy.Username, Display, Section, Action, DelegateUser FROM SetupAuditTrail WHERE CreatedDate >= 2016-09-10T00:00:00Z AND CreatedDate <= 2016-10-01T00:00:00Z ORDER BY CreatedDate DESC

Sample Batch Code

  1. global class SetupAuditTrailBatch implements Database.Batchable<sObject>, Database.Stateful {
  2.    
  3.     global String csvColumnHeader;
  4.     global List<String> csvRowValues = new List<String>();
  5.    
  6.     global Database.QueryLocator start(Database.BatchableContext BC){
  7.         //Query all SetupAuditTrail records.
  8.         String query = 'SELECT CreatedDate, CreatedBy.Username, Display, Section, Action, DelegateUser, CreatedById, CreatedBy.Name FROM SetupAuditTrail ORDER BY CreatedDate DESC';
  9.         return Database.getQueryLocator(query);
  10.     }
  11.    
  12.     global void execute(Database.BatchableContext BC, List<sObject> scope){
  13.         //Process retrieved SetupAuditTrail records and format field values.
  14.         for(SetupAuditTrail currSetupAudit : (List<SetupAuditTrail>) scope){
  15.             String formattedDate = currSetupAudit.CreatedDate.format('M/d/yyyy h:mm:ss a z');
  16.             String userName = currSetupAudit.CreatedBy.Username != null ? currSetupAudit.CreatedBy.Username : '';
  17.             String displayVal = currSetupAudit.Display != null ? String.valueOf(currSetupAudit.Display).escapeCsv() : '';
  18.             String sectionVal = currSetupAudit.Section != null ? currSetupAudit.Section : '';
  19.             String delegateUser = currSetupAudit.DelegateUser != null ? currSetupAudit.DelegateUser : '';
  20.            
  21.             String rowStr = formattedDate + ',' + userName + ',' + displayVal + ',' + sectionVal + ','+ delegateUser;
  22.             csvRowValues.add(rowStr);
  23.         }
  24.     }
  25.    
  26.     global void finish(Database.BatchableContext BC){
  27.         List<Folder> folders = [SELECT Id, Name FROM Folder WHERE Name = 'Setup Audit Trail Logs'];
  28.        
  29.         if(!folders.isEmpty()){
  30.             String documentName = 'SetupAuditTrailLog-'+ Datetime.now().format('MMM') + Datetime.now().year();
  31.             csvColumnHeader = 'Date, User, Action, Section, Delegate User\n';
  32.             String csvFile = csvColumnHeader + String.join(csvRowValues,'\n');
  33.            
  34.             // Insert the generated CSV file in Document object under "Setup Audit Trail Logs".
  35.             Document doc = new Document(Name = documentName, Body = Blob.valueOf(csvFile), FolderId = folders[0].Id, Type = 'csv', ContentType='application/vnd.ms-excel');
  36.             insert doc;
  37.         }
  38.     }
  39. }


References:


Supported calls:
query(), retrieve()

Note:
Aggregate queries aren’t supported on this object. For example, SELECT count() FROM SetupAuditTrail works but SELECT count(Id) FROM SetupAuditTrail fails.

Activities: Assign Tasks to a Queue Salesforce Lightning

Salesforce announced to assign Tasks to a Queue beginning from Spring'20 release. How does it work? In Setup, enter Queues in th...