Monday, February 4, 2019

How to convert my existing source code retrieve by Ant migration tool to SFDX supported metadata.

1. First crate a sfdx project/workspace from CLI (Check http://sfdccodepractices.blogspot.com/2019/01/sfdx-setup-guide.html for command help. Say folder name is “SFDX_Supported_Metadata” under "D" drive. Hence project path is "D:\SFDX_Supported_Metadata".

2. After project creation system will automatically create SFDX folder and file structure. Say our project is created under "D:\SFDX_Supported_Metadata\SfdxDemo".

3. Change directory to that folder (D:\SFDX_Supported_Metadata\SfdxDemo) in CLI.

4. Now retrieve the source code using ANT migration tool. Say source code is retrieve under "D:\ANT_Supported_Metadata" folder.

5. Now run the below sfdx command for conversion (From Ant supported meta data to SFDX supported meta data).

sfdx force:mdapi:convert -r D:\ANT_Supported_Metadata

6. Once the above command will run successfully, it will put all meta-data under project root directory with suitable sfdx structure. Root directory is “D:\SFDX_Supported_Metadata\SfdxDemo\force-app\main\default”.

7. So, our structure is finally ready for SFDX use.

Thursday, January 31, 2019

How to ignore any source components to be pulled or push from or to Scratch Org?



If you check your local SFDX Project Directory, then you can see that there is a file named as ".forceignore". This file is basically used for ignore source component(s) tracking.

  • IGNORE SOURCE COMPONENT(S) FOR PULL OPERATION.
  1. If you want to ignore any file(s) to be pull from Scratch Org to your local project, then just copy paste your file name (with extension) in your ".forceignore" file. For example say you have create a class "TestIgnoreClass.cls" in your Org for any R&D purpose and you don't want to pull it in your local project, so just write the name "TestIgnoreClass.cls" under your ".forceignore" file.

  • IGNORE SOURCE COMPONENT(S) FOR PUSH OPERATION.
  1. If you want to ignore any file(s) to push from local project to Scratch Org, then you have to give absolute path of that file/folder [Path will be started from your root directory]. For example say you have a class "TestIgnoreClass.cls" in your local project and you don't want to push it to your scratch Org, then just write the path of that class "force-app\main\default\classes\TestIgnoreClass.cls" under your ".forceignore" file.

Note: If you have multiple classes to be ignore then just write down the file names (pull operation) / file or folder path (push operation) with extension and separate the file/folder by placing them in new line.

Tuesday, January 29, 2019

SFDX Setup Guide.

Goal of this post is to setup your SFDX environment and perform below activities,
  • DevHub setup,
  • Local workspace/project creation,
  • Scratch Org creation,
  • Pereform PUSH/PULL operation (deploy/retrieve) etc.

Step by step perform the below action items.


1. First you have to install sfdxcli. Download it from https://developer.salesforce.com/tools/sfdxcli (I have download here). Then install it in your machine and set your environment variable for your install sfdxcli.

2. Now open command prompt and run below command to check is it working properly.

sfdx -v

3. Now create a folder where you want to setup your local repository for sfdx operation. For my case say it under"D:\Assignments\Salesforce DX".

4. Now open CLI and change the directory location to above location using below command,

cd D:\Assignments\Salesforce DX

5. Now setup your DevHub org from where you want to create scratch Orgs. To setup an Org as DevHub run the below command in your CLI.

sfdx force:auth:web:login --setdefaultdevhubusername --setalias my-devhub-org

6. It takes few seconds and browser window will open. Put your user name and password and after successful login in browser it will show below successful message in CLI.




7. If you already login in your DevHub org, then go to setup and search for "Dev Hub" and then       enabled Dev Hub. Otherwise you will get error while try to create scratch org (explain below).



8. Now your dev hub is ready and you are ready to create your scratch org. But before create a    scratch org first create local workspace/project. And it is the location where you push or pull            your source code to your scratch org or from your scratch org respectively.
Now run the below command to create a wrokspace/project in your local directory,

sfdx force:project:create --projectname MyFirstSFDXProject


     So, a new project will be create named as "MyFirstSFDXProject" under "D:\Assignments\Salesforce DX" directory.


9. Now open the folder "D:\Assignments\Salesforce DX\MyFirstSFDXProject\config” there is a file named as "project-scratch-def.json". This json file contains scratch org information. So, you can edit this file to setup your scratch org name, edition etc.

{

    "orgName": "ArunSFDX Demo",

    "edition": "Developer",

    "orgPreferences" : {

        "enabled": ["S1DesktopEnabled"]

    }

}

10. Run the command in CLI to change the directory to your project directory which is created in point 8.

cd MyFirstSFDXProject


11. Now check your Dev Hub connection and list of scratch orgs related to this dev hub. Currently we don't have any scratch org. Run the below command for checking,
sfdx force:org:list



12. Create Scratch Org (Use the above JSON as mention in point 9) and run the below command. Here I have given my scratch org alias name as "MyScratchOrg1".
sfdx force:org:create --setdefaultusername -f config/project-scratch-def.json --setalias MyScratchOrg1

Note: If you miss to enable Dev Hub as mentioned in point 7, then you will get the below error.  So, enable your dev hub as mentioned point 7 and run the command again.




13. If the above command run successfully then CLI will show your scratch org name.


Response message:
Successfully created scratch org: 00DN0000000REujMAG, username: test-f2bwflahpmax@example.com

14. Now like point 11, you can check the dev hub connection and it's scratch org list. Currently we have one scratch org. Run the same command as mentioned in point 11.
sfdx force:org:list



15. Open your scratch org by below command (No password is here).
sfdx force:org:open
or
sfdx force:org:open -u org_alias

 (for my case it is sfdx force:org:open -u ArunSFDX Demo)



System will automatically open the scratch Org in your default browser or you can open the ORG by copy paste the displaying URL in CLI.


16. You can generate password for your scratch org.
sfdx force:user:password:generate




17. You can see the password / org details again by running below command.
sfdx force:user:display -u scratch_org_user_name
For me it like,

sfdx force:user:display -u test-f2bwflahpmax@example.com



18. Check Company Information and it is same as you mentioned in your JSON


19. As this scratch org is developer org so the storage limit is low and you can check it from “System Overview”.


20. Now try to deploy some source code in the scratch org.
  • Open your project folder (D:\Assignments\Salesforce DX\MyFirstSFDXProject) and here you get a json file named as “sfdx-project.json”.
  • Open the json file and there you get the source directory folder path, where you put your source code to deploy.

{
  "packageDirectories": [

    {

      "path": "force-app",

      "default": true

    }

  ],

   "namespace": "",

"sfdcLoginUrl": "https://login.salesforce.com",

  "sourceApiVersion": "44.0"

}
  • Suppose I want to deploy some class. So create “Classes” folder and here put your classes and their metadata. Folder and file structure is same as used on the time of ant deployment and only difference is here being no package.xml is required.
  • For our case say, I want to deploy “ToolBean.cls”.


  • Currently there is no class under scratch Org.

  • Now use below push command for deployment.
sfdx force:source:push


  • Check Org for this deployment,


  • Now suppose I have created another class (ArunSFDXDemoClass.cls) and a lightning component (ArunSFDXDemoComponent.cmp) and also modify existing class (ToolBean.cls) in scratch org and finally I want to pull it from scratch Org.



  • Now run the below command to pull the above new and modified source code.
  • sfdx force:source:pull
  • Before pull

  • After pull

  • Under classes folder


  • Under aura folder



21. Once you complete your work then logout from org. Below are the logout command,

sfdx force:auth:logout -u test-f2bwflahpmax@example.com

Sunday, November 25, 2018

Custom Permissions

In Salesforce, many features require access checks that specify which users can access certain functions. Permission set and profiles settings include built-in access settings for many entities, like objects, fields, tabs, and Visualforce pages. However, permission sets and profiles don’t include access for some custom processes and apps.

Challenge 1 :
Suppose We have an object “Product Complaint” and it has filed like below,
1.      Status [Open/ Closed/ Other] è Pick list filed.
2.      Reason For Other è Text
Now create a validation rule so that if Status is selected as “Other” and if user was not entered any value for “Reason For Other” field, then an warning/error/validation message will be thrown as “Please enter reason to select other”.




Now our aim is that this validation rule will be fire for every users except the user belongs to System Admin profile. That mean user with system admin profile will able to save any PC record with status value as “Other” and no value in “Reason For Other” filed.


Solution:
1. Create a custom permission.
















2. Assign it to System Admin Profile.



3. Update the validation rule.



Now user with System Admin profile can create PC record with “Other” status – without entering “Reason For Other” value. But other profile user will get the validation message.

Challenge 2 :
Now if we want this validation in user level i.e. some System Admin user will face this validation rule and some not.

Solution:
1. Remove “Custom Permission” form System Admin Profile.
2. Create a permission set (Named it same as custom permission).



3. Click on “Manage Assignments” button to assign the user who can use this permission set.
4. Now click on the “Custom Permissions” link to assign custom permission to “Permission Set”.



5. Now try to test the validation rule for 2 System Admin Users, one who is assigned in Permission Set and one who is not assigned.

Note: We can also use custom permission in VISUALFORCE page. Like some render condition.
Syntax  is look like below,
(Not($Permission. Can_Set_PC_Status_to_Other))

Permission Sets Concept.

1. Why Permission Set is used in Salesforce?
 
     In Salesforce each user should has one and only one profile. But there could be multiple users for a single profile. Now taking the above consideration check the below scenario :

     Suppose we have a Profile named as "My Custom Profile" and suppose this profile has only read permission on Account Object. Now there are 3 users (U1, U2, U3) have assigned to this profile.
So, as per above scenario all 3 users (U1, U2, U3) should have only read permission as their assigned profile has read permission on Account object.

Now, suppose there is a requirement that U2 can also perform create and edit operation on Account irrespective of it's profile permission (i.e. only read permission). So this the place where we can use Permission Set.



2. How to create and configure Permission Set for the above scenario?


  • Search "permission sets" under "Quick Find" box and click on "Permission Sets" link and it will open "Permission Sets" detail page.Now click on "New" button to create a new permission set. For example our permission set name is "My Custom Permission" and the screen like below screen,




  • Now open newly created permission set named as "My Custom Permission Set" and then click on "Object Setting" link and it will open list of objects and then click on the object link for which you want to give the extra permission which not available in Profile. For the above example click on "Account" object.




  • Once we click on "Account" link it will open "my Custom Permission Set" for "Account" object and then click on "Edit" button and set the extra permission on Object and Field level and finally click on "Save" button.

  • Now its time to set the above create permission set to different user and for our case it is for user "U2". So, open user "U2" and then scroll down to " Permission Set Assignments" section and click on "Edit Assignments" button.

  • Once click it will shown you the available and enabled permission sets bucket and form available bucket we have to add "My Custom Permission Set" to enabled bucket and once done then click on "Save" button and its done. Now test the scenario.



Is it mandatory to select User License while creating permission sets? If not, what is the significance of selecting a User License?


It is not mandatory to select a User License while creating a permission sets.
If users with one type of license will use this permission set, then choose the same license that’s associate with them.
If you are planning to assign this permission set to multiple users with different licenses then, choose none.


Thursday, May 31, 2018

Lightning Datatable using Fieldset

1. Create a util class (FieldSetExample) which is responsible to return list of fields (label, api and       type) available under field set of an object passed as parameters by a method.

public class FieldSetExample {
    /**
     * This method is responsible to return list of fields (label, api and type) avaliable
     * under field set of an object passed as parameters.
     * */
    public static List<FieldSetProperties> getFieldFromFieldSet(String objApi, String fieldSetName){
        List<FieldSetProperties> lstOfWrapper = new List<FieldSetProperties>();
        
        Schema.SObjectType sObjType = Schema.getGlobalDescribe().get(objApi);
        Schema.DescribeSObjectResult desSObjRslt = sObjType.getDescribe();            
        Schema.FieldSet fieldSetIns = desSObjRslt.FieldSets.getMap().get(fieldSetName);
        
        for( Schema.FieldSetMember fieldSetMember : fieldSetIns.getFields() ){
            FieldSetProperties wrapperIns = new FieldSetProperties();
            
            wrapperIns.label = String.valueOf(fieldSetMember.getLabel()); 
            wrapperIns.fieldName = String.valueOf(fieldSetMember.getFieldPath()); 
            wrapperIns.type = String.valueOf(fieldSetMember.getType()).toLowerCase();
            
            lstOfWrapper.add(wrapperIns);
        }        
        
        return lstOfWrapper;
    }
    
    /**
     * Wrapper class to hold fieds properties like label, field api and field type.
     * */
    public class FieldSetProperties{
        @AuraEnabled
        public String label;
        @AuraEnabled
        public String fieldName;
        @AuraEnabled
        public String type;
    }
}

2. Create a server side controller class (DataTableExampleController) for the lightning component (dataTableExample) used to display records using data table.

public class DataTableExampleController {
    
    @AuraEnabled
    public static DataTableDetails getDataTableDetails(String objApi, String fieldSetName){
        DataTableDetails dataTableDtls = new DataTableDetails();
        List<FieldSetExample.FieldSetProperties> lstOfFieldSetProperties = FieldSetExample.getFieldFromFieldSet(objApi, fieldSetName);
        
        if(lstOfFieldSetProperties != null && lstOfFieldSetProperties.size() > 0){
            String strQuery = 'SELECT ';
            for(FieldSetExample.FieldSetProperties inst : lstOfFieldSetProperties){
                dataTableDtls.lstOfFieldLabels.add(inst);
                
                strQuery = strQuery + inst.fieldName + ',';
            }
            if(!strQuery.equalsIgnoreCase('SELECT '))
                strQuery = strQuery + 'Id FROM ' + objApi;
            
            dataTableDtls.lstOfSObjs = Database.query(strQuery);
        }
        
     return dataTableDtls;
    }
    
    
    public class DataTableDetails{
        @AuraEnabled
        public List<sObject> lstOfSObjs = new List<sObject>();
        @AuraEnabled
        public List<FieldSetExample.FieldSetProperties> lstOfFieldLabels = new List<FieldSetExample.FieldSetProperties>();
    }
}

3. Create the lightning component (dataTableExample.cmp).

<aura:component controller="DataTableExampleController">
    <aura:attribute name="lstOfRecords" type="Object"/>
    <aura:attribute name="columnsHeader" type="List"/>
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
        
    <lightning:datatable data="{!v.lstOfRecords}"
                         columns="{!v.columnsHeader}"
                         keyField="Id"
                         hideCheckboxColumn="true"/>
</aura:component>

4. dataTableExampleController.js

({
    doInit : function(component, event, helper) {
         helper.getDataTableRespone(component, event);
    }
})

5. dataTableExampleHelper.js

({
 getDataTableRespone : function(component, event) {
        var action = component.get("c.getDataTableDetails");
        action.setParams({
            objApi : 'YOUR OBJECT API',
            fieldSetName : 'YOUR FIELD SET NAME'
        });
        action.setCallback(this, function(response){
            var state = response.getState();
            if(state === 'SUCCESS'){
                //console.log('::::::::::::: SUCCESS :::::::::::::'+JSON.stringify(response.getReturnValue().lstOfFieldLabels));
                component.set("v.columnsHeader", response.getReturnValue().lstOfFieldLabels);
                
                component.set("v.lstOfRecords", response.getReturnValue().lstOfSObjs);    
            }else if (state === 'ERROR'){
                console.log('::::::::::::: ERROR :::::::::::::');
            }
        });
        $A.enqueueAction(action);
 }
})

6. Call the above component from an application (dataTableExampleApp.app)


<aura:application extends="force:slds">
 <c:dataTableExample />
</aura:application>

How to fetch Field(s) under Fieldset using Apex.



public class FieldSetExample {
    /**
     * This method is responsible to return list of fields (label, api and type) avaliable
     * under field set of an object passed as parameters.
     * */
    public static List<FieldSetProperties> getFieldFromFieldSet(String objApi, String fieldSetName){
        List<FieldSetProperties> lstOfWrapper = new List<FieldSetProperties>();
        
        Schema.SObjectType sObjType = Schema.getGlobalDescribe().get(objApi);
        Schema.DescribeSObjectResult desSObjRslt = sObjType.getDescribe();            
        Schema.FieldSet fieldSetIns = desSObjRslt.FieldSets.getMap().get(fieldSetName);
        
        for( Schema.FieldSetMember fieldSetMember : fieldSetIns.getFields() ){
            FieldSetProperties wrapperIns = new FieldSetProperties();
            
            wrapperIns.label = String.valueOf(fieldSetMember.getLabel()); 
            wrapperIns.fieldName = String.valueOf(fieldSetMember.getFieldPath()); 
            wrapperIns.fieldType = String.valueOf(fieldSetMember.getType()).toLowerCase();
            
            lstOfWrapper.add(wrapperIns);
        }        
        
        return lstOfWrapper;
    }
    
    /**
     * Wrapper class to hold fieds properties like label, field api and field type.
     * */
    public class FieldSetProperties{
        public String label;
        public String fieldName;
        public String fieldType;
    }
}

Data Cloud Part 6: Practical (Ingest Physical Store's Customer details and Sales details)

Hope you have already created your Data Cloud Org and also downloaded the Customer's details and Sales details from previous posts.  Now...