Sunday, August 31, 2014

calling controller method from javascript in salesforce?

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**');
 }
}










Saturday, August 30, 2014

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. 









Friday, August 29, 2014

How to Pass Parameters in Action Function

How to Pass Parameters in Action Function 

We can pass parameters to controller method that is being called using action function. For this we can use attribute "param" in visualforce.


Following is an example to demonstrate the parameter passing using param in action function. Clicking the checkbox calls the controller method using action function, first name and last name are passed to the controller using param attribute

Visualforce Page:

<apex:page controller="passparam">
 <apex:form>
  <apex:pageblock id="pgblck">
   First name : <apex:inputtext id="fn" value="{!firstname}">
   Last Name :<apex:inputtext id="ln" value="{!lastname}">
 Click this to See full name :  <apex:inputcheckbox onclick="calculate('{!$Component.fn}','{!$Component.ln}')">
Full Name:    <apex:outputtext value="{!fullname}"></apex:outputtext>
  </apex:inputcheckbox></apex:inputtext></apex:inputtext></apex:pageblock>
<apex:actionfunction action="{!calpercentage}" name="calAF" rerender="pgblck">
<apex:param assignto="{!firstname}" name="param1" value="">
<apex:param assignto="{!lastname}" name="param" value="">
</apex:param></apex:param></apex:actionfunction>
 </apex:form>
 <script>
  function calculate(frst,lst){
  var Fname = document.getElementById(frst).value;
 var Lname = document.getElementById(lst).value;
   var res = confirm('Do you want to calculate?');
   if(res == true)
      calAF(Fname,Lname );
  }
 </script>
</apex:page>


Controller :

Public class passparam{
Public string firstname{get;set;}
Public string lastname{get;set;}
Public string fullname{get;set;}
 Public void calpercentage(){
  fullname = firstname +' '+lastname;
 }
}



Output :











How to call batch apex from trigger?

How to call batch apex from trigger?


A batch apex can be called from a class as well as from trigger code. But, we have to be very very carefull while calling a batch apex from trigger.

Batch apex

global class BatchApexDemo implements database.batchable<sobject>{
Public string soqlquery;
 Public void setQry(string soqlquery){
    this.soqlquery = 'Select name,status from account limit 1';
 }
 global database.querylocator start(database.batchableContext bc){
   return database.getquerylocator(soqlquery);
 }
 global void execute(database.batchablecontext bd, list<sObject> sc){
   System.debug('**In Execute Method**');
 }
 Public void finish(database.batchableContext bc){
 }
}


Trigger

trigger callbatchapex on Account (after insert) {
 List<account> accList = new List<account>();
 for(account acc : trigger.new){
     if(acc.annualrevenue < 20000)
        accList.add(acc);
 }
    if(accList.size() > 0)
      database.executebatch(new BatchApexDemo(),200);
}






Thursday, August 28, 2014

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.



Wednesday, August 27, 2014

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;
      }
    }
}





Tuesday, August 26, 2014

How to Use Custom label in apex code?

How to Use  Custom label in apex code?

Custom labels are used to store custom text values which can be accessed in apex code or visualforce pages. It is also possible to translate these custom values in different languages. A custom label can hold up to 1000 characters in it and an org can have a total of 5000 custom labels.
You can Create a custom label by navigating to set up -> create -> custom label

In the below example let us see how we can access the custom label in apex. Let's assume we have created a custom label of name category with a value "A Custom Label Value"



Visualforce page

<apex:page controller="custlabelcontroller">
   <apex:form >
     <apex:pageblock >
       Value stored in custom label is: {!customValue}
     </apex:pageblock>
   </apex:form>
</apex:page>



Controller


Public class custlabelcontroller{
Public string customValue{get;set;}
  Public custlabelcontroller(){
  customValue = Label.category;
  }
}











Monday, August 25, 2014

How to use an inline Visualforce page in Record Details Page?

How to use an inline Visualforce page in Record Details Page?

An inline visualforce page is a vf page which can be embedded within a detail page of a record. Salesforce allows doing so, in the edit page layout option. A vf page would be available for embedding in the detail page layout provided page is using standard controller of that particular object. For example, in the below example a inline vf page of standard controller 'contact' would be available for embedding in contact records only.

Visualforce Page:

<apex:page standardController="contact" extensions="InLineController">
 <apex:form >
   <apex:pageBlock title="My Inline Visualforce page">
    <b>Account Name : </b> <apex:outputField value="{!accRec.name}"/><br/>
    <b>Account Number: </b> <apex:outputField value="{!accRec.accountnumber}"/><br/>
     <b>Annual Revenue : </b>    <apex:outputField value="{!accRec.annualrevenue}"/>
   </apex:pageBlock>
 </apex:form>
</apex:page>

Controller:

public class InLineController {
 Public contact conRec{get;set;}
 Public id accRecId;
 Public account accRec{get;set;}
 public InLineController(ApexPages.StandardController controller) {    

   if(ApexPages.currentPage().getParameters().get('id') != null) {
   
     accRecId = [select id,accountid from contact where id = :ApexPages.currentPage().getParameters().get('id')].accountid;
      if(accRecId != null)
         accRec = [select id,name,accountnumber,annualrevenue from account where id =:accRecId];
         
   }
 }

}



once you complete the VF and Controller add the VF section in Contact Detail Page Layout.

save image


Output:

save image










 
| ,