Friday, June 30, 2017

calling controller method from javascript in salesforce?

In salesforce we use java script either in a visualforce page or we execute javascript on custom button (i.e a custom button is override with a java script). While the java script is being executed we may require to call a controller class method which may have a piece of code required for custom functionality. In case of visualforce page we may use action function which can call the controller method from java script directly. 


For calling a controller method from java script written to override a custom button, we need to use AJAX method callout. In the example below, a custom button on opportunity is overridden with a java script and from the java script calls a method of a controller class



{!REQUIRESCRIPT("/soap/ajax/20.0/connection.js")} 
{!REQUIRESCRIPT("/soap/ajax/20.0/apex.js")} 
sforce.apex.execute("updateStatusClass","MethodeWithoutParameters",{});

First two lines of the java script code makes the AJAX toolkit available in the java script of the custom button. As you can see in the code snippet, we have to use method sforce.apex.execute for calling the controller method. We have to just specify the class name in double quotes followed by coma and then method name in double quotes ("className","Methode of that class",{}) We can also call the controller method from Visualforce page using AJAX.  So as to make the AJAX available in visualforce page we have call it as below

<script src="../../soap/ajax/28.0/connection.js" type="text/javascript">
  <!-- AJAX method here -->
</script>


Following is the class that is being called from above java script.


/* This is a class for demo purpose, methods of this class are called from  java script
a method without parameter as well as method with parameters is called form java script*/

Public Class updateStatusClass{
 Public updateStatusClass(){
  /*This is a constructor of the demo class*/
 }
 /*Method without any parameters */
 Public void MethodeWithoutParameters(){
  system.debug('**Method without any parameters**');
 }
}


Custom Button clicks count:

There is custom button or link ,when click the button ,it will open the visual force page and count the how many times that button got clicked.

OnClick JavaScript{!REQUIRESCRIPT("/soap/ajax/30.0/connection.js")}

try{
var clickCntStr = '{!opportunity.Number1__c}';
clickCntStr = clickCntStr == null || clickCntStr == "" ? "0" : clickCntStr;

clickCnt = parseFloat(clickCntStr);
++clickCnt;
// alert(clickCnt);

var updOpp = new sforce.SObject('opportunity');
updOpp.Id = "{!opportunity.Id}";
updOpp.number1__c= clickCnt;
//alert(updOpp.number1__c);
var result = sforce.connection.update([updOpp]);

}
catch(ccex){
console.log('click count increment error: ' + ccex);
}
window.open('/apex/Countbuttonclickpage?Id={!opportunity.Id}');
Visual force page:Countbuttonclickpage

<apex:page standardController="opportunity" >
  <apex:form >
    <apex:outputLabel value="Count of buttton click: {!opportunity.Number1__c}"></apex:outputLabel>
  </apex:form>
</apex:page>

select query using javascript in salesforce

select query using javascript  in salesforce 

Sometimes we may need to query records in java script in salesforce. For this we can use "sforce.connection.query". Let us demo how we can query records from any object and iterate through the returned records.


In the following example we will query 10 account records and also iterate through the retured records. Create a custom button on any object and override it with a java script as below.

{!REQUIRESCRIPT("/soap/ajax/20.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/20.0/apex.js")}

Result = sforce.connection.query("Select Name, Id from account limit 10");
records = Result.getArray("records");

for (var i=0; i< records.length; i++) {
      var accRecord = records[i];
      log(Account Name + " -- " + accRecord.Name);
   log(Account Id + " -- " + accRecord.Id);


The returned records can be debugged using log. 


What is offset in Apex and Using offset in soql

What is offset in Apex and Using offset in soql 


We can Use OFFSET keyword in SOQL to specify the starting row from the result  returned by your query. This is useful in cases where we need to quickly jump to a particular subset of the total result returned by SOQL query. For example if there are 20 records then, if we specify offset as 10 in the query then it would return record 11 through 20.

OFFSET keyword can be used to implement pagination in visaulforce page tables.

Simple Ajax Example Using Visualforce Page.

Simple Ajax Example Using Visualforce Page.


Hi,
Here i am going to give simple example of using Ajax functionality in Visualforce, In the below example when ever a user enters a key value then it will call the Controller method and fetch the accounts related to text box value.

Visualforce Page:

<apex:page controller="AjaxWildcardController">
  <apex:form >
      <apex:pageBlock >
        Type Account Name Here :<apex:inputText value="{!inputtext}" >
          <apex:actionSupport action="{!actionSupMethod}" event="onkeyup" reRender="outptText" />
        </apex:inputtext>
      </apex:pageBlock>  

    <apex:pageblock >
      <apex:pageblocktable value="{!accList}" var="acc" id="outptText">
        <apex:column value="{!acc.name}"/>
        <apex:column value="{!acc.accountnumber}"/>
      </apex:pageblocktable>
    </apex:pageblock>
  </apex:form>
</apex:page>

Controller :

public class AjaxWildcardController {
Public string inputtext{get;set;}
    Public List<account> accList{get;set;}
    Public boolean flagshow{get;set;}
    Public AjaxWildcardController(){
    flagshow = false;
    }    
    
    Public void actionSupMethod(){
     system.debug('inputtext-->'+inputtext);
    
      accList = database.Query('select name,accountnumber from account where name like '+'\''+'%'+inputtext+'%'+'\'');
    }
        

}

Output : 

save image


Wild card search in soql.

Wild card search in soql.

Use like operator along with % character in where clause of SOQL to implement wild card search. In the following example query returns account records matching input text with account name. %'input string'% in where clause returns all the accounts having the input string anywhere in the account name. For ex.if the input string is 'tech' , query will return account with names 'Willsinfotech' and also 'infotech solutions'

Visualforce Page:

<apex:page controller="WildcardSOQLController" id="pg">
  <apex:form id="fm" >
    <apex:pageblock id="pb" >
        <apex:inputtext value="{!inputtext}" id="inpt"/>
        <apex:commandbutton value=" Search " action="{!searchRecords}" />
    </apex:pageblock>
    <apex:pageblock rendered="{!flagshow}">
      <apex:pageblocktable value="{!accList}" var="acc">
        <apex:column value="{!acc.name}"/>
        <apex:column value="{!acc.accountnumber}"/>
      </apex:pageblocktable>
    </apex:pageblock>
    
    
  </apex:form>
</apex:page>


Controller Class :

Public class WildcardSOQLController {
    Public string inputtext{get;set;}
    Public List<account> accList{get;set;}
    Public boolean flagshow{get;set;}
    
    Public WildcardSOQLController(){
    flagshow = false;
    }    
    
    Public void searchRecords(){
    
      accList = database.Query('select name,accountnumber from account where name like '+'\''+'%'+inputtext+'%'+'\'');
      if(accList !=null && accList.size()>0){
       flagshow = true;
      }
    }
}


What is the Difference Between Rendered, ReRender and RenderAs in visualforce?

What is the Difference Between Rendered, ReRender and RenderAs in visualforce?

Rendered :

A visualforce component in a VF page can be displayed or hidden by using rendered attribute. Rendered is bound to a Boolean variable in controller which can be switched between true and false making the vf component display or hide depending on Boolean value.

As an example:

Visualforce Page:

<apex:page controller="RenderedControllr">
 <!-- Rendered  Demo -->
 <apex:form >
   <apex:pageBlock >
    <apex:commandButton value="Show Bottom Page Block" action="{!ShowBlockMethod}"/>
   </apex:pageBlock>
    
   <apex:pageBlock rendered="{!ShowpageBlockFlag}">
    Account Name  :<apex:outputField value="{!accRec.name}"/>
<br/>
    Account Number :<apex:outputField value="{!accRec.accountnumber}"/>
   </apex:pageBlock>
 </apex:form>

</apex:page>

Controller : 

Public class RenderedControllr {
 Public Boolean ShowpageBlockFlag{get;set;}
 Public Account accRec{get;set;}

  Public RenderedControllr(){
   accRec = [select name,id,accountnumber from account limit 1];
   ShowpageBlockFlag = false;
  }
   
  Public void ShowBlockMethod(){
   ShowpageBlockFlag = true;
  }

}

Out put :

save image

Once you click on Show Bottom Page Block..
save image


Here lower page block is given rendered that is bound to a boolean variable "ShowpageBlockFlag". Initially (in constructor) this variable is set to false which hides the lower page block.

Once we click the command button, "ShowBlockMethod" method is called where this boolean is set to true and hence the lower page block gets displayed. 


ReRender :
Rerender is used to refresh a particular section of the visualforce page. We have to just mention the id of the page section (in the Rerender attribute) that needs to be refreshed.

In the following example Clicking of the command button "Refresh Lower Page Block" refreshes the lower page block.

Visualforce Page:

<apex:page controller="ReRenderControllr">
 <!-- Render and Rerender Demo -->
     <apex:form >
           <apex:pageBlock >
                <apex:commandButton value="Refresh Lower Page Block" action="{!ShowBlockMethod}" rerender="pgblckID"/>
           </apex:pageBlock>
        
           <apex:pageBlock id="pgblckID">
               <b>  Output Text   : </b>   <apex:outputText value="{!OutPutString}"/>
           </apex:pageBlock>
     </apex:form>

</apex:page>


Controller Class: 

public class ReRenderControllr {

 Public string OutPutString{get;set;}
   
  Public ReRenderControllr(){
    OutPutString = 'Test value set in Constructor';
  }
   
  Public void ShowBlockMethod(){
   OutPutString = 'value set in method called by button click' ;
  }
  

}


Output:
save image



save image


Initially when the page is loaded the output string value is set in constructor as "Test value set in constructor".'

When the button is pressed method "ShowBlockMethod" is called where "OutPutString"  value is changed also lower page block is refreshed and hence the new value is displayed in the lower page block.

rerender="pgblckID" statement in command button indicates that the page block section with id ="pgblckID" should be refreshed when button is pressed. Only Lower page block is refreshed rest of the page remains as it is.

A single Rerender attribute could be used to refresh many sections of the page. For example: reRender= "pgblck1, pgbcl2"


RenderAs
This is used with page component and renders the page in the specified format. 

Following page will give output in pdf form /render as pdf.

Visualforce Page:

<apex:page standardController="Account" renderAs="pdf">
     <apex:pageBlock >
          <apex:outputField value="{!Account.name}"/>
          <apex:outputField value="{!Account.AccountNumber}"/>
     </apex:pageBlock>
</apex:page>