Saturday, October 6, 2012

Simple Dynamic Component:

Simple Dynamic Component:
This tag acts as a placeholder for your dynamic Apex components. It has one required parameter—componentValue—which accepts the name of an Apex method that returns a dynamic component.


public class SimpleDynamicController {

    public Component.Apex.Detail getDynamicDetail() {
        Component.Apex.Detail detail = new Component.Apex.Detail();
        detail.expressions.subject = '{!acct.OwnerId}';
        detail.relatedList = false;
        detail.title = false;
        return detail;
    }

    // Just return the first Account, for example purposes only 
    
    public Account acct {
        get { return [SELECT Id, Name, OwnerId FROM Account LIMIT 1]; }
    }
}
<apex:page controller="SimpleDynamicController">
    <apex:dynamicComponent componentValue="{!dynamicDetail}" /> 
</apex:page>

Wizard:

Wizard:
Salesforce wizard is a good example to understand the view state.Please check the view state once you done.You can get UtilityJS Here

public class JobAppWizard {

    // These properties will be used to maintain state
 
    // Search results are not transient in case the user accidentally selects
    // the wrong one and wants to go back
    public List<Candidate__c> results {
    get{
    if(results == null) results = new List<Candidate__c>();
        return results;
    }
    set;
    }
 
    public ApexPages.standardController controller {get; set;}
 
    public String searchText {
    get;
    set{
    value = value.endsWith('*') ? value : value + '*';
            searchText = value;
    }
    }
 
    public Boolean showSearch {
    get{
    if (showSearch == null) showSearch = true;
    return showSearch;
    }
    set;
    }

    public Job_Application__c jobApplication { get; set; }
 
    public Candidate__c candidate {
    get{
            if (candidate == null) candidate = new Candidate__c();
            return candidate;
    }
    set;
    }
 
    public ID candidateId { get; set; }
 
    public JobAppWizard(ApexPages.StandardController stdController) {
    // constructor
    controller = stdController;
        this.jobApplication = (Job_Application__c)stdController.getRecord();
        if ((ApexPages.currentPage().getParameters().get('posId') != null)&&
            (ApexPages.currentPage().getParameters().get('posId') != '')){
        jobApplication.Position__c = ApexPages.currentPage().getParameters().get('posId');
        }
    }
     
    // The next 3 methods control navigation through
    // the wizard. Each returns a PageReference for one of the 3 pages
    // in the wizard. Note that the redirect attribute does not need to
    // be set on the PageReference because the URL does not need to change
    // when users move from page to page.
    public PageReference step1() {
        return Page.jobAppStep1;
    }
    public PageReference step2() {
    return Page.jobAppStep2;
    }
    public PageReference step3() {
    if (candidate.last_name__c == null){
    candidate.last_name__c.addError('Last Name is required');
    return null;
    } else {
    return Page.jobAppStep3;
    }
    }
 
    // this function is called by step2 & step3 pages in the action attribute,
    // in case anyone tries to go directly to them it will navigate the user back to step1
    public PageReference checkPosition(){
    if (jobApplication.Position__c == null) {
    PageReference newRef = Page.jobAppStep1;
    newRef.setRedirect(true);
    return newRef;
    } else {
    return null;
    }
    }
   
    public PageReference doSearch() {
        results = (List<Candidate__c>)[FIND :searchText IN ALL FIELDS RETURNING Candidate__c(Id, First_Name__c, Last_Name__c, Email__c, City__c, State_Province__c, Phone__c)] [0];
        return null;
    }
 
    // doing a separate query here to keep the view state down
    public PageReference SelectCandidate() {  
        candidate = [select id,first_name__c,last_name__c,phone__c,email__c,mobile__c, street_address_1__c,street_address_2__c,city__c,state_province__c,zip_postal_code__c,country__c from Candidate__c where id=:candidateId];
        return Page.jobAppStep3;
    }
 
    public PageReference NewCandidate(){
    if (!showSearch) {
    candidate = new Candidate__c();
    candidateId = null; // reset the id so we know what to do upon save
    }
    return null;
    }
       
        public PageReference save() {
        // catches need to return null; redo using ApexPages.addMessages(e) & <apex:pageMessages>
        if (candidateId == null) {
        // it's a brand spanking new candidate so we need to insert it first
        try{
        insert candidate;
        System.debug('new candidate=' + candidate);
        } catch (System.DmlException e) {
ApexPages.addMessages(e);
return null;
        }
        }
        System.debug('jobApplication=' + jobApplication);
        jobApplication.Candidate__c = candidate.id;
        try{
        insert jobApplication;
        } catch (System.DmlException e) {
ApexPages.addMessages(e);
return null;
    }
        controller = new ApexPages.standardController(jobApplication);
        return controller.view();
        }
}
and the step 1 page looks like this

<apex:page standardController="Job_Application__c" extensions="JobAppWizard" tabStyle="Job_Application__c">
  <apex:includeScript value="{!$Resource.utilityJS}" />
  <apex:sectionHeader title="Job Application" subtitle="Step 1 of 3"/>
  <apex:form >
      <apex:pageBlock id="theBlock" title="Job Application Edit" mode="edit">
          <apex:pageBlockButtons >
              <apex:commandButton action="{!step2}" value="Next"/>
              <apex:commandButton action="{!cancel}" value="Cancel" onclick="return confirmCancel()" immediate="true" style="margin-left: 2em"/>
          </apex:pageBlockButtons>
          <apex:pageBlockSection title="Information" columns="1">
              <apex:inputField value="{!JobApplication.Status__c}"/>
              <apex:inputField value="{!JobApplication.Stage__c}"/>
              <apex:inputField value="{!JobApplication.Position__c}" required="true"/>
          </apex:pageBlockSection>
      </apex:pageBlock>
  </apex:form>
</apex:page>
Step 2 page :

<apex:page standardController="Job_Application__c" extensions="JobAppWizard" tabStyle="Job_Application__c" action="{!checkPosition}">
  <apex:includeScript value="{!$Resource.utilityJS}" />
  <apex:sectionHeader title="Job Application" subtitle="Step 2 of 3"/>
  <apex:form id="theForm" >
      <apex:pageBlock id="theRadioBlock" title="Choose" mode="edit">
          <apex:pageMessages />
          <apex:pageBlockButtons location="top" >
              <apex:commandButton action="{!step1}" value="Previous"/>
              <apex:commandButton action="{!step3}" value="Next" rendered="{!NOT(ShowSearch)}"/>
              <apex:commandButton action="{!cancel}" value="Cancel" onclick="return confirmCancel()" immediate="true" style="margin-left: 2em"/>
          </apex:pageBlockButtons>
          <apex:pageBlockSection collapsible="false" title="Search or New" id="searchOrNew" columns="1">
              <apex:selectRadio value="{!ShowSearch}">
                  <apex:selectOption itemValue="true" itemLabel="Search for Existing Candidate"/>
                  <apex:selectOption itemValue="false" itemLabel="Create New Candidate" />
                  <apex:actionSupport rerender="theForm" event="onclick" action="{!NewCandidate}"/>
              </apex:selectRadio>
          </apex:pageBlockSection>
      </apex:pageBlock>
      <apex:pageBlock id="theSearchBlock" title="Specify Candidate" mode="edit" rendered="{!ShowSearch}">
          <apex:pageBlockButtons location="bottom" >
              <apex:commandButton action="{!step1}" value="Previous"/>
              <apex:commandButton action="{!step3}" value="Next" rendered="{!NOT(ShowSearch)}"/>
          </apex:pageBlockButtons>
          <apex:pageBlockSection title="Candidate Search" collapsible="false" id="candSearch" columns="1">
              <apex:outputPanel layout="searchBlock" style="padding:5px 0px;margin-bottom:5px;background-color:#D9D9D9">
                    <apex:outputLabel style="padding:0px 5px;font-size:95%;font-weight:bold;font-family: 'Verdana','Geneva',sans-serif;" value="Enter Candidate Last Name" for="searchText"/>                                      
                    <apex:inputText id="searchText" value="{!searchText}" size="50" />
                    <apex:commandButton value="Search" action="{!doSearch}" rerender="results" status="status"/>
                    <apex:actionStatus id="status" startText="requesting..."/>
              </apex:outputPanel>  
          </apex:pageBlockSection>
          <apex:pageBlockSection title="Candidate Search Results" id="results" columns="1" collapsible="false" >
              <apex:pageBlockTable value="{!results}" var="c" id="thePBTable" >  
                  <apex:column headerValue="Action">
                      <apex:commandLink action="{!SelectCandidate}" value="Select" >
                        <apex:param name="a" assignTo="{!candidateId}" value="{!c.Id}"/>
                      </apex:commandLink>
                  </apex:column>          
                  <apex:column value="{!c.First_Name__c}"/>
                  <apex:column value="{!c.Last_Name__c}"/>
                  <apex:column value="{!c.Email__c}"/>
                  <apex:column value="{!c.Phone__c}"/>
                  <apex:column value="{!c.City__c}"/>
                  <apex:column value="{!c.State_Province__c}"/>
              </apex:pageBlockTable>
         </apex:pageBlockSection>
       </apex:pageBlock>
       <apex:pageBlock id="theCandidateBlock" title="New Candidate" mode="edit" rendered="{!NOT(ShowSearch)}">
          <apex:pageBlockButtons location="bottom" >
              <apex:commandButton action="{!step1}" value="Previous"/>
              <apex:commandButton action="{!step3}" value="Next"/>
          </apex:pageBlockButtons>            
          <apex:pageBlockSection title="Candidate Information" columns="2" id="candInfo" collapsible="false">
              <apex:inputField value="{!Candidate.First_Name__c}"/>
              <apex:inputField value="{!Candidate.Phone__c}"/>
              <apex:inputField value="{!Candidate.Last_Name__c}" />
              <apex:inputField value="{!Candidate.Mobile__c}"/>
              <apex:pageBlockSectionItem >
                  <apex:outputText value=""/>
              </apex:pageBlockSectionItem>
              <apex:inputField value="{!Candidate.Email__c}" />    
          </apex:pageBlockSection>  
          <apex:pageBlockSection title="Address Info" columns="1">
              <apex:inputField value="{!Candidate.Street_Address_1__c}"/>
              <apex:inputField value="{!Candidate.Street_Address_2__c}" />
              <apex:inputField value="{!Candidate.City__c}"/>
              <apex:inputField value="{!Candidate.State_Province__c}"/>
              <apex:inputField value="{!Candidate.Zip_Postal_Code__c}"/>
          </apex:pageBlockSection>
      </apex:pageBlock>
  </apex:form>
</apex:page>
Step 3 Page:

<apex:page standardController="Job_Application__c" extensions="JobAppWizard" tabStyle="Job_Application__c" action="{!checkPosition}">
  <apex:includeScript value="{!$Resource.utilityJS}" />
  <apex:sectionHeader title="Job Application" subtitle="Step 3 of 3"/>
  <apex:form >
      <apex:pageBlock id="theBlock" title="Job Application and Candidate" mode="detail">
          <apex:pageBlockButtons >
              <apex:commandButton action="{!step2}" value="Previous"/>
              <apex:commandButton action="{!save}" value="Save"/>
              <apex:commandButton action="{!cancel}" value="Cancel" onclick="return confirmCancel()" immediate="true" style="margin-left: 2em"/>
          </apex:pageBlockButtons>
          <apex:pageMessages />
          <apex:pageBlockSection title="Job Application" columns="1" collapsible="false">
              <apex:outputField value="{!JobApplication.Status__c}"/>
              <apex:outputField value="{!JobApplication.Stage__c}"/>
              <apex:outputField value="{!JobApplication.Position__c}"/>
          </apex:pageBlockSection>                    
          <apex:pageBlockSection title="Candidate Information" columns="2" id="candInfo" collapsible="false">
              <apex:outputField value="{!Candidate.First_Name__c}"/>
              <apex:outputField value="{!Candidate.Phone__c}"/>
              <apex:outputField value="{!Candidate.Last_Name__c}" />
              <apex:outputField value="{!Candidate.Mobile__c}"/>
              <apex:pageBlockSectionItem >
                  <apex:outputText value=""/>
              </apex:pageBlockSectionItem>
              <apex:outputField value="{!Candidate.Email__c}" />    
              <apex:pageBlockSectionItem >
                  <apex:outputText value=""/>
              </apex:pageBlockSectionItem>
          </apex:pageBlockSection>  
          <apex:pageBlockSection showHeader="false" columns="1">
              <apex:outputField value="{!Candidate.Street_Address_1__c}"/>
              <apex:outputField value="{!Candidate.Street_Address_2__c}" />
              <apex:outputField value="{!Candidate.City__c}"/>
              <apex:outputField value="{!Candidate.State_Province__c}"/>
              <apex:outputField value="{!Candidate.Zip_Postal_Code__c}"/>
          </apex:pageBlockSection>  
      </apex:pageBlock>
  </apex:form>
</apex:page>






Web Forms:

Web Forms:
This example shows how to create a job application form for your sites that search dynamically from your salesforce and apply for specific position.

global class jobApplicationExCtrl {
 
 private final Candidate__c cand;
 public string resumeText {Get; Set;}
 public String myPosition_Id {Get; Set;}
 
 public jobApplicationExCtrl(ApexPages.StandardController stdController) {
        this.cand = (Candidate__c)stdController.getRecord();
    }
 
 public PageReference Save() 
 {
  System.debug('--------------------- jobApplicationExCtrl Save BEGIN');
  PageReference ret;
  
  try{
         insert cand;
         System.debug('--------------------- jobApplicationExCtrl cand Id = ' + cand.Id);
     } catch (System.DmlException e) {
         System.debug('--------------------- jobApplicationExCtrl save Dml Exception = ' + e.getMessage());
     }
    if (resumeText != null && resumeText != '')
    {
   System.debug('--------------------- jobApplicationExCtrl resumeText = ' + resumeText);
   Blob resumeBlob = Blob.valueOf(resumeText);
   Attachment att = new Attachment(parentId = cand.Id, name='Resume.txt', body = resumeBlob);
   try{
    insert att;
    System.debug('--------------------- jobApplicationExCtrl att Id = ' + att.Id);
   } catch (System.DmlException e) {
    System.debug('--------------------- jobApplicationExCtrl save Dml Exception = ' + e.getMessage());
   }
    }
     PageReference candPage = new ApexPages.StandardController(cand).view();
  candPage.setRedirect(true);
  ret = candPage;
  
  System.debug('--------------------- jobApplicationExCtrl Save END');
  return ret;
 }
 
 public PageReference Apply() 
 {
  System.debug('--------------------- jobApplicationExCtrl Apply BEGIN');
  PageReference ret;
  if (myPosition_Id != null && myPosition_Id != '')
  {
   System.debug('--------------------- jobApplicationExCtrl myPosition_Id = ' + myPosition_Id);
   try{
          insert cand;
          System.debug('--------------------- jobApplicationExCtrl cand Id = ' + cand.Id);
      } catch (System.DmlException e) {
          System.debug('--------------------- jobApplicationExCtrl Apply Dml Exception = ' + e.getMessage());
      }
     if (resumeText != null && resumeText != '')
     {
    System.debug('--------------------- jobApplicationExCtrl resumeText = ' + resumeText);
    Blob resumeBlob = Blob.valueOf(resumeText);
    Attachment att = new Attachment(parentId = cand.Id, name='Resume.txt', body = resumeBlob);
    try{
     insert att;
     System.debug('--------------------- jobApplicationExCtrl att Id = ' + att.Id);
    } catch (System.DmlException e) {
     System.debug('--------------------- jobApplicationExCtrl Apply Dml Exception = ' + e.getMessage());
    }
     }

     Job_Application__c app = new Job_Application__c();
     app.Position__c = myPosition_Id;
     app.Candidate__c = cand.Id;
     try{
       insert app;
   } catch (System.DmlException e) {
      System.debug('--------------------- jobApplicationExCtrl Apply Dml Exception = ' + e.getMessage());
   }
   System.debug('--------------------- jobApplicationExCtrl Apply app.Id = ' + app.Id);
   
      PageReference candPage = new ApexPages.StandardController(cand).view();
   candPage.setRedirect(true);
   ret = candPage;
  }
  else
  {
   System.debug('--------------------- jobApplicationExCtrl No Position Selected');
   ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.FATAL,'Please search for a position.');
   ApexPages.addMessage(myMsg);
   ret = null;
  }
  System.debug('--------------------- jobApplicationExCtrl Apply END');
  return ret;
 }
 
 @RemoteAction global static Position__c[] findPositions(String Name) 
    {
        System.debug('--------------------- jobApplicationExCtrl findPositions BEGIN');
        String queryName = '%'+ String.escapeSingleQuotes(Name)+'%';
        Position__c[] p = [Select p.Type__c, p.Name, p.Id, p.Department__c From Position__c p where p.Name LIKE :queryName Limit 10];
        System.debug('--------------------- jobApplicationExCtrl findPositions END'); 
        return p;
    }
}
and the page looks like this 
<apex:page standardController="Candidate__c" extensions="jobApplicationExCtrl" sidebar="false" showHeader="false" standardStylesheets="false">

<apex:stylesheet value="{!URLFOR($Resource.UC_SiteBranding, 'style.css')}"/>

<script type="text/javascript">
    var positions;   
    
    function positionsSearch(name) {
        jobApplicationExCtrl.findPositions(name,handlePositions);
        return false;
    }
     
    function handlePositions(result, event) {
        if(event.type == 'exception') {
            alert(event.message);
        } else {
            positions = result;
            showPositions();
        }
    }
     
    function showPositions() {
        var newList = "";
        for(var i = 0; i < positions.length; i++) {
            newList += "<input type=\"radio\" onclick=\"javascript: setPositionId('" +positions[i].Id+"');\" id=\"position\" name=\"position\" value=\"" +positions[i].Id+"\" /> "+positions[i].Name+ " <br />"
        }
        document.getElementById('positionsList').innerHTML = newList;
    }
    
    function setPositionId (posStr)
    {
     var posText = getApexElementByID("input","hiddenPositionId");
     posText.value = posStr;
    }
    
  function getApexElementByID(tagname, eid) {
     var tags = document.getElementsByTagName(tagname);
     var regex = new RegExp(":" + eid + "$");
     for (var i=0; i < tags.length; i++) {
   if (tags[i].getAttribute("id") != null) {
    var pos = tags[i].getAttribute("id").search(regex);
    if (pos != -1) return tags[i];
   }
  }
  return null;
    }  
</script>

<apex:outputPanel id="header" layout="block">
    <apex:outputPanel id="logo" layout="block">
        <h1><apex:outputLink value="#">Universal Containers</apex:outputLink></h1>
        <h2><apex:outputLink value="http://www.salesforce.com/">A Great Place to work</apex:outputLink></h2>
    </apex:outputPanel>
    <apex:outputPanel id="menu" layout="block">
        <ul>
            <li><apex:outputLink value="#">Home</apex:outputLink></li>
            <li><apex:outputLink value="#">About Us</apex:outputLink></li>
            <li><apex:outputLink value="#">Benefits</apex:outputLink></li>
            <li><apex:outputLink value="#">Positions</apex:outputLink></li>
            <li><apex:outputLink value="#">Apply</apex:outputLink></li>
        </ul>
    </apex:outputPanel>
</apex:outputPanel>
<apex:outputPanel id="splash" layout="block"></apex:outputPanel>
<apex:form id="jobapp">
<apex:outputPanel id="page" layout="block">
    <apex:outputPanel id="content">
        <h2>Apply</h2>
        <apex:pageMessages />
        <fieldset>
            <legend>1) Search for a Position</legend>
            <apex:outputPanel >
                <!-- TODO (EXERCISE 3-1) Add Text and Button input HTML tags. -->
  <!-- The Text input should have an id of searchTerm -->
  <!-- The Button input should have a value of search  -->
  <!-- onclick call the positionsSearch javaScript function with the value of searchTerm -->
  <input type="text" id="searchTerm" />
                <input type="button" onclick="return positionsSearch(document.getElementById('searchTerm').value);" value="Search" />
                <div id="positionsList"></div>
                <div style="float: right;">
                </div>
            </apex:outputPanel>
            <apex:inputHidden value="{!myPosition_Id}" id="hiddenPositionId"/>
        </fieldset>
        <fieldset>
            <legend>Contact Information</legend>
            <apex:outputPanel layout="block">
                <apex:outputLabel value="First Name:" for="fName"/>
                <apex:inputText id="fName" value="{!Candidate__c.First_Name__c}" />                 
            </apex:outputPanel>
            <apex:outputPanel layout="block">
                <apex:outputLabel value="Last Name:" for="lName"/> 
                <apex:inputText id="lName" value="{!Candidate__c.Last_Name__c}" />
            </apex:outputPanel>
            <apex:outputPanel layout="block">
                <apex:outputLabel value="Email:" for="email"/> 
                <apex:inputText id="email" value="{!Candidate__c.Email__c}" /> 
            </apex:outputPanel>
            <apex:outputPanel layout="block">
                <apex:outputLabel value="Phone:" for="phone"/> 
                <apex:inputText id="phone" value="{!Candidate__c.Phone__c}" /> 
            </apex:outputPanel>
        </fieldset>
        <fieldset> 
            <legend>3) Cut &amp; Paste Resume</legend>
            <!-- TODO (EXERCISE 3-1) add an Apex Input Text Area tag that is tied to the action method-->
            <!-- Override the style to set the width to 473px and height to 250px-->
   <apex:inputTextarea id="resume" value="{!resumeText}" style="width: 473px; height: 250px;"/>
        </fieldset>
        <!-- TODO (EXERCISE 3-1) change the commandButton to call the Apply method in the extension controller-->
        <apex:commandButton value="Apply" action="{!Apply}"/>
    </apex:outputPanel>
    <apex:outputPanel id="sidebar">
        <h2>Universal Containers is Hiring!</h2>
        <p>Universal Containers (UC) is is a global company with more than 4,750 employees in offices around the world.</p>
        <p>We are an Equal Employment Opportunity and Affirmative Action Employer.</p>
        <p><strong>Accessibility</strong> – If you require accessibility assistance applying for open positions please contact the <a href="mailto:applications@universalcontainers.com">Recruiting Department</a>.</p>
    </apex:outputPanel>
</apex:outputPanel>
<apex:outputPanel id="footer" layout="block">
    <p id="legal">Copyright &copy; 2007 BreakFast. All Rights Reserved. Designed by <apex:outputLink value="http://www.freecsstemplates.org/">Free CSS Templates</apex:outputLink>.</p>
    <p id="links"><apex:outputLink value="#">Privacy Policy</apex:outputLink> | <apex:outputLink value="#">Terms of Use</apex:outputLink></p>
</apex:outputPanel>
</apex:form>
</apex:page> 
           

Best Dynamic Search:

Best Dynamic Search:
Salesforce dynamic searching is fast to find a customer info.For example
public with sharing class ContactSearchController {

  // the soql without the order and limit
  private String soql {get;set;}
  // the collection of contacts to display
  public List<Contact> contacts {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 = 'lastName'; } 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 ContactSearchController() {
    soql = 'select firstname, lastname, account.name, interested_technologies__c from contact where account.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 {
      contacts = 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 firstName = Apexpages.currentPage().getParameters().get('firstname');
    String lastName = Apexpages.currentPage().getParameters().get('lastname');
    String accountName = Apexpages.currentPage().getParameters().get('accountName');
    String technology = Apexpages.currentPage().getParameters().get('technology');

    soql = 'select firstname, lastname, account.name, interested_technologies__c from contact where account.name != null';
    if (!firstName.equals(''))
      soql += ' and firstname LIKE \''+String.escapeSingleQuotes(firstName)+'%\'';
    if (!lastName.equals(''))
      soql += ' and lastname LIKE \''+String.escapeSingleQuotes(lastName)+'%\'';
    if (!accountName.equals(''))
      soql += ' and account.name LIKE \''+String.escapeSingleQuotes(accountName)+'%\'';  
    if (!technology.equals(''))
      soql += ' and interested_technologies__c includes (\''+technology+'\')';

    // run the query again
    runQuery();

    return null;
  }

  // use apex describe to build the picklist values
  public List<String> technologies {
    get {
      if (technologies == null) {

        technologies = new List<String>();
        Schema.DescribeFieldResult field = Contact.interested_technologies__c.getDescribe();

        for (Schema.PicklistEntry f : field.getPicklistValues())
          technologies.add(f.getLabel());

      }
      return technologies;          
    }
    set;
  }

}
and the page looks like this

<apex:page controller="ContactSearchController" sidebar="false">
 
  <apex:form >
  <apex:pageMessages id="errors" />
 
  <apex:pageBlock title="Find Me A Customer!" mode="edit">
 
  <table width="100%" border="0">
  <tr>  
    <td width="200" valign="top">
 
      <apex:pageBlock title="Parameters" mode="edit" id="criteria">
 
      <script type="text/javascript">
      function doSearch() {
        searchServer(
          document.getElementById("firstName").value,
          document.getElementById("lastName").value,
          document.getElementById("accountName").value,
          document.getElementById("technology").options[document.getElementById("technology").selectedIndex].value
          );
      }
      </script> 
 
      <apex:actionFunction name="searchServer" action="{!runSearch}" rerender="results,debug,errors">
          <apex:param name="firstName" value="" />
          <apex:param name="lastName" value="" />
          <apex:param name="accountName" value="" />
          <apex:param name="technology" value="" />
      </apex:actionFunction>
 
      <table cellpadding="2" cellspacing="2">
      <tr>
        <td style="font-weight:bold;">First Name<br/>
        <input type="text" id="firstName" onkeyup="doSearch();"/>
        </td>
      </tr>
      <tr>
        <td style="font-weight:bold;">Last Name<br/>
        <input type="text" id="lastName" onkeyup="doSearch();"/>
        </td>
      </tr>
      <tr>
        <td style="font-weight:bold;">Account<br/>
        <input type="text" id="accountName" onkeyup="doSearch();"/>
        </td>
      </tr>
      <tr>
        <td style="font-weight:bold;">Interested Technologies<br/>
          <select id="technology" onchange="doSearch();">
            <option value=""></option>
            <apex:repeat value="{!technologies}" var="tech">
              <option value="{!tech}">{!tech}</option>
            </apex:repeat>
          </select>
        </td>
      </tr>
      </table>
 
      </apex:pageBlock>
 
    </td>
    <td valign="top">
 
    <apex:pageBlock mode="edit" id="results">
 
        <apex:pageBlockTable value="{!contacts}" var="contact">
 
            <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="First Name" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="firstName" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
                <apex:outputField value="{!contact.firstName}"/>
            </apex:column>
 
            <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="Last Name" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="lastName" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
                <apex:outputField value="{!contact.lastName}"/>
            </apex:column>
 
            <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="Account" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="account.name" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
                <apex:outputField value="{!contact.account.name}"/>
            </apex:column>
 
            <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="Technologies" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="interested_technologies__c" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
                <apex:outputField value="{!contact.Interested_Technologies__c}"/>
            </apex:column>
 
        </apex:pageBlockTable>
 
    </apex:pageBlock>
 
    </td>
  </tr>
  </table>
 
  <apex:pageBlock title="Debug - SOQL" id="debug">
      <apex:outputText value="{!debugSoql}" />           
  </apex:pageBlock>    
 
  </apex:pageBlock>
 
  </apex:form>
 
</apex:page>
                                  

Play Attachment songs in Detail Page:

Play Attachment songs in Detail Page:
Visualforce page gives the ability to play the songs with in the page instead of download and play.
Here is the example for lead ,You can download the player Here
public without sharing class PlayAudio {
    
    public List<Attachment> listAttachment {get;set;}
    public Lead lead {get;set;}
    
    //constructor
    public PlayAudio(ApexPages.StandardController controller) {
        
        //get the controller instance
        lead = (Lead)controller.getRecord();
        
        //initialize the attachments list
        listAttachment = new List<Attachment>();
        
        //get all the lead related attachments
        listAttachment = [Select Id, ContentType, Name from Attachment where ParentId = :lead.Id];
        
        //get all the related tasks attachments
        List<Task> listTask = [Select WhatId from Task where WhoId =: lead.Id ];
        listAttachment.addAll([Select Id, ContentType, Name from Attachment where ParentId IN :listTask]);
        
        //get all the related events attachments
        List<Event> listEvent = [Select WhatId from Event where WhoId =: lead.Id ];
        listAttachment.addAll([Select Id, ContentType, Name from Attachment where ParentId IN :listEvent]);
        
    }
    
    @isTest
    private static void testPlayAudio()
        {
            //create a lead record
            Lead lead = new Lead(LastName='test', Company='test');
            insert lead;
            
            //start test from here 
            Test.startTest();
            
            PlayAudio controller = new PlayAudio(new ApexPages.StandardController(lead));
            
            System.assert(lead != null);
            //stop test here
            Test.stopTest();
        }

}
and the page looks like this

<apex:page standardController="Lead" id="pg" extensions="PlayAudio" sidebar="false">
<apex:includeScript value="{!URLFOR($Resource.AudioPlayer, 'audio-player/audio-player.js')}"/>
<script type="text/javascript">  
  AudioPlayer.setup("{!URLFOR($Resource.AudioPlayer, 'audio-player/player.swf')}", {  
   width: 290  
  });  
</script> 

<script type="text/javascript">  
 function playAudio(trackObj)
  {
   AudioPlayer.embed("audioplayer_1", {soundFile: trackObj});
  }  
</script>
<apex:form id="frm">
 <apex:pageBlock id="pb">
  <apex:variable value="{!0}" var="count" />
  <apex:pageBlockTable value="{!listAttachment}" var="item" id="pbt">
   <apex:column headerValue="Name">
    {!item.Name}
   </apex:column>
   <apex:column headerValue="ContentType">
    {!item.ContentType}
   </apex:column>
   <apex:column id="colPlayer" rendered="{!CONTAINS(item.ContentType, 'audio')}">
    <p id="{!count}.audioplayer"></p>
    <script type="text/javascript">
     AudioPlayer.embed("{!count}.audioplayer", {soundFile: 'https://c.na9.content.force.com/servlet/servlet.FileDownload?file={!item.Id}'});
    </script>
    <apex:variable value="{!count+1}" var="count" />
   </apex:column>
  </apex:pageBlockTable>
 </apex:pageBlock>
</apex:form>
</apex:page>
             

Friday, October 5, 2012

Mass Moving Reports From One Folder to Other Using Eclipse:

Mass Moving Reports From One Folder to Other
 Using Eclipse:
In the Eclipse IDE
Create a new projectInclude ‘reports’ or more specifically the report
 folders you are concerned withLet Eclipse refresh the project with the 
reports metadataIn Eclipse, navigate to the reports folder you just
download and then select the Report Folder you want the reports
 you want to move from, right click and select Properties

Take Note of the Location. This is the path where the metadata files
 are locatedOpen a windows explorer window and navigate to that path

Highlight all the Reports you want to move and right click 
CutStill in window explorer navigate back to the list of report 
folders and expand the one you want to move the reports to
 and right click and PasteNow back in the IDE highlight the
 folder titled Reports and right click and Refresh and then right
 click again and Force.com - Save to Server

Execute Anonymous II:

Execute Anonymous II:
As continuous to previous execute anonymous post Execute Anonymous 1 ,we can test this example with an apex class.First create your class and observe the log using developer console by execute anonymous statements below

Dog myDogFido = new Dog();
myDogFido.play();
String myDogFidoStatus = myDogFido.getStatus();
System.debug('Fido is currently ' + myDogFidoStatus);



public class Dog {     // Declare a private String attribute called status     private String status;          // Declare a method to make the dog sit     public void sit(){         // Set the status to 'Sitting'         status = 'Sitting';     }          // Declare a method to make the dog play     public void play(){         // Set the status to 'Playing'         status = 'Playing';     }          // Declare a method to make the dog wag its tail     public void wagTail(){         // Set the status to 'Wagging Tail'         status = 'Wagging Tail';     }     // Declare a method that returns the status of the dog     public String getStatus(){         // Return the status attribute         return status;     } }

Facet Usage:

Facet Usage:
facet consists of content in an area of a Visualforce component that provides contextual information about the data that is presented in the component. For example,<apex:dataTable> supports facets for the header, footer, and caption of a table, while <apex:column> only supports facets for the header and footer of the column. The<apex:facet> component allows you to override the default facet on a Visualforce component with your own content. Facets only allow a single child within the start and close tags.

<apex:page standardController="Account">
    <apex:pageBlock>
        <apex:dataTable value="{!account}" var="a">
            <apex:facet name="caption"><h1>This is 
              {!account.name}</h1></apex:facet>
            <apex:facet name="footer"><p>Information 
              Accurate as of {!NOW()}</p></apex:facet>
            <apex:column>
                <apex:facet name="header">Name</apex:facet>
                <apex:outputText value="{!a.name}"/>
            </apex:column>
            
            <apex:column>
                <apex:facet  name="header">Owner</apex:facet>
                <apex:outputText value="{!a.owner.name}"/>
            </apex:column>
        </apex:dataTable>
    </apex:pageBlock>        
</apex:page>

Accessing Component IDs:

Accessing Component IDs:

To refer to a Visualforce component in JavaScript or another Web-enabled language you must specify a value for the id attribute for that component. A DOM id is constructed from a combination of the id attribute of the component, and the id attributes of all components that contain the element. This ensures every element has a unique DOM id.
The $Component global variable simplifies references and reduces some of the dependency on the overall page structure. For example, to access a data table with id="tableID"contained in a page block with id="blockID", use the following expression: $Component.blockID.tableID.
You don't need to specify an ID for a component you want to access if it is an ancestor or sibling to the $Component variable in the Visualforce component hierarchy. The system dynamically assigns IDs to the outer components and automatically determines the hierarchy for you.
<apex:page>
  <apex:form id="theForm">
    <apex:pageBlock id="thePageBlock">
      <apex:pageBlockSection id="theSection">
        <apex:pageBlockSectionItem id="theSectionItem">All the
        alerts refer to this component</apex:pageBlockSectionItem>
        <!-- Works because this outputPanel has a direct parent 
             with a "theSectionItem" child --> 
    
        <apex:outputPanel onclick="alert('
 {!$Component.theSectionItem}');">
            First click here
        </apex:outputPanel>
      </apex:pageBlockSection>
      <apex:pageBlockButtons id="theButtons" location="bottom">
        <!-- Works because this outputPanel has a grandparent ("theSection")
             with a "theSectionItem" child --> 
    
        <apex:outputPanel onclick="alert('
 {!$Component.theSection.theSectionItem}');">
            Second click here<br />
        </apex:outputPanel>
        <!-- Works because this outputPanel has a distant parent 
             with a "theForm" child. --> 
    
        <apex:outputPanel onclick="alert('
 {!$Component.theForm.thePageBlock.theSection.theSectionItem}');">
            Third click here<br />
        </apex:outputPanel>
      </apex:pageBlockButtons>
    </apex:pageBlock>
    <!-- $Component will reference the common parent of this usage 
         and the target, which is "theForm" --> 
    
    <apex:outputPanel onclick="alert('
 {!$Component.thePageBlock.theSection.theSectionItem}');">
        Fourth click here</apex:outputPanel>
  </apex:form>
</apex:page>