Wednesday, March 29, 2017

How To Get Current Page URL from Apex code in Salesforce

To implement this we need to use Apexpages.currentPage() methods.

Get Current Page URL
getHeaders() : It return a map of the request headers, where the key string contains the name of the header, and the value string contains the value of the header.
After that get the ‘Host’ key value from that map

getUrl() : It returns the relative URL associated with the PageReference when it was originally defined, including any query string parameters and anchors.
Apex Code :


public with sharing class currentpageurl{
    public  String  headerdata{get;set;}
    public string urlvalue{get;set;}
    public string url{get;set;}
         
public currentpageurl(){      
headerdata= ApexPages.currentPage().getHeaders().get('Host');
urlvalue=Apexpages.currentPage().getUrl();
url='https://' + headerdata+ urlvalue;
    }  
}
Visualforce Page : 

<apex:page controller="currentpageurl"> 

1. {!headerdata} 
2. {!urlvalue} 
3. {!url} 

</apex:page>

 Output:

1. c.cs3.visual.force.com

2. /apex/Pageurl

3. https://c.ap2.visual.force.com/apex/Pageurl

Saturday, March 11, 2017

How to pass parameters from JavaScript to Controller in Salesforce

VisualForce Page

<apex:page>
  <apex:form>
    <apex:pageblock>
   <select id="dropDownId">
   <apex:commandButton value="Update" onclick="validate();return false;" />
 </apex:pageblock>

  <apex:actionFunction name="updateRecords" action="{!performUpdate}"
                              reRender="resultPanel,errMsg" status="statusSaveTrip">
        <apex:param id="status" name="selStatus" value="" />
        <apex:param id="renerTabId" name="renderTabId" value="" />
        <apex:param id="phone" name="phone" value="" />
    </apex:actionFunction>
  </apex:form>
</apex:page>

<script>
  funtion validate(dropDownId )
  {
    //Some processing here
  updateRecords(param1 value,param2 value,param3 value);
  }

</script>

Apex Controller

public class MyController
{
   public MyController()
   {
 
   }
 
   public pagereference performUpdate()
    {
     System.debug('..entered...performUpdate..');  
     String selDropdownVal=Apexpages.currentPage().getParameters().get('selStatus');
     String tableIdtoRender = Apexpages.currentPage().getParameters().get('renderTabId');
     String phone = Apexpages.currentPage().getParameters().get('phone');
     System.debug('..selDropdownVal...'+selDropdownVal+'..'+tableIdtoRender+'..'+phone);
   }

}

What is the maximum number of Promoted Terms we can create in Salesforce

These are nothing but the terms or words which we will be attaching to knowledge articles to make the smother search of the Articles very quick based on prompted words which matches with given search keywords.

These terms are limited to 2000 for an organisation and for better search results it's better to have less than 2000.

Friday, March 10, 2017

How to stop recursive trigger in salesforce

Below are the two primary scenarios:

1) Many Developers face recursive trigger , or recursive update trigger. For example in 'after update' trigger, Developer is performing update operation and this lead to recursive call.

2) You want to write a trigger that creates a new record ; however, that record may then cause another trigger to fire, which in turn causes another to fire, and so on.

We can create a class with a static Boolean variable with default value true. In the trigger, before executing your code keep a check that the variable is true or not. Once you check make the variable false.

Apex Class with Static Variable 

public class ContactTriggerHandler {
     public static Boolean isFirstOccurance = true;
}

  Trigger Code
trigger ContactTriggers on Contact (after update)
{
    Set<String> accIdSet = new Set<String>();
    if(ContactTriggerHandler. isFirstOccurance)
    {
        ContactTriggerHandler. isFirstOccurance = false;
         for(Contact conObj : Trigger.New)
  {
            if(conObj.name != 'Test')
     {
                accIdSet.add(conObj.accountId);
            }
         }
   // any code here
    }

}

Locking Statements FOR UPDATE

Apex allows you to lock sObject records while they’re being updated in order to prevent race conditions and other thread safety problems. While an sObject record is locked, no other client or user is allowed to make updates either through code or the Salesforce user interface.

Account [] accounts = [SELECT Id FROM Account LIMIT 2 FOR UPDATE];

NOTE:- 
1. While the records are locked by a client, the locking client can modify their field values in the database in the same transaction. Other clients have to wait until the transaction completes and the records are no longer locked before being able to update the same records. Other clients can still query the same records while they’re locked.
2. If you attempt to lock a record currently locked by another client, you will get a QueryException. Similarly, if you attempt to update a record currently locked by another client, you will get a DmlException.
3. If a client attempts to modify a locked record, the update operation might succeed if the lock gets released within a short amount of time after the update call was made. In this case, it is possible that the updates will


Implement Enter Key to Execute Method in salesforce for search

How to Call Apex method on click of Enter button.
Solution :-
We can use the "keyCode==13" with actionfuction to call the apex method on Enter Key event like below

Apex Class:
public with sharing class EnterSearchController {

    public string strKey {get;set;}
    public List<Account> lstAccount {get;set;}
    public EnterSearchController()
    {
        lstAccount = new List<Account>();
    }

    public pageReference cancel()
    {
        return new pageReference('/001/o');
    }
   
    public void search()
    {
        if( strKey != null && strKey !=''  )
        {
            String wildcard = '%'+strKey+'%';
            lstAccount = [select id,name from account where name like :wildcard  ] ;
        }
       
    }

}
Visualforce Page:

<apex:page controller="EnterSearchController" >
    <apex:form >
        <apex:pageBlock >
        <apex:actionFunction action="{!search}" name="actionFunction" />
       
            <apex:pageBlockSection >
                <apex:inputText value="{!strKey}" onkeydown="if(event.keyCode==13){this.blur();actionFunction();}" />
               
            </apex:pageBlockSection>
            <apex:pageBlockButtons >
                <apex:commandButton action="{!cancel}" value="cancel" />              
                <apex:commandButton action="{!search}" value="Search" />              
           
            </apex:pageBlockButtons>
           
            <apex:pageBlockSection columns="1" >
                <apex:pageBlockTable value="{!lstAccount }" var="acc">
                    <apex:column value="{!acc.name}"/>
                   
                </apex:pageBlockTable>
            </apex:pageBlockSection>
           
        </apex:pageBlock>
    </apex:form>
</apex:page>

Calculate Overall Code Coverage in salesforce

We can use Tooling API  to calculate the coverage individually for an apex class/ apex trigger or overall coverage.

1) How many lines are covered for a specific class or trigger:

SELECT NumLinesCovered, NumLinesUncovered FROM ApexCodeCoverage WHERE ApexClassOrTriggerId =

2) Which lines are covered for a specific class or trigger:

SELECT Coverage FROM ApexCodeCoverage WHERE ApexClassOrTriggerId =

3) The current org-wide coverage:

SELECT PercentCovered FROM ApexOrgWideCoverage

To test these queries you may use Workbench (workbench.developerforce.com) as follows: 1) Go to Utilities | REST Explorer 2) Select GET 3) Enter the following URL:

/services/data/v37.0/tooling/query/?q=YOUR_QUERY

where YOUR_QUERY should be the query to execute

4) Click "Show Raw Response".


If you are still not confident enough, then you can do a production validation (click on validate only button in the tool which you are using to deploy) and it will give you errors/warnings if there is no coverage for classes.