Showing posts with label apex. Show all posts
Showing posts with label apex. Show all posts

Sunday, April 3, 2016

How to access ListView in Apex | Using StandardSetController for Pagination

How to access ListView in Apex | Using StandardSetController for Pagination

Example :

In this post i am using Account object listviews.



Use ListView in Visualforce with Paging and Navigation

Apex class :

/**
*  Description : Controller Class to show How to utilize existing List View in Apex with Pagination Support
*/

public with sharing class ListViewDemo {

  private String baseQuery = 'Select ID, Name FROM Account ORDER BY NAME ASC';
  public String AccFilterId {get; set;}
  private Integer pageSize = 10;

  public ListViewDemo(){}

  public ApexPages.StandardSetController AccSetController {
        get{
            if(AccSetController == null){
                AccSetController = new ApexPages.StandardSetController(Database.getQueryLocator(baseQuery));
                AccSetController.setPageSize(pageSize);

                // We have to set FilterId after Pagesize, else it will not work
                if(AccFilterId != null)
                {
                  AccSetController.setFilterId(AccFilterId);
                }
            }
            return AccSetController;
        }set;
    }

  public ListViewDemo(ApexPages.StandardSetController c) {   }

    //Navigate to first Page
    public void firstPage()
    {
      AccSetController.first();
    }

    //Navigate to last Page
    public void lastPage()
    {
      AccSetController.last();
    }

    //Navigate to Next page
    public void next()
    {
      if(AccSetController.getHasNext())
      {
        AccSetController.next();
      }
    }

    //Navigate to Prev Page
    public void prev()
    {
      if(AccSetController.getHasPrevious())
      {
        AccSetController.previous();
      }
    }

    public List<Account> getAccounts()
    {
      return (List<Account>)AccSetController.getRecords();
    }

    //Get all available list view for Account
    public SelectOption[] getAccountExistingViews(){
        return AccSetController.getListViewOptions();
    }

    /**
    * Reset List View
    */
    public PageReference resetFilter()
    {
      AccSetController = null;
        AccSetController.setPageNumber(1);
        return null;
    }

}


Visualforce Page:

<apex:page controller="ListViewDemo">
Available List Views for Account :
  <apex:form id="pageForm">
       <apex:selectList value="{!AccFilterId}" size="1" id="filterMenu">
       <apex:selectOptions value="{!AccountExistingViews}"></apex:selectOptions>
       <apex:actionSupport event="onchange"  action="{!resetFilter}" rerender="AccntTable" status="ajaxStatus"/>
       </apex:selectList>

       <apex:actionStatus id="ajaxStatus" startText="Loading..."  stopText=""/>

     <apex:pageBlock title="Accounts">
        <apex:pageBlockButtons >
                <apex:commandButton action="{!firstPage}" value="|<<" reRender="AccntTable"  status="ajaxStatus" />
                <apex:commandButton action="{!prev}" value="<" reRender="AccntTable"  status="ajaxStatus" />
                <apex:commandButton action="{!next}" value=">" reRender="AccntTable"  status="ajaxStatus" />
                <apex:commandButton action="{!lastPage}" value=">>|" reRender="AccntTable"  status="ajaxStatus" />
            </apex:pageBlockButtons>

         <apex:pageBlockTable value="{!Accounts}" var="item" id="AccntTable">
             <apex:column value="{!item.name}"/>
         </apex:pageBlockTable>
     </apex:pageBlock>
   </apex:form>
</apex:page>


Test Class :

@isTest
public class ListViewDemoTest
{    
    
    @testSetup 
    static void createAccount() {
        // Create common test accounts
        List<Account> testAccts = new List<Account>();
        for(Integer i=0;i<20;i++) {
            testAccts.add(new Account(Name = 'TestAcct'+i));
        }
        insert testAccts;        
    }
    
     public static testMethod void getListView(){
        //Lets Assume we are writing Controller extension to use on List View of Account
        List <Account> acctList = [SELECT ID FROM Account];
  
         //Check Account created count by setup()
         System.assertEquals(20,acctList.size());
         
        //Start Test Context, It will reset all Governor limits
        Test.startTest();

        //Inform Test Class to set current page as your Page where Extension is used
        Test.setCurrentPage(Page.ListViewDemo);

        //Instantiate object of "ApexPages.StandardSetController" by passing array of records
        ApexPages.StandardSetController stdSetController = new ApexPages.StandardSetController(acctList);

        //Now, create Object of your Controller extension by passing object of standardSetController
        ListViewDemo ext = new ListViewDemo(stdSetController);
        
        SelectOption[] selOptions = ext.getAccountExistingViews();
         
        //We should not assert count of list View as no control over creation of list view
        //but in my Dev org, I know count is 6 
        System.assertEquals(6,selOptions.size());
         
         ext.firstPage();
         List<Account> accFirsttPage = ext.getAccounts();
         System.assertEquals( 10, accFirsttPage.size() );
         
         ext.next();
         ext.prev();
         ext.resetFilter();
         ext.lastPage();
          
        //Finish Test
        Test.stopTest();
     } 
}

That's it !!!!



Set Up Test Data for an Entire Test Class & @TestSetup method in Apex.

Set Up Test Data for an Entire Test Class & @TestSetup method in Apex.


In old school way, if we wanted to create records for test methods, helper or utility classes were favourite option for developers.

However this approach has few disadvantages

  • Multiple Test classes could depend on these utility methods
  • It creates tight coupling between classes
  • Deployment could be slow if unnecessary test record being created for test methods
  • If class to create test record is not marked with @isTest then it will count against allowed apex code in instance
  • Test classes needs to explicitly call method to create test records

Test Setup (@testSetup) Methods in Test Class

Apex has introduced new method in Test class known as “Test Setup”. Following are some highlights and considerations of using Test Setup method in Test classes :

  • It needs to be marked with @testSetup annotation in Test class
  • One Test class can have multiple @testSetup methods
  • These test setup methods are implicitly invoked before each test methods
  • These methods can be used to create test records specific to Test class
  • It helps to keep Test classes isolated and independent of helper or utility classes
  • It can’t be used if Test class is marked with @isTest(SeeAllData=true)
  • If error occurs in setup method then entire test class fails
  • If non-test method is called from setup method then no code coverage is calculated for non-test method
  • If multiple set up method is written in Test class then sequence of execution of those methods are not guaranteed

Below class shows sample code of Test method in action. It creates 200 lead records in test setup method (@testSetup) and checks whether 200 records are created or not in test method.

@iSTest
public class LeadProcessorTest {   

    //below test setup method will be invoked
    // implicitly before every test methods 
    @testsetup
    static void createLead(){
        List<Lead> lstLead = new List<Lead>();        
        for(Integer i = 0 ; i<200 ; i++) {
            lstLead.add(new Lead(lastName = 'testLName'+i , Company = 'Salesforce'));
        } 
        insert lstLead ;
    }
    
   //Check whether records created in test method
   //is accessible or not
    public static testMethod void test(){
        System.assertEquals(200, [SELECT COUNT() FROM Lead Where company = 'Salesforce']);
    }
}


Salesforce Documentation for Using Test Setup Methods

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_testing_testsetup_using.htm




Saturday, April 2, 2016

What is Visualforce Remote Objects.?

What is Visualforce Remote Objects.?


One of the exciting feature of Spring14 release is introduction of “Visualforce Remote Objects”. You can say its actually replacement of JavaScript Remoting.

Why do we need “Visualforce Remote Objects” when we already have “JavaScript Remoting” ?
Well, here are few advantages of “Visualforce Remote Objects” :
    1.    No need to write Controllers, Everything can be done in Visualforce only.
   2.    As @RemoteAction annotated methods needs to be static so you had to take special precaution as it didn’t supported Viewstate. This hurdle is completely removed now.
   3.    No need to write Test Class now, as no Controller is involved.
   4.    Not counted against API call

How to start with this ?
At time of writing this article, This feature is under Pilot release. So, you have to contact Salesforce support to enable it in your Organization.
Visualforce code Sample :

<!-- This Demo will assume Querying Account Object -->
<apex:remoteObjects>
<apex:remoteObjectModel name="Account" jsShorthand="getActs" fields="Name,Id">
 <apex:remoteObjectField name="ClientType__c" jsShorthand="cType">
</apex:remoteObjectModel>
</apex:remoteObjects>



you can see in above code, few new Visualforce tags are introduced like “remoteObjectModel” and “remoteObjectField“.
jsShorthand attribute defines shortcut that can be used inside your JavaScript code. Now, we don’t have to write annoying object or field name ending with “__c” or namespace name. This will keep our code tidy.
Javascript code Sample :

//Create new Remote Object Reference
var src = new SObjectModel.getActs();
 
//Use Remote Object to query 5 records
src.retrieve({
                        limit : 10,
                        where : {
                             cType :{
                                          eq : 'Banking'
                                                                            }
                                        }
                               } ,
                          function(err,records){
                               if(err == null)
                                  {
                                      //Process returned "records" to display in Visualforce code.
                                  }
} );


In above code, we are calling retrieve() method of Javascript object SObjectModel. Once you get records, you can process it in your javascript. Other than retrieve() , you can perform all CRUD operations on object.
You can see below articles also on same topic.


Let test this features quickly on our own, by designing a visualforce page.  Here I have designed a page that pulls up ten accounts from Salesforce solely by using JavaScript Remote Objects (see picture below)

Just copy-paste the code in your org to test this by yourself. I am querying Accounts (standard object) and using bootstrap CDN (check what is bootstrap and cdn go to bootstrap site to style the page. At the moment, I wrote retrieve() operation that pulls ten records, soon ill update the code will perform all sort of DML operation mentioned in the documentation.


Test on Salesforce 1 :  this works like charm on Salesforce 1







<apex:page sidebar="false" showHeader="false" standardStylesheets="false">
   <apex:includeScript value="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.2.min.js"/>
   <link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet" media="screen"/>
   <style>
      .wrapper
      {
      text-align : center;
      }
   </style>
   <!-- lets query Salesforce Contact using remoting objects -->
   <!--Lets add up Amount field on Contact objects here using shorthand amt-->
   <apex:remoteObjects >
      <!--Name the field you like to query-->
      <apex:remoteObjectModel name="Account" jsShorthand="acc" fields="Id,Name,BillingState, Phone"/>
   </apex:remoteObjects>
   <!-- now address you field with shorthand -->
   <script>
      function clearList()
      {
          if(!$('#cList').empty())
          {
              //if non-empty then clear list before every call
              $('#cList').empty();
          }
      }
     
      var DML = function(){
          //clear old list beforehand
          clearList();
          //Instantiate a reference
          var data = new SObjectModel.acc();
          //process the data received in return
          data.retrieve({ limit: 10 } ,function(err, records){
              //if failure
              if(err) alert(err.message);
              else {
                  populate(records);      
              }
          });
         
          //Method to Pouplate Records
          function populate(records)
          {
              var ul = document.getElementById("cList");
              records.forEach(function(record) {
                  // Build the text for a warehouse line item
                  var toAdd = record.get("Name");
                  // Add the line item to the warehouses list
                  var rule = document.createElement("br");
                  var li = document.createElement("li");
                  li.appendChild(document.createTextNode(toAdd));
                  ul.appendChild(li);
                  ul.appendChild(rule);
              });
          }
      }
     
   </script>
   <div class="jumbotron">
      <h1>Retrieve Contacts via Remote Objects</h1>
      <p>via Remote Objects</p>
      <a href="#" class="list-group-item active">
         <h4 class="list-group-item-heading">What is Remote Object?</h4>
         <p class="list-group-item-text">Visualforce Remote Objects are proxy objects that allow basic DML operations on sObjects directly from JavaScript. Remote Objects take some of the complexity out of JavaScript remoting, by reducing the need for @RemoteAction methods in an Apex controller or extension. Like JavaScript remoting, <br/> Remote Objects calls don’t count towards API request limits.</p>
      </a>
      <br/>
      <div class="wrapper">
         <p> <button  class="btn btn-success btn-lg" onclick="DML()"> <span class="glyphicon glyphicon-star"></span>Pull
            Accounts</button>
         </p>
      </div>
   </div>
   <a href="#" class="list-group-item active">
   <span class="glyphicon glyphicon-list"></span> Accounts:
   </a>
   <div class="wrapper">
      <ul class="list-inline" id="cList">
      </ul>
   </div>
</apex:page>




Friday, October 16, 2015

Converting Multi-Select picklist to Multi-Select checkboxes in VF page.

Converting Multi-Select pick-list to Multi-Select check-boxes in VF page.



In this post i am providing an example of converting Multi Select Pick-list to  convert Multi Select Chyeckboxes in VF page.

For this i created a Multi-Select Pick-list field on opportunity page with some values.



Using custom controller extension in VF page.

Controller Class:

public class MultiCheckBoxExtn {
    public opportunity opp{get;set;}
    public List<SelectOption> leadSourceCheckbox {get;set;}
    
    public MultiCheckBoxExtn(ApexPages.StandardController controller) {
        opp = (opportunity)controller.getRecord();
    }
    
    public void saveOpp(){
    system.debug('opp.Srinivas__Multi_Select_Pick_List__c==>'+opp.Srinivas__Multi_Select_Pick_List__c);
     upsert opp;
    }
    
    
  
 //get the multi-select pick list values
    public List<SelectOption> MPOptions {
     get {
       List<SelectOption> options = new List<SelectOption>();
       for( Schema.PicklistEntry f : opportunity.Srinivas__Multi_Select_Pick_List__c.getDescribe().getPicklistValues()) {
         options.add(new SelectOption(f.getValue(), f.getLabel()));
        } 
       return options;
     }  
     set;
    }
    
    
    //get and set the multi-select pick list as checkboxes
       public String[] MPItems { 
     get {
        String[] selected = new List<String>();
        List<SelectOption> sos = this.MPOptions;
        for(SelectOption s : sos) {
        if (this.opp.Srinivas__Multi_Select_Pick_List__c !=null && this.opp.Srinivas__Multi_Select_Pick_List__c.contains(s.getValue()))
           selected.add(s.getValue());
        }
        return selected;
     }public set {
        String selectedCheckBox = '';
        for(String s : value) {
         if (selectedCheckBox == '') 
           selectedCheckBox += s;
         else selectedCheckBox += ';' + s;
        }
        opp.Srinivas__Multi_Select_Pick_List__c = selectedCheckBox;
     }
   } 
 }



VF page : 

<apex:page standardController="Opportunity" extensions="MultiCheckBoxExtn" tabStyle="Opportunity" id="thepg">
<apex:pagemessages ></apex:pagemessages>
    <apex:form id="theFm" >
     <apex:pageBlock id="thePB" >
        <apex:pageblockSection title="Opporutnity Details" id="thePbs1" collapsible="false">
         <apex:inputfield value="{!opp.name}" id="name1"/>
         <apex:inputField value="{!opp.closeDate}"/>
          <apex:inputField value="{!opp.stageName}"/>
        </apex:pageblockSection>
     

         <apex:pageBlockSection title="Multiselect Picklist to Checkbox" columns="2" collapsible="false" id="thePbs2">
         <apex:outputLabel value="{!$ObjectType.opportunity.Fields.Multi_Select_Pick_List__c.InlineHelpText}" />
           <apex:selectcheckboxes layout="pageDirection"  value="{!MPItems}" label="" id="checkbox1">                   
             <apex:selectoptions value="{!MPOptions}"  > </apex:selectoptions>       
            </apex:selectcheckboxes>
         </apex:pageBlockSection>
        
        <apex:pageblockButtons >
         <apex:commandButton value="Save" action="{!saveOpp}"/>
        
        </apex:pageblockButtons>
        </apex:pageBlock>
    
    </apex:form>
</apex:page>


























Once the user clicks  on the save button it will set the check box values into multi select pick-list 



If you edit the record it will show the multiselect picklist like this.





That's it.

Thanks... 



Wednesday, September 30, 2015

What is Web Service and What are different types of webservices?

What is Web Service and What are different types of web services?


A Web Service is can be defined by following ways:
  • Is a client server application or application component for communication.
  • Method of communication between two devices over network.
  • Is a software system for interoperable machine to machine communication.
  • Is a collection of standards or protocols for exchanging information between two devices or application.

Let's understand it by the figure given below:



As you can see in the figure, java, .net or PHP applications can communicate with other applications through web service over the network. For example, java application can interact with Java, .Net and PHP applications. So web service is a language independent way of communication.

Types of Web Services
There are mainly two types of web services.
  1. SOAP web services.
  2. RESTful web services.



SOAP Web Services

SOAP stands for Simple Object Access Protocol. It is a XML-based protocol for accessing web services. SOAP is a W3C recommendation for communication between two applications.


SOAP is XML based protocol. It is platform independent and language independent. By using SOAP, you will be able to interact with other programming language applications.


Advantages of Soap Web Services

WS Security: SOAP defines its own security known as WS Security.

Language and Platform independent: SOAP web services can be written in any programming language and executed in any platform.

Disadvantages of Soap Web Services
Slow: SOAP uses XML format that must be parsed to be read. It defines many standards that must be followed while developing the SOAP applications. So it is slow and consumes more bandwidth and resource.

WSDL dependent: SOAP uses WSDL and doesn't have any other mechanism to discover the service.

RESTful Web Services

REST stands for Representational State Transfer. REST is an architectural style not a protocol.

Advantages of RESTful Web Services

Fast: RESTful Web Services are fast because there is no strict specification like SOAP. It consumes less bandwidth and resource.

Language and Platform independent: RESTful web services can be written in any programming language and executed in any platform.

Can use SOAP: RESTful web services can use SOAP web services as the implementation.

Permits different data format: RESTful web service permits different data format such as Plain Text, HTML, XML and JSON.


SOAP vs REST Web Services

S.No
SOAP
REST
1
SOAP is a protocol.
REST is an architectural style.
2
SOAP stands for Simple Object Access Protocol.
REST stands for REpresentational State Transfer.
3
SOAP can't use REST because it is a protocol.
REST can use SOAP web services because it is a concept and can use any protocol like HTTP, SOAP.
4
SOAP uses services interfaces to expose the business logic.
REST uses URI to expose business logic.
5
SOAP defines standards to be strictly followed.
REST does not define too much standards like SOAP.
6
SOAP defines standards to be strictly followed.
REST does not define too much standards like SOAP.
7
SOAP requires more bandwidth and resource than REST.
REST requires less bandwidth and resource than SOAP.
8
SOAP defines its own security.
RESTful web services inherits security measures from the underlying transport.
9
SOAP permits XML data format only.
REST permits different data format such as Plain text, HTML, XML, JSON etc.
10
SOAP is less preferred than REST.
REST more preferred than SOAP.



Thanks for reading.....


 
| ,