ads

Thursday 30 August 2018

Custom Permission using in Workflow Rule in Salesforce

Select formula evaluates to true in the Workflow Rule.



Workflow Field and Formula Fields Updates

Workflow Field Updates

1. Changes in Parent record cannot be updated in child records.
2. If the record was updated with workflow field updates, fires before and after triggers one more time. Custom validation rules, duplicate rules, and escalation rules are not run again.
3. It considers criteria before updating the field value.

Note: Workflow field update is recommended over formula field for better performance.


Formula Fields 

1. 
Change in Formula field cannot invoke trigger or workflows.
2. Changes in Parent record will be automatically reflected in child records.
3. Formula field values cannot be modified manually.

Create New Sub Folder in Salesforce Reports and Dashboards

1. Go to Reports tab.


2. Select the Folder where you wan to create the Sub Folder.

3. Click New Folder inside the Parent folder.



 Sub Folder view in Salesforce



Find duplicate Accounts in Lightning Experience

1. Open Account Record.


2. Select Related record. If duplicate Accounts are exist, you will found View Duplicates button 
to merge it.

Email to Case Assignment Rule not firing

This problem can be solved by making the Case Owner field blank in Case Settings.

Case Owner field is used to find the owner of the case, which can be either an individual user 
or a queue. This field is optional.

Note:1. If you specify a case owner, auto-assignment rules are ignored.
2. You can’t delete a queue that a routing address refers to. Either delete the routing address,
 or edit the routing address settings to point to a different queue.


Insert comma between two field value in formula field


Insert Fields:



To insert ',' between two field values in Formula field in Salesforce use &","& between two fields values.

For example: Account Name and Account number are two fields. Create a field as Description and in the formula editor type Name&",'"&AccountNumber to separate those values with comma.


Output:

Convert String to sObject using Apex in Salesforce

Code Format:


//Setting String str as Contact

String str = '
Contact';

//Casting String to sObject

sObject objc = Schema.getGlobalDescribe().get(str).newSObject();
objc.put('LastName', 'Test');
objc.put('
AssistantName', 'Testing');
objc.put('Department', 'Testing');

system.debug('objc is ' + objc);

Output:


Wednesday 29 August 2018

Cover addError() in trigger in Apex Test

Sample Trigger:


trigger RestrictAccountByName on 
Account(before insert, before update) {
    
    for (
Account Acc : Trigger.New) {
        if(Acc.Name == 'INVALIDNAME') {   //invalidname is invalid
            Acc.AddError('The Account Name "'+Acc.Name+'" is not allowed for DML');
        }
    }
}

Sample Test Class:

@isTest
private class RestrictAccountByName {
    @isTest static void test() {
        
Account Acc = new Account(Name = 'INVALIDNAME');
        Database.SaveResult result = Database.insert(Acc, false);
        System.assertEquals('The  Name "'+Acc.Name+'" is not allowed for DML',result.getErrors()[0].getMessage());
    }
}

Cover Page Reference method in test class in Salesforce

Apex Class:

public class Reference {
    public 
Reference () {
    }
    
    public PageReference SFDCForyou() {
        PageReference pr = new PageReference('http://www.SFDCForyou.com');
        pr.setRedirect(true);
        return pr;
    }
}

Test class:

@isTest
private class Testclass {
    @isTest static void test() {
        
Reference r = new Reference ();
        r.
SFDCForyou();
    }
}

System.CalloutException: Method can not be null

IF error occur like System.CalloutException: Method can not be null issue, then u should use POST Or GET Or PUT in your request.


Sample Code:

        HTTPRequest firstreq = new HTTPRequest();
        firstreq.setEndPoint('Enter Your End Point URL');
firstreq.setMethod('GET');

Line Break in Formula Field in Salesforce

Formula Field:


IF( CONTAINS(Name, 'SFDCForyou'),
'SFDCForyou' & BR() &  'Department',
'Not belongs to SFDCForyou department'

)

Formula Editor:












Output:


style not working apex:outputtext

Code Format:


<apex:page>

     <apex:outputText style="font-size:20px; font-weight:bold; color:brown;" 
                                   value="Style working for this tag."/>
     <br> </br>
     <br> </br>  

     <apex:outputText style="font-size:20px; font-weight:bold; color:brown;">
                              Style not working for this tag</apex:outputText>

</apex:page>

Output:


Get batch status using Apex code

Code Format:


    public String BatchJobstatus {get;set;}
    Id batchJobId;

/*****call the batch class using Method******/



 public void runBatch(){
        batchContactUpdate batchObj = new batchContactUpdate();
        batchJobId = Database.executebatch(batchObj);
    }

/*****check the status of batch Using Method******/


   

 public void checkBatchStatus(){
      AsyncApexJob JobObj = [SELECT Status FROM AsyncApexJob WHERE ID =: batchJobId];
                    
       BatchJobstatus = JobObj.Status;
    }

Find number of pending batch jobs in Salesforce

Code Format:


List<String> JobStatus = new List<String> {'Holding', 'Queued', 'Preparing', 'Processing'};


List<AsyncApexJob> pendingJobsStatus = [SELECT Id FROM AsyncApexJob WHERE Status IN: JobStatus];


pendingJobsStatus.size() ;// Note :  This will give you the  number of pending batch jobs
                                                         in Salesforce

Fetch users with Salesforce User License using SOQL Query

Using SOQL Query:


SELECT Id FROM User WHERE Profile.UserLicense.Name  =  'Salesforce'

Using Salesforce Report :

1. Setup --> Customize --> Users --> Fields --> Create New Field.

2. Create a "Text" formula field.

3. Use "Profile.UserLicense.Name" in the formula.

4. Save the formula field.Use the formula field in the report.

Regular Expression for numbers alone validation in Salesforce

Formula: 


NOT( REGEX( NumberField__c , '[0-9]*' ) )

To set created date for a test record in test class in Salesforce

    Code Format:


     Student__c stud = new Student__c(Student_Name__c = 'Testing');
     insert stud;  

     Test.setCreatedDate(stud.Id, DateTime.newInstance(1000,20,20));  

Reset the governor limits within a test class

Test.startTest() and Test.stopTest() are very useful when your test class hits Salesforce Governor Limits. These methods can be used to reset the governor limits within a test class.


The code inside Test.startTest() and Test.stopTest() have new set of Salesforce Governor Limits.
 As a good practice, make sure initializing the variables, fetching records, creating and updating records are coded before Test.startTest() and Test.stopTest() and calling the controllers for code coverage is
 done inside Test.startTest() and Test.stopTest(). The code before Test.startTest() and after Test.stopTest() have new set of Salesforce Governor Limits and code between Test.startTest() and Test.stopTest() have new set of Salesforce Governor Limits.

Example Test Class:

private class ExampleTestClass {
        static TestMethod void test() {
                /*
                        Declare the variables, Fetch the required records, Create and update sample records
                */
                /*
                        Test.startTest();
                        /*
                        Call the controller for code coverage
                        */
                        Test.stopTest();
                */
        }
}

Cover the test coverage for getURL method

 To cover the test coverage for getURLmethod,         use Test.setCurrentPage(Page.PageName).


 Test.setCurrentPage(Page.PageName) will help you to cover the codes which makes use   of ApexPages.currentPage().getUrl().

Mock HTTPCallOuts available in Salesforce

The mock HTTPCallOuts available in Salesforce are below:


1. StaticResourceCalloutMock
2. HttpCalloutMock

Get Standard Price Book Id in test class

By using this "Test.getStandardPricebookId()" we get Standard Price Book Id in test class.


Code Format:

Id pricebookId = Test.getStandardPricebookId();

Tuesday 28 August 2018

Portal Health Reports

Portal health reports show how much access your portal users have to the data in your organization.


Go to Setup --> Security Controls --> Portal Health Check to open it...


To Get The Record Count Of SOQL query into a variable in Salesforce

Code Format:


    public static Integer ContactCount() {
        return [ SELECT COUNT() FROM Contact ];
    }

Or

Integer n = [ SELECT COUNT() FROM Contact ]; 

To calculate no of hours since the record is created using formula field in Salesforce

Formula Field:


(NOW() - CreatedDate) * 24 )

HTTP Methods available in Salesforce

1. HEAD

Retrieves resource metadata.

2. GET
Queries data.

3. 
PUT
Upserts records.
4. POST
Creates record.

5. PATCH
Updates record.

6. DELETE
Deletes record.

SOAP API Methods using WSDL from Salesforce

1.) create()


2.) update()

3.) upsert()

4.) delete()

5.) merge()

6.) query()
To perform an initial query against a Salesforce Org.

7.) queryAll()
To perform a query against a Salesforce org that returns records in the Recycle Bin as well as active records.

8.) queryMore()
To get additional batch results from a query. Default batch size is 500. Minimum batch size is 200 and maximum batch size is 2000.

9.) retrieve()
To retrieve data from objects based on their ids.

Example:
retrieve("Id, Name, Website", "Accounts", ids)

10. emptyRecycleBin()

11. login()
Uses username and password to log in. Gets session id and URL to maintain the connection.

12. logout()

13. search()

14. getDeleted()
Retrieves deleted records for the specific time interval.

Example:
getDeleted("Account", StartTime, EndTime)

15. getUpdated()
Retrieves updated records for the specific time interval.

Example:
getUpdated("Account", StartTime, EndTime)

16.getUserInfo()

17.) resetPassword() 

18.) convertLead()

19.) process()

20.) getServerTimeStamp()

21. setPassword()

22. sendEmail()

23. sendEmailMessage()

24.) describeTabs()

25.) describeLayout()

26.) describeGlobal()

27.) describeSObjects()

28. describesoftphoneLayout()

To get current Path: ApexPages.currentPage().getUrl()

Code Format:


Visualforce page:
<apex:page controller="Path">
    <apex:form >
        <apex:pageBlock >
            Current URL is {!currURL}
        </apex:pageBlock>
    </apex:form>
</apex:page>

Apex Class:
public with sharing class Path {
    
    public String currURL {get;set;}
    
    public Path() {
        currURL = ApexPages.currentPage().getUrl();
    }
        
}

Output:


Hide lines and borders in pageBlock tag in Visualforce Page

Code Format:

<apex:page standardController="Contact" sidebar="false">

 <style>

    .bPageBlock .pbBody .dataCol {

        border:0px;

    }

    .bPageBlock .pbBody .labelCol {

        border:0px;

    }

</style>

    <apex:form >

        <apex:pageBlock mode="maindetail">

            

                <apex:pageBlockSection columns="2"  >

                <apex:selectList value="{!Contact.Name}"/>

                <apex:inputField value="{!Contact.AssistantName}"/>

                <apex:inputField value="{!Contact.Birthdate}"/>

                <apex:inputField value="{!Contact.Department}"/>

                <apex:inputField value="{!Contact.LeadSource}"/>

                <apex:inputField value="{!Contact.Phone}"/>


            </apex:pageBlockSection>

            <apex:pageBlockButtons >

                <apex:commandButton value="Save" action="{!save}"/>

                <apex:commandButton value="Cancel" action="{!cancel}"/>

            </apex:pageBlockButtons>

        </apex:pageBlock>

    </apex:form>

</apex:page>


Output:


Monday 27 August 2018

Command Buttons Align Right in Visualforce page

Code Format:

<apex:page showHeader="false" controller="example" >

<apex:form >
   <apex:panelGrid columns="1" style="float:right;">

        <apex:commandButton value="First"/>
        <apex:commandButton value="Second"/>
        <apex:commandButton value="Third"/>

        <apex:commandButton value="Done"/>
      
    </apex:panelGrid>

</apex:form>  
   
</apex:page>



Output: 

Friday 17 August 2018

write a validation rule of Multiselect Picklist in Salesforce

In this INCLUDES() is used to write a validation rule of Multiselect Picklist in Salesforce.

Determines if any value selected in a multi-select picklist field equals a text value you specify.

Syntax:

INCLUDES(Multipicklist_Api_Name, Text_Value)

Get Case Id from CaseComment object using trigger

Sample Code:

Trigger getParentCase on CaseComment(after insert) {

set<Id> CCIds = new set<Id>();

      
    
     for ( CaseComment c: trigger.new ) {
     CCIds.add(c.Id);
     }
    
     List < CaseComment > lCComment = [ SELECT Id, Parent.Id FROM CaseComment
                                                                                                                                          WHERE Id IN: CCIds];
    
   set<Id> CaseIds= new set<Id>();        
for ( CaseComment c: lCComment) {
        
CaseIds.add(c.Parent.Id); // collect case Id in set of Id

        }

}

update parent records when task created or updated

Sample Trigger:

trigger  TaskParentUpdate  on Task (after insert, after update) {

    Set < Id > setIds = new Set < Id >();


if(IsInsert || IsUpdate) {

    for ( Task tsk : trigger.New) {
        if ( tsk.WhatId.getSobjectType().getDescribe().Name == 'Accounts' )
        setIds.add(tsk.WhatId);
    }
   
}

    List<Account> lAccount = [Select Id,description From Account where Id IN:setIds];


  List<Account> UpdateAccount = new List<Account>();

    for(Account a:lAccount){
        a.description = 'Description Updated';
       UpdateAccount.add(a);

   }


  update UpdateAccount;


}

Help text for apex:inputField

Code Format:

Visualforce Page:

<apex:page controller="helpcontroller">
<apex:form >
        <apex:pageBlock >
           
                <apex:pageBlockSection >
                
                <apex:pageBlockSectionItem helpText="Owner of the Account">
                
                    Owner Name <apex:inputField value="{!acc.Name}"/>
                    
                </apex:pageBlockSectionItem>
               
                </apex:pageBlockSection>
            
        </apex:pageBlock>
</apex:form> 
</apex:page>


Apex Class:

public with sharing class helpcontroller{
       public Account acc{get;set;}
        public Sample() {
    }    
}

Ouput:

Check object level security within a Visualforce page


By using this " {!$ObjectType.Lead.Accessible} " to check object level security within a Visualforce page in Salesforce.

VF page Code Format:

<apex:page>

    {!$ObjectType.Lead.Accessible} 

</apex:page>