function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Chris BettiniChris Bettini 

Need help writing a test class for a visualforce custom controller? It's just a search page...

public with sharing class PositionHistSearchController {

    public String positionhist { get; set; }
  
  // the soql without the order and limit
  private String soql {get;set;}
  // the collection of contacts to display
  public List<PositionHistory__c> positionhistlist {get;set;}
  
  // the current sort direction. defaults to asc
  public String sortDir {
    get  { if (sortDir == null) {  sortDir = 'asc'; } return sortDir;  }
    set;
  }
  
  // the current field to sort by. defaults to last name
  public String sortField {
    get  { if (sortField == null) {sortField = 'Name'; } return sortField;  }
    set;
  }
  
  // format the soql for display on the visualforce page
  public String debugSoql {
    get { return soql + ' order by ' + sortField + ' ' + sortDir + ' limit 20'; }
    set;
  }

  // init the controller and display some sample data when the page loads
  public PositionHistSearchController() {
    soql = 'select Name, Investor__r.Name, product__r.name, Balance_Date__c, Balance__c from PositionHistory__c where Name != null';
    runQuery();
  }
  
  // toggles the sorting of query from asc<-->desc
  public void toggleSort() {
    // simply toggle the direction
    sortDir = sortDir.equals('asc') ? 'desc' : 'asc';
    // run the query again
    runQuery();
  }
  
  // runs the actual query
  public void runQuery() {
        
    try {
      positionhistlist = Database.query(soql + ' order by ' + sortField + ' ' + sortDir + ' limit 20');
    } catch (Exception e) {
      ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Ooops!'));
    }

  }
  
  // runs the search with parameters passed via Javascript
  public PageReference runSearch() {
    
    String Name = Apexpages.currentPage().getParameters().get('name');
    String Investor = Apexpages.currentPage().getParameters().get('investor');
    String effectiveDate = Apexpages.currentPage().getParameters().get('asofDate');
    String product = Apexpages.currentPage().getParameters().get('product');
        
    soql = 'select Name, Investor__r.Name, product__r.name, Balance_Date__c, Balance__c from PositionHistory__c where Name != null';
    if (!Name.equals(''))
      soql += ' and (name LIKE \'%'+ Name +'%\' or investor__r.Name LIKE \'%'+ Name +'%\')';
    if (!effectiveDate.equals(''))
      soql += ' and asofDate = ' + effectiveDate ;
    if (!product.equals(''))
      soql += ' and product__r.Name LIKE \'%'+ product +'%\'' ;
 

    // run the query again
    runQuery();

    return null;
  }