<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Jeff Douglas - Technology, Coding and Bears... OH MY! &#187; Visualforce</title>
	<atom:link href="http://blog.jeffdouglas.com/category/technology/visualforce-technology/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.jeffdouglas.com</link>
	<description>Get your head out of your #@! and into the clouds!</description>
	<lastBuildDate>Thu, 02 Feb 2012 11:57:20 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=</generator>
		<item>
		<title>Roll Your Own Salesforce &#8220;Lookup&#8221; Popup Window</title>
		<link>http://blog.jeffdouglas.com/2011/08/12/roll-your-own-salesforce-lookup-popup-window/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=roll-your-own-salesforce-lookup-popup-window</link>
		<comments>http://blog.jeffdouglas.com/2011/08/12/roll-your-own-salesforce-lookup-popup-window/#comments</comments>
		<pubDate>Fri, 12 Aug 2011 12:18:48 +0000</pubDate>
		<dc:creator>Jeff Douglas</dc:creator>
				<category><![CDATA[Apex]]></category>
		<category><![CDATA[Salesforce]]></category>
		<category><![CDATA[Visualforce]]></category>

		<guid isPermaLink="false">http://blog.jeffdouglas.com/?p=4087</guid>
		<description><![CDATA[Let&#8217;s talk about the standard salesforce.com &#8220;lookup&#8221; popup window for a few minutes. You know what I&#8217;m talking about.. this button right here It&#8217;s a handy little button that pops up whenever you need to search for related records. It does a pretty good job but it has some serious drawbacks: It&#8217;s virtually impossible to [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fblog.jeffdouglas.com%2F2011%2F08%2F12%2Froll-your-own-salesforce-lookup-popup-window%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fblog.jeffdouglas.com%2F2011%2F08%2F12%2Froll-your-own-salesforce-lookup-popup-window%2F&amp;source=jeffdonthemic&amp;style=normal&amp;service=bit.ly&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>Let&#8217;s talk about the standard salesforce.com &#8220;lookup&#8221; popup window for a few minutes. You know what I&#8217;m talking about.. this button right here</p>
<p><img title="custom-lookup-button.png" src="http://blog.jeffdouglas.com/wp-content/uploads/2011/08/custom-lookup-button.png" border="0" alt="Custom lookup button" width="292" height="116" /></p>
<p>It&#8217;s a handy little button that pops up whenever you need to search for related records. It does a pretty good job but it has some serious drawbacks:</p>
<ol>
<li>It&#8217;s virtually impossible to modify your search criteria. What if you want your users to do some crazy search based upon custom logic or search a field that is not typically available? Sorry&#8230; you are out of luck. Not possible.</li>
<li>It&#8217;s terrible for creating new records. Let&#8217;s say that a user searches for a specific related record and it (absolutely) doesn&#8217;t exist. To create the new record they need to close the lookup window, navigate to the tab to create the new related record, create the new record, then go back to the original record they were either editing or creating, pop up the lookup window again and find their newly created record. Wow! That&#8217;s a lot of work. </li>
<li>&#8220;Quick Create&#8221; is evil! You can enable the &#8220;Quick Create&#8221; option for an entire org but don&#8217;t do it! It displays, by default, on the tab home pages for leads, accounts, contacts, forecasts, and opportunities! The major problems are that you can only create new records for these 5 objects (what about the other ones!?), you can&#8217;t customize the fields on the page and validation rules don&#8217;t fire (can you say, &#8220;bad data&#8221;). </li>
</ol>
<p><img title="custom-lookup.png" src="http://blog.jeffdouglas.com/wp-content/uploads/2011/08/custom-lookup.png" border="0" alt="Quick Create is Bad" width="500" height="466" /></p>
<h3>Here&#8217;s the Solution!</h3>
<p>I have some good news and some bad news. For standard page layouts I can&#8217;t help you. Go vote for <a href="http://success.salesforce.com/ideaView?id=08730000000IYRFAA4">this idea</a> and <a href="http://success.salesforce.com/ideaview?id=08730000000IYB1AAO">this idea</a>. However, for Visualforce page I have a solution to all of these problems with code!</p>
<p><img title="custom-lookup1.png" src="http://blog.jeffdouglas.com/wp-content/uploads/2011/08/custom-lookup1.png" border="0" alt="Custom Lookup" width="500" height="250" /></p>
<p>Here&#8217;s how it looks. It may be easier to watch it full screen at <a href="http://www.youtube.com/watch?v=CGeFt6hdgRY">YouTube</a>.</p>
<p><span class="youtube">
<object width="560" height="340">
<param name="movie" value="http://www.youtube.com/v/CGeFt6hdgRY?color1=d6d6d6&amp;color2=f0f0f0&amp;border=0&amp;fs=1&amp;hl=en&amp;loop=0&amp;showinfo=0&amp;iv_load_policy=3&amp;showsearch=0&amp;rel=1&amp;hd=1" />
<param name="allowFullScreen" value="true" />
<embed wmode="opaque" src="http://www.youtube.com/v/CGeFt6hdgRY?color1=d6d6d6&amp;color2=f0f0f0&amp;border=0&amp;fs=1&amp;hl=en&amp;loop=0&amp;showinfo=0&amp;iv_load_policy=3&amp;showsearch=0&amp;rel=1&amp;hd=1" type="application/x-shockwave-flash" allowfullscreen="true" width="560" height="340"></embed>
<param name="wmode" value="opaque" />
</object>
</span><p><a href="http://www.youtube.com/watch?v=CGeFt6hdgRY&fmt=18">www.youtube.com/watch?v=CGeFt6hdgRY</a></p></p>
<p>Here&#8217;s the code you need to accomplish this. You need two Visualforce pages (the record you are editing and the popup window) and two Apex controllers (a simple one for the record you are editing and the controller for the search and new record popup).</p>
<p><strong>MyCustomLookupController</strong> - <a href="https://github.com/jeffdonthemic/Blog-Sample-Code/blob/master/salesforce/src/classes/MyCustomLookupController.cls">code at github</a></p>
<p>Here&#8217;s the Apex controller for the record you are either creating or editing. This is an extremely simple controller that just creates a new contact so you can use the lookup for the related account field.</p>
<p>
<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
</pre></td><td class="code"><pre class="java" style="font-family:monospace;">public with sharing class MyCustomLookupController {
&nbsp;
  public Contact contact {get;set;}
&nbsp;
  public MyCustomLookupController() {
    contact = new Contact();
  }
&nbsp;
}</pre></td></tr></table></div>

</p>
<p><strong>MyCustomLookup</strong> - <a href="https://github.com/jeffdonthemic/Blog-Sample-Code/blob/master/salesforce/src/pages/MyCustomLookup.page">code at github</a></p>
<p>This is the &#8220;magical&#8221; Visualforce page that uses jQuery to intercept the popup and instead of showing the standard salesforce.com pop, shows our custom popup instead. The user experience is seamless.</p>
<p>
<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
</pre></td><td class="code"><pre class="java" style="font-family:monospace;">&lt;apex:page controller=&quot;MyCustomLookupController&quot; id=&quot;Page&quot; tabstyle=&quot;Contact&quot;&gt;
&nbsp;
  &lt;script type=&quot;text/javascript&quot;&gt; 
  function openLookup(baseURL, width, modified, searchParam){
    var originalbaseURL = baseURL;
    var originalwidth = width;
    var originalmodified = modified;
    var originalsearchParam = searchParam;
&nbsp;
    var lookupType = baseURL.substr(baseURL.length-3, 3);
    if (modified == '1') baseURL = baseURL + searchParam;
&nbsp;
    var isCustomLookup = false;
&nbsp;
    // Following &quot;001&quot; is the lookup type for Account object so change this as per your standard or custom object
    if(lookupType == &quot;001&quot;){
&nbsp;
      var urlArr = baseURL.split(&quot;&amp;&quot;);
      var txtId = '';
      if(urlArr.length &gt; 2) {
        urlArr = urlArr[1].split('=');
        txtId = urlArr[1];
      }
&nbsp;
      // Following is the url of Custom Lookup page. You need to change that accordingly
      baseURL = &quot;/apex/CustomAccountLookup?txt=&quot; + txtId;
&nbsp;
      // Following is the id of apex:form control &quot;myForm&quot;. You need to change that accordingly
      baseURL = baseURL + &quot;&amp;frm=&quot; + escapeUTF(&quot;{!$Component.myForm}&quot;);
      if (modified == '1') {
        baseURL = baseURL + &quot;&amp;lksearch=&quot; + searchParam;
      }
&nbsp;
      // Following is the ID of inputField that is the lookup to be customized as custom lookup
      if(txtId.indexOf('Account') &gt; -1 ){
        isCustomLookup = true;
      }
    }
&nbsp;
&nbsp;
    if(isCustomLookup == true){
      openPopup(baseURL, &quot;lookup&quot;, 350, 480, &quot;width=&quot;+width+&quot;,height=480,toolbar=no,status=no,directories=no,menubar=no,resizable=yes,scrollable=no&quot;, true);
    }
    else {
      if (modified == '1') originalbaseURL = originalbaseURL + originalsearchParam;
      openPopup(originalbaseURL, &quot;lookup&quot;, 350, 480, &quot;width=&quot;+originalwidth+&quot;,height=480,toolbar=no,status=no,directories=no,menubar=no,resizable=yes,scrollable=no&quot;, true);
    } 
  }
&lt;/script&gt;
&nbsp;
&lt;apex:sectionHeader title=&quot;Demo&quot;  subtitle=&quot;Custom Lookup&quot; /&gt;
&nbsp;
  &lt;apex:form id=&quot;myForm&quot;&gt;  
    &lt;apex:PageBlock id=&quot;PageBlock&quot;&gt;    
      &lt;apex:pageBlockSection columns=&quot;1&quot; title=&quot;Custom Lookup&quot;&gt;
        &lt;apex:inputField id=&quot;Account&quot; value=&quot;{!contact.AccountId}&quot;  /&gt;
      &lt;/apex:pageBlockSection&gt;
    &lt;/apex:PageBlock&gt;
  &lt;/apex:form&gt;
&nbsp;
&lt;/apex:page&gt;</pre></td></tr></table></div>

</p>
<p><strong>CustomAccountLookupController</strong> - <a href="https://github.com/jeffdonthemic/Blog-Sample-Code/blob/master/salesforce/src/classes/CustomAccountLookupController.cls">code at github</a></p>
<p>The Apex controller for the custom popup window is yours to customize. I know what you are thinking, &#8220;Free at last! Free at last! Thank God Almighty, we are free at last!&#8221; This class has all of your custom search functionality plus the method to create a new account. This is demo code so the search is very limited and does not prevent <a href="http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_dynamic_soql.htm">soql injections</a>.</p>
<p>
<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
</pre></td><td class="code"><pre class="java" style="font-family:monospace;">public with sharing class CustomAccountLookupController {
&nbsp;
  public Account account {get;set;} // new account to create
  public List&lt;Account&gt; results{get;set;} // search results
  public string searchString{get;set;} // search keyword
&nbsp;
  public CustomAccountLookupController() {
    account = new Account();
    // get the current search string
    searchString = System.currentPageReference().getParameters().get('lksrch');
    runSearch();  
  }
&nbsp;
  // performs the keyword search
  public PageReference search() {
    runSearch();
    return null;
  }
&nbsp;
  // prepare the query and issue the search command
  private void runSearch() {
    // TODO prepare query string for complex serarches &amp; prevent injections
    results = performSearch(searchString);               
  } 
&nbsp;
  // run the search and return the records found. 
  private List&lt;Account&gt; performSearch(string searchString) {
&nbsp;
    String soql = 'select id, name from account';
    if(searchString != '' &amp;&amp; searchString != null)
      soql = soql +  ' where name LIKE \'%' + searchString +'%\'';
    soql = soql + ' limit 25';
    System.debug(soql);
    return database.query(soql); 
&nbsp;
  }
&nbsp;
  // save the new account record
  public PageReference saveAccount() {
    insert account;
    // reset the account
    account = new Account();
    return null;
  }
&nbsp;
  // used by the visualforce page to send the link to the right dom element
  public string getFormTag() {
    return System.currentPageReference().getParameters().get('frm');
  }
&nbsp;
  // used by the visualforce page to send the link to the right dom element for the text box
  public string getTextBox() {
    return System.currentPageReference().getParameters().get('txt');
  }
&nbsp;
}</pre></td></tr></table></div>

</p>
<p><strong>CustomAccountLookup</strong> - <a href="https://github.com/jeffdonthemic/Blog-Sample-Code/blob/master/salesforce/src/pages/CustomAccountLookup.page">code at github</a></p>
<p>Any finally the Visualforce page for the popup itself. It contains a tabbed interface easily allowing a user to search for records and create new ones. Make sure you look at the code for the second tab for creating a new record. I have better things to do than change the fields on the input form every time a new field is created or something is made required. The solution is to use <a href="http://www.salesforce.com/us/developer/docs/pages/Content/pages_dynamic_vf_field_sets.htm">field sets</a>! So when an administrator makes a change, they can simply update the field set and the popup reflects the change accordingly. Life is good.</p>
<p>
<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
</pre></td><td class="code"><pre class="java" style="font-family:monospace;">&lt;apex:page controller=&quot;CustomAccountLookupController&quot;
  title=&quot;Search&quot; 
  showHeader=&quot;false&quot; 
  sideBar=&quot;false&quot; 
  tabStyle=&quot;Account&quot; 
  id=&quot;pg&quot;&gt;
&nbsp;
  &lt;apex:form &gt;
  &lt;apex:outputPanel id=&quot;page&quot; layout=&quot;block&quot; style=&quot;margin:5px;padding:10px;padding-top:2px;&quot;&gt;
    &lt;apex:tabPanel switchType=&quot;client&quot; selectedTab=&quot;name1&quot; id=&quot;tabbedPanel&quot;&gt;
&nbsp;
      &lt;!-- SEARCH TAB --&gt;
      &lt;apex:tab label=&quot;Search&quot; name=&quot;tab1&quot; id=&quot;tabOne&quot;&gt;
&nbsp;
        &lt;apex:actionRegion &gt;  
          &lt;apex:outputPanel id=&quot;top&quot; layout=&quot;block&quot; style=&quot;margin:5px;padding:10px;padding-top:2px;&quot;&gt;
            &lt;apex:outputLabel value=&quot;Search&quot; style=&quot;font-weight:Bold;padding-right:10px;&quot; for=&quot;txtSearch&quot;/&gt;
            &lt;apex:inputText id=&quot;txtSearch&quot; value=&quot;{!searchString}&quot; /&gt;
              &lt;span style=&quot;padding-left:5px&quot;&gt;&lt;apex:commandButton id=&quot;btnGo&quot; value=&quot;Go&quot; action=&quot;{!Search}&quot; rerender=&quot;searchResults&quot;&gt;&lt;/apex:commandButton&gt;&lt;/span&gt;
          &lt;/apex:outputPanel&gt;
&nbsp;
          &lt;apex:outputPanel id=&quot;pnlSearchResults&quot; style=&quot;margin:10px;height:350px;overflow-Y:auto;&quot; layout=&quot;block&quot;&gt;
            &lt;apex:pageBlock id=&quot;searchResults&quot;&gt; 
              &lt;apex:pageBlockTable value=&quot;{!results}&quot; var=&quot;a&quot; id=&quot;tblResults&quot;&gt;
                &lt;apex:column &gt;
                  &lt;apex:facet name=&quot;header&quot;&gt;
                    &lt;apex:outputPanel &gt;Name&lt;/apex:outputPanel&gt;
                  &lt;/apex:facet&gt;
                   &lt;apex:outputLink value=&quot;javascript:top.window.opener.lookupPick2('{!FormTag}','{!TextBox}_lkid','{!TextBox}','{!a.Id}','{!a.Name}', false)&quot; rendered=&quot;{!NOT(ISNULL(a.Id))}&quot;&gt;{!a.Name}&lt;/apex:outputLink&gt;     
                &lt;/apex:column&gt;
              &lt;/apex:pageBlockTable&gt;
            &lt;/apex:pageBlock&gt;
          &lt;/apex:outputPanel&gt;
        &lt;/apex:actionRegion&gt;
&nbsp;
      &lt;/apex:tab&gt;
&nbsp;
      &lt;!-- NEW ACCOUNT TAB --&gt;
      &lt;apex:tab label=&quot;New Account&quot; name=&quot;tab2&quot; id=&quot;tabTwo&quot;&gt;
&nbsp;
        &lt;apex:pageBlock id=&quot;newAccount&quot; title=&quot;New Account&quot; &gt;
&nbsp;
          &lt;apex:pageBlockButtons &gt;
            &lt;apex:commandButton action=&quot;{!saveAccount}&quot; value=&quot;Save&quot;/&gt;
          &lt;/apex:pageBlockButtons&gt;
          &lt;apex:pageMessages /&gt;
&nbsp;
          &lt;apex:pageBlockSection columns=&quot;2&quot;&gt;
            &lt;apex:repeat value=&quot;{!$ObjectType.Account.FieldSets.CustomAccountLookup}&quot; var=&quot;f&quot;&gt;
              &lt;apex:inputField value=&quot;{!Account[f]}&quot;/&gt;
            &lt;/apex:repeat&gt;
          &lt;/apex:pageBlockSection&gt; 
        &lt;/apex:pageBlock&gt;
&nbsp;
      &lt;/apex:tab&gt;
    &lt;/apex:tabPanel&gt;
  &lt;/apex:outputPanel&gt;
  &lt;/apex:form&gt;
&lt;/apex:page&gt;</pre></td></tr></table></div>
</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jeffdouglas.com/2011/08/12/roll-your-own-salesforce-lookup-popup-window/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>Dynamically Group &amp; Display Query Results</title>
		<link>http://blog.jeffdouglas.com/2011/03/02/dynamically-group-display-query-results/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=dynamically-group-display-query-results</link>
		<comments>http://blog.jeffdouglas.com/2011/03/02/dynamically-group-display-query-results/#comments</comments>
		<pubDate>Wed, 02 Mar 2011 10:55:14 +0000</pubDate>
		<dc:creator>Jeff Douglas</dc:creator>
				<category><![CDATA[Apex]]></category>
		<category><![CDATA[Code Sample]]></category>
		<category><![CDATA[Salesforce]]></category>
		<category><![CDATA[Visualforce]]></category>

		<guid isPermaLink="false">http://blog.jeffdouglas.com/?p=3737</guid>
		<description><![CDATA[I was working on a Visualforce page that displays the results of a query in separate PageBlock sections based upon a value in the query results. I ran into a small issue which took about an hour or so to solve, so I thought it might make descent blog fodder. The requirement for the page [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fblog.jeffdouglas.com%2F2011%2F03%2F02%2Fdynamically-group-display-query-results%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fblog.jeffdouglas.com%2F2011%2F03%2F02%2Fdynamically-group-display-query-results%2F&amp;source=jeffdonthemic&amp;style=normal&amp;service=bit.ly&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>I was working on a Visualforce page that displays the results of a query in separate PageBlock sections based upon a value in the query results. I ran into a small issue which took about an hour or so to solve, so I thought it might make descent blog fodder. </p>
<p>The requirement for the page was to query for records and then display them grouped in sections in a Visualforce page based upon whatever values (in this case BillingState) are returned in the results. If additional states were added, then the Visualforce page should be able to add those new sections without changes to the code. Here&#8217;s a screenshot of the sample solution that I came up with but you can also<a href="http://jeffdouglas-developer-edition.na5.force.com/examples/DisplaySections" target="_blank"> run this sample on my Developer Site</a>:</p>
<p><a href="http://blog.jeffdouglas.com/wp-content/uploads/2011/03/group-by-value.png" rel="lightbox[3737]"><img src="http://blog.jeffdouglas.com/wp-content/uploads/2011/03/group-by-value-300x283.png" alt="" title="group-by-value" width="300" height="283" class="alignnone size-medium wp-image-3738" /></a></p>
<p>Here&#8217;s the code for the Visualforce page. I&#8217;ve made it as bare as possible but you can see that it iterates over the array of states to display the pageBlock sections and then displays the record if the state matches the current blockSection&#8217;s state.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
</pre></td><td class="code"><pre class="java" style="font-family:monospace;">&lt;apex:page controller=&quot;DisplaySectionsController&quot; action=&quot;{!load}&quot; sidebar=&quot;false&quot;&gt;
  &lt;apex:sectionHeader title=&quot;My Sample Display Page&quot; subtitle=&quot;Group by States&quot; 
    description=&quot;This page shows how you can dynamically group results by field value.&quot;/&gt;
&nbsp;
  &lt;apex:repeat value=&quot;{!states}&quot; var=&quot;state&quot;&gt;
&nbsp;
    &lt;apex:pageBlock title=&quot;{!state}&quot;&gt;
&nbsp;
      &lt;apex:repeat value=&quot;{!accounts}&quot; var=&quot;account&quot;&gt; 
&nbsp;
        &lt;apex:outputPanel rendered=&quot;{!IF(state=account.BillingState,true,false)}&quot;&gt;
        {!account.Name} - {!account.BillingState}&lt;br/&gt;
        &lt;/apex:outputPanel&gt;
&nbsp;
      &lt;/apex:repeat&gt;
&nbsp;
    &lt;/apex:pageBlock&gt;
&nbsp;
  &lt;/apex:repeat&gt;
&nbsp;
&lt;/apex:page&gt;</pre></td></tr></table></div>

<p>The Controller exposes two collections to the Visualforce page: the list of Accounts and the array of States.  Here&#8217;s the issue that I ran into. Since I wanted to have a collection of unique state names, I originally added each state to a Set and simply returned the Set to the Visualforce page (instead of the array) to display the pageBlock sections. However, returning the Set gave me a compile error at line 11 in the Visualforce page:</p>
<blockquote><p>Save error: Incorrect parameter for operator &#8216;=&#8217;. Expected Text, received Object</p></blockquote>
<p>The problem is that even though the Set is a collection of Strings, it is actually an object underneath the covers and throws a comparison error. Therefore you have to return the states as an array of strings for the code to compile and run properly.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
</pre></td><td class="code"><pre class="java" style="font-family:monospace;">public with sharing class DisplaySectionsController {
&nbsp;
  public List&lt;Account&gt; accounts {get;set;}  
  public String[] states {get;set;}
&nbsp;
  public void load() {
&nbsp;
    // for demo purposes limit the states  
    accounts = [Select ID, Name, BillingState From Account 
      Where BillingState IN ('CA','NY','FL')];
&nbsp;
    // dynamically create set of unique states from query
    Set&lt;String&gt; stateSet = new Set&lt;String&gt;();
    for (Account a : accounts)
      stateSet.add(a.BillingState);
&nbsp;
    // convert the set into a string array  
    states = new String[stateSet.size()];
    Integer i = 0;
    for (String state : stateSet) { 
      states[i] = state;
      i++;
    }
&nbsp;
  }
&nbsp;
}</pre></td></tr></table></div>

]]></content:encoded>
			<wfw:commentRss>http://blog.jeffdouglas.com/2011/03/02/dynamically-group-display-query-results/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Neat Salesforce URLFOR Trick</title>
		<link>http://blog.jeffdouglas.com/2010/12/28/neat-salesforce-urlfor-trick/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=neat-salesforce-urlfor-trick</link>
		<comments>http://blog.jeffdouglas.com/2010/12/28/neat-salesforce-urlfor-trick/#comments</comments>
		<pubDate>Tue, 28 Dec 2010 21:39:27 +0000</pubDate>
		<dc:creator>Jeff Douglas</dc:creator>
				<category><![CDATA[Salesforce]]></category>
		<category><![CDATA[Visualforce]]></category>

		<guid isPermaLink="false">http://blog.jeffdouglas.com/?p=3392</guid>
		<description><![CDATA[I was working on an app the other day and had written a custom screen allowing the user to add/edit multiple records on the same page. So in the process I wrote a Visualforce page that Overrides the standard New and Edit functions and redirects the user to this new screen. Here&#8217;s my code that [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fblog.jeffdouglas.com%2F2010%2F12%2F28%2Fneat-salesforce-urlfor-trick%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fblog.jeffdouglas.com%2F2010%2F12%2F28%2Fneat-salesforce-urlfor-trick%2F&amp;source=jeffdonthemic&amp;style=normal&amp;service=bit.ly&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>I was working on an app the other day and had written a custom screen allowing the user to add/edit multiple records on the same page. So in the process I wrote a Visualforce page that Overrides the standard New and Edit functions and redirects the user to this new screen. Here&#8217;s my code that I thought should have worked perfectly.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="java" style="font-family:monospace;">&lt;apex:page standardController=”MyCustomObject__c”
  action=”{!URLFOR($Page.AddEditMultipleRecords,null,
  [id=MyCustomObject__c.SomeRelatedObject__c])}”/&gt;</pre></td></tr></table></div>

<p>The code above worked great for the New function but I was receiving the following error for the Edit function:</p>
<blockquote><p>SObject row was retrieved via SOQL without querying the requested field: MyCustomObject__c.SomeRelatedObject__c</p></blockquote>
<p>This is actually a <a href="http://forums.sforce.com/t5/Visualforce-Development/error-referencing-field-using-standard-controller-extension/m-p/83237">well-known &#8220;problem&#8221;</a> when using a standard controller. The standard controller automatically constructs your SOQL query for you based on the fields that are referenced in your page. So simply including the field on the page, fixes the error.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="java" style="font-family:monospace;">&lt;apex:page standardController=”MyCustomObject__c”
  action=”{!URLFOR($Page.AddEditMultipleRecords,null,
  [id=MyCustomObject__c.SomeRelatedObject__c])}”&gt;
  {!MyCustomObject__c.SomeRelatedObject__c}
&lt;/apex:page&gt;</pre></td></tr></table></div>

]]></content:encoded>
			<wfw:commentRss>http://blog.jeffdouglas.com/2010/12/28/neat-salesforce-urlfor-trick/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Force.com Programming Best Practices</title>
		<link>http://blog.jeffdouglas.com/2010/10/21/force-com-programming-best-practices/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=force-com-programming-best-practices</link>
		<comments>http://blog.jeffdouglas.com/2010/10/21/force-com-programming-best-practices/#comments</comments>
		<pubDate>Thu, 21 Oct 2010 11:56:18 +0000</pubDate>
		<dc:creator>Jeff Douglas</dc:creator>
				<category><![CDATA[Apex]]></category>
		<category><![CDATA[Salesforce]]></category>
		<category><![CDATA[Salesforce Handbook]]></category>
		<category><![CDATA[Visualforce]]></category>

		<guid isPermaLink="false">http://blog.jeffdouglas.com/?p=3301</guid>
		<description><![CDATA[  ﻿Wes and I are adding a few more topics to our Salesforce Handbook before we put it to bed and I thought a great topic would be programming best practices. I&#8217;ve never seen a &#8220;complete&#8221; list of best practices so I thought I would put something together based upon my experiences. I know I&#8217;ve [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fblog.jeffdouglas.com%2F2010%2F10%2F21%2Fforce-com-programming-best-practices%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fblog.jeffdouglas.com%2F2010%2F10%2F21%2Fforce-com-programming-best-practices%2F&amp;source=jeffdonthemic&amp;style=normal&amp;service=bit.ly&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p> </p>
<p>﻿Wes and I are adding a few more topics to our <a href="http://salesforcehandbook.wordpress.com/">Salesforce Handbook</a> before we put it to bed and I thought a great topic would be programming best practices. I&#8217;ve never seen a &#8220;complete&#8221; list of best practices so I thought I would put something together based upon my experiences. I know I&#8217;ve left some out, so if you have any to add, please chime in and we may include them in the book.</p>
<p><strong>Apex</strong></p>
<ul>
<li>Since Apex is case insensitive you can write it however you&#8217;d like. However, to increase readability, follow Java capitalization standards and use two spaces instead of tabs for indentation.</li>
<li>Use Asychronous Apex (@future annotation) for logic that does not need to be executed synchronous. </li>
<li>Asychronous Apex should be &#8220;bulkified&#8221;.</li>
<li>Apex code must provide proper exception handling.</li>
<li>Prevent SOQL and SOSL injection attacks by using static queries, binding variables or the escapeSingleQuotes method.</li>
<li>When querying large data sets, use a <a href="http://www.salesforce.com/us/developer/docs/apexcode/Content/langCon_apex_SOQL_VLSQ.htm">SOQL &#8220;for&#8221; loop</a> </li>
<li>Use SOSL over SOQL where possible &#8211; it&#8217;s much faster.</li>
<li>Use Apex Limits Methods to avoid hitting governor exceptions.</li>
<li>No SOQL or SOSL queries inside loops</li>
<li>No DML statements inside loops</li>
<li>No Async (@future) methods inside loops</li>
<li>Do not use hardcoded IDs</li>
</ul>
<p> </p>
<p><strong>Triggers</strong></p>
<ul>
<li>There should only be one trigger for each object.</li>
<li>Avoid complex logic in triggers. To simplify testing and resuse, triggers should delegate to Apex classes which contain the actual execution logic. See Mike Leach&#8217;s <a href="http://www.embracingthecloud.com/2010/07/08/ASimpleTriggerTemplateForSalesforce.aspx">excellent trigger template</a> for more info.</li>
<li>Bulkify any &#8220;helper&#8221; classes and/or methods.</li>
<li>Trigers should be &#8220;bulkified&#8221; and be able to process up to 200 records for each call.</li>
<li>Execute DML statements using collections instead of individual records per DML statement.</li>
<li>Use Collections in SOQL &#8220;WHERE&#8221; clauses to retrieve all records back in single query</li>
<li>Use a consistent naming convention including the object name (e.g., AccountTrigger)</li>
</ul>
<p> </p>
<p><strong>Visualforce</strong></p>
<ul>
<li>Do not hardcode picklists in Visualforce pages; include them in the controller instead.</li>
<li>Javascript and CSS should be included as Static Resources allowing the browser to cache them.</li>
<li>Reference CSS at the top and JavaScript a the bottom of Visualforce pages as this provides for faster page loads.</li>
<li>Mark controller variables as &#8220;transient&#8221; if they are not needed between server calls. This will make your page load faster as it reduces the size of the View State. </li>
<li>Use &lt;apex:repeat&gt; to iterate over large collections.</li>
<li>Use the cache attribute with the &lt;apex:page&gt; component to take advantage CDN caching when appropriate</li>
</ul>
<p> </p>
<p><strong>Unit Testing</strong></p>
<ul>
<li>Use a consistent naming convention including &#8220;Test&#8221; and the name of the class being tested (e.g., Test_AccountTrigger)</li>
<li>Test classes should use the @isTest annotation</li>
<li>Test methods should craete all data needed for the method and not rely on data currently in the Org. </li>
<li>Use System.assert liberally to prove that code behaves as expected.</li>
<li>Test each branch of conditional logic</li>
<li>Write test methods that both pass and fail for certain conditions and test for boundary conditions.</li>
<li>Test triggers to process 200 records &#8211; make sure your code is &#8220;bulkified&#8221; for 200 records and doesn&#8217;t throw the dreaded &#8220;Too many SOQL queries: 21&#8243; exception.</li>
<li>When testing for governor limits, use Test.startTest and Test.stopTest and the Limit class instead of hard-coding governor limits.</li>
<li>Use System.runAs() to execute code as a specific user to test for sharing rules (but not CRUD or FLS permissions)</li>
<li>Execute tests with the Force.com IDE and not the salesforce.com UI. We&#8217;ve seen misleading code coverage results when running from the salesforce.com UI.</li>
<li>Run the <a href="http://security.force.com/sourcescanner">Force.com Security Source Scanner</a> to test your Org for a number of security and code quality issues (e.g., Cross Site Scripting, Access Control Issues, Frame Spoofing)</li>
</ul>
<p> </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jeffdouglas.com/2010/10/21/force-com-programming-best-practices/feed/</wfw:commentRss>
		<slash:comments>25</slash:comments>
		</item>
		<item>
		<title>Why is this so DOM Hard?</title>
		<link>http://blog.jeffdouglas.com/2010/08/11/why-is-this-so-dom-hard/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=why-is-this-so-dom-hard</link>
		<comments>http://blog.jeffdouglas.com/2010/08/11/why-is-this-so-dom-hard/#comments</comments>
		<pubDate>Wed, 11 Aug 2010 12:27:01 +0000</pubDate>
		<dc:creator>Jeff Douglas</dc:creator>
				<category><![CDATA[Salesforce]]></category>
		<category><![CDATA[Visualforce]]></category>

		<guid isPermaLink="false">http://blog.jeffdouglas.com/?p=3052</guid>
		<description><![CDATA[Let me start out right away by saying I am not a DOM or CSS master. I&#8217;ve typically had employees or co-workers to perform these functions for my so I&#8217;ve (unfortunately) let me skills wane. However, I&#8217;m not totally clueless. I was trying to build the following Visualforce page a couple of days ago and [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fblog.jeffdouglas.com%2F2010%2F08%2F11%2Fwhy-is-this-so-dom-hard%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fblog.jeffdouglas.com%2F2010%2F08%2F11%2Fwhy-is-this-so-dom-hard%2F&amp;source=jeffdonthemic&amp;style=normal&amp;service=bit.ly&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>Let me start out right away by saying I am not a DOM or CSS master. I&#8217;ve typically had employees or co-workers to perform these functions for my so I&#8217;ve (unfortunately) let me skills wane. However, I&#8217;m not totally clueless. I was trying to build the following Visualforce page a couple of days ago and working with the DOM and Visualforce components seems to be much harder than what it should be. Perhaps I&#8217;m doing something wrong? Luckily <a href="http://th3silverlining.com" target="_blank">Wes Nolte</a> and <a href="http://d3developer.com/" target="_blank">Joel Dietz</a> <strong>are</strong> experts and they both have a number of great blog posts on this subject.</p>
<p>I was trying to create the following Visualforce page that contains a simple SelectList (I&#8217;ve sanitized the code for your protection).</p>
<p><img src="http://blog.jeffdouglas.com/wp-content/uploads/2010/08/dom1.png" alt="" width="419" height="41" /></p>
<p>When the user submits the form, the value of the currently selected  option is fired off via JavaScript. Shouldn&#8217;t be a big deal, right? Based upon the Visualforce docs for <a href="http://www.salesforce.com/us/developer/docs/pages/Content/pages_access.htm?SearchType=Stem&amp;Highlight=DOM" target="_blank">Using JavaScript to Reference Components</a>, I thought this code would work using the $Component variable (line #5).</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
</pre></td><td class="code"><pre class="java" style="font-family:monospace;">&lt;apex:page controller=&quot;MyController&quot; showHeader=&quot;false&quot; id=&quot;thePage&quot;&gt;
&nbsp;
  &lt;script language=&quot;javascript&quot;&gt;
  function doSubmit() {
    alert(document.getElementById(&quot;{!$Component.theSelectList}&quot;).value);
  }
  &lt;/script&gt;
&nbsp;
  &lt;apex:form id=&quot;theForm&quot;&gt;
    &lt;apex:pageblock id=&quot;thePageBlock&quot;&gt;
      &lt;apex:pageblockSection id=&quot;thePageBlockSection&quot;&gt;
        &lt;apex:pageBlockSectionItem id=&quot;thePageBlockItem&quot;&gt;
          &lt;apex:selectList value=&quot;{!selectedContentId}&quot; size=&quot;1&quot; id=&quot;theSelectList&quot;&gt;
            &lt;apex:selectOptions value=&quot;{!contentOptions}&quot;/&gt;      
          &lt;/apex:selectList&gt;
        &lt;/apex:pageBlockSectionItem&gt;
        &lt;input type=&quot;button&quot; value=&quot;Submit&quot; onclick=&quot;doSubmit()&quot; /&gt;
      &lt;/apex:pageblockSection&gt;
    &lt;/apex:pageblock&gt;
  &lt;/apex:form&gt;
&nbsp;
&lt;/apex:page&gt;</pre></td></tr></table></div>

<p>Unfortunately Firebug choked with s null pointer for the object&#8217;s reference.</p>
<p><img src="http://blog.jeffdouglas.com/wp-content/uploads/2010/08/dom2.png" alt="" width="459" height="153" /></p>
<p>I found Wes&#8217; great post, <a href="http://th3silverlining.com/2009/06/17/visualforce-component-ids-javascript/" target="_blank">VisualForce Component Ids &amp; Javascript</a>, and took a look at the element Id that Salesforce generated for the SelectList component. Based upon the other elements in the DOM hierarchy, I hard-coded my JavaScript to use the id that Salesforce was generating and the method worked correctly!</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>3
4
5
6
7
</pre></td><td class="code"><pre class="java" style="font-family:monospace;">  &lt;script language=&quot;javascript&quot;&gt;
  function doSubmit() {
    alert(document.getElementById(&quot;thePage:theForm:thePageBlock:thePageBlockSection:thePageBlockItem:theSelectList&quot;).value);
  }
  &lt;/script&gt;</pre></td></tr></table></div>

<p><img src="http://blog.jeffdouglas.com/wp-content/uploads/2010/08/dom3.png" alt="" width="570" height="156" /></p>
<p>So now I was confused. I dug deeper into Wes&#8217; post, the code and comments. Wes&#8217; solution was to assign the element value to a JavaScript variable just after it appears on the page (or at the same level within the page tree). My final (working) code looks like the following. Notice line #16 where I set the local JavaScript variable and then line #5 where I reference it&#8217;s currently selected value.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
</pre></td><td class="code"><pre class="java" style="font-family:monospace;">&lt;apex:page controller=&quot;MyController&quot; showHeader=&quot;false&quot; id=&quot;thePage&quot;&gt;
&nbsp;
  &lt;script language=&quot;javascript&quot;&gt; 
  function doSubmit() {
    alert(options.value);
  }
  &lt;/script&gt;
&nbsp;
  &lt;apex:form id=&quot;theForm&quot;&gt;
    &lt;apex:pageblock id=&quot;thePageBlock&quot;&gt;
      &lt;apex:pageblockSection id=&quot;thePageBlockSection&quot;&gt;
         &lt;apex:pageBlockSectionItem id=&quot;thePageBlockItem&quot;&gt;
            &lt;apex:selectList value=&quot;{!selectedContentId}&quot; size=&quot;1&quot; id=&quot;theSelectList&quot;&gt;
              &lt;apex:selectOptions value=&quot;{!contentOptions}&quot;/&gt;       
            &lt;/apex:selectList&gt;
            &lt;script&gt; var options = document.getElementById(&quot;{!$Component.theSelectList}&quot;); &lt;/script&gt;
         &lt;/apex:pageBlockSectionItem&gt;
        &lt;input type=&quot;button&quot; value=&quot;Submit&quot; onclick=&quot;doSubmit()&quot; /&gt;
      &lt;/apex:pageblockSection&gt;
    &lt;/apex:pageblock&gt;
  &lt;/apex:form&gt; 
&nbsp;
&lt;/apex:page&gt;</pre></td></tr></table></div>

<p>Wes states that this solution is simple as well as flexible. However, what happens if you have 20+ form fields that you need to process in this manner? Does accessing the DOM seem too hard with Visualforce components? Let me know if I am doing something wrong?</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jeffdouglas.com/2010/08/11/why-is-this-so-dom-hard/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
		</item>
		<item>
		<title>Email a Document with Salesforce.com</title>
		<link>http://blog.jeffdouglas.com/2010/07/22/create-and-email-a-document-with-salesforce-com/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=create-and-email-a-document-with-salesforce-com</link>
		<comments>http://blog.jeffdouglas.com/2010/07/22/create-and-email-a-document-with-salesforce-com/#comments</comments>
		<pubDate>Thu, 22 Jul 2010 10:39:28 +0000</pubDate>
		<dc:creator>Jeff Douglas</dc:creator>
				<category><![CDATA[Apex]]></category>
		<category><![CDATA[Code Sample]]></category>
		<category><![CDATA[Salesforce]]></category>
		<category><![CDATA[Visualforce]]></category>

		<guid isPermaLink="false">http://blog.jeffdouglas.com/?p=2895</guid>
		<description><![CDATA[After my last post, Create and Email a PDF with Salesforce.com, I received a few comments whether it was possible to do the same with Document stored in Salesforce.com. Could you choose a Document and then send it via email as an attachment? The short answer is yes! However, I tried to do it from [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fblog.jeffdouglas.com%2F2010%2F07%2F22%2Fcreate-and-email-a-document-with-salesforce-com%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fblog.jeffdouglas.com%2F2010%2F07%2F22%2Fcreate-and-email-a-document-with-salesforce-com%2F&amp;source=jeffdonthemic&amp;style=normal&amp;service=bit.ly&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p style="clear: both">After my last post, <a href="http://blog.jeffdouglas.com/2010/07/16/create-and-email-a-pdf-with-salesforce-com/" target="_blank">Create and Email a PDF with Salesforce.com</a>, I received a few comments whether it was possible to do the same with Document stored in Salesforce.com. Could you choose a Document and then send it via email as an attachment? The short answer is yes! However, I tried to do it from a Force.com Sites page but was not able to get it to work. The document is not marked for internal use and it is marked as an externally available image. I also made sure that the public settings for my Site included read access to documents but still the query for the document returns no results. No time to look at it in depth right now so if anyone has an idea, please send it my way.</p>
<p style="clear: both"><a href="http://blog.jeffdouglas.com/2010/07/22/create-and-email-a-document-with-salesforce-com/email-doc/" rel="attachment wp-att-2896"><img src="http://blog.jeffdouglas.com/wp-content/uploads/2010/07/email-doc.png" alt="" title="email-doc" width="500" class="alignnone size-full wp-image-2896" /></a></p>
<p style="clear: both"><strong>DocumentEmailer Visualforce Page</strong></p>
<p style="clear: both">

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
</pre></td><td class="code"><pre class="java" style="font-family:monospace;">&lt;apex:page controller=&quot;DocumentEmailController&quot;&gt;
  &lt;apex:sectionHeader title=&quot;Document Example&quot; subtitle=&quot;Email a Document&quot; 
    description=&quot;Example of how to email a Document.&quot;/&gt;
&nbsp;
  &lt;apex:form &gt;
    &lt;apex:pageMessages /&gt;
    &lt;apex:pageBlock title=&quot;Document Input&quot;&gt;
&nbsp;
      &lt;apex:pageBlockButtons &gt;
        &lt;apex:commandButton action=&quot;{!sendDoc}&quot; value=&quot;Send Document&quot;/&gt;
      &lt;/apex:pageBlockButtons&gt;
&nbsp;
      &lt;apex:pageBlockSection &gt;
&nbsp;
        &lt;apex:pageBlockSectionItem &gt;
            &lt;apex:outputLabel value=&quot;Email to send to&quot; for=&quot;email&quot;/&gt;
          &lt;apex:inputText value=&quot;{!email}&quot; id=&quot;email&quot;/&gt;
        &lt;/apex:pageBlockSectionItem&gt;
&nbsp;
        &lt;apex:pageBlockSectionItem &gt;
            &lt;apex:outputLabel value=&quot;Document&quot; for=&quot;document&quot;/&gt;
            &lt;apex:selectList value=&quot;{!documentId}&quot; id=&quot;document&quot; size=&quot;1&quot;&gt;
                 &lt;apex:selectOptions value=&quot;{!documents}&quot;/&gt;
            &lt;/apex:selectList&gt;
        &lt;/apex:pageBlockSectionItem&gt;
&nbsp;
      &lt;/apex:pageBlockSection&gt;
&nbsp;
    &lt;/apex:pageBlock&gt;
  &lt;/apex:form&gt;
&nbsp;
&lt;/apex:page&gt;</pre></td></tr></table></div>

</p>
<p style="clear: both"><strong>DocumentEmailController</strong></p>
<p style="clear: both">

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
</pre></td><td class="code"><pre class="java" style="font-family:monospace;">public with sharing class DocumentEmailController {
&nbsp;
  public ID documentId {get;set;}
  public String email {get;set;}
&nbsp;
  public List&lt;SelectOption&gt; documents {
    get {
      if (documents == null) {
        documents = new List&lt;SelectOption&gt;();
        documents.add(new SelectOption('01570000001NZDn','Cup of Coffee? - DOC'));
        documents.add(new SelectOption('01570000001NZDi','Workflow Cheatsheet -  PDF'));
      }
      return documents;
    }
    set;
  }
&nbsp;
  public PageReference sendDoc() {
&nbsp;
    Document doc = [select id, name, body, contenttype, developername, type 
      from Document where id = :documentId];
&nbsp;
    Messaging.EmailFileAttachment attach = new Messaging.EmailFileAttachment();
    attach.setContentType(doc.contentType);
    attach.setFileName(doc.developerName+'.'+doc.type);
    attach.setInline(false);
    attach.Body = doc.Body;
&nbsp;
    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
    mail.setUseSignature(false);
    mail.setToAddresses(new String[] { email });
    mail.setSubject('Document Email Demo');
    mail.setHtmlBody('Here is the email you requested: '+doc.name);
    mail.setFileAttachments(new Messaging.EmailFileAttachment[] { attach }); 
&nbsp;
    // Send the email
    Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
&nbsp;
    ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO, 'Email with Document sent to '+email));
&nbsp;
    return null;
&nbsp;
  }
&nbsp;
}</pre></td></tr></table></div>

</p>
<p style="clear: both"><strong>Test Class</strong></p>
<p style="clear: both">

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
</pre></td><td class="code"><pre class="java" style="font-family:monospace;">@isTest
private class Test_DocumentEmailer {
&nbsp;
  static Document document;
&nbsp;
  static {
&nbsp;
    document = new Document();
    document.Body = Blob.valueOf('Some Text');
    document.ContentType = 'application/pdf';
    document.DeveloperName = 'my_document';
    document.IsPublic = true;
    document.Name = 'My Document';
    document.FolderId = [select id from folder where name = 'My Test Docs'].id;
    insert document;
&nbsp;
  }
&nbsp;
  static testMethod void testDocumentEmailer() {
&nbsp;
    PageReference pref = Page.DocumentEmailer;        
    DocumentEmailController con = new DocumentEmailController();    
&nbsp;
    Test.startTest();
&nbsp;
    System.assertEquals(2,con.documents.size());
&nbsp;
    // populate the field with values
    con.documentId = document.id;
    con.email = 'test@noemail.com';
    // submit the request
    pref = con.sendDoc();
&nbsp;
    Test.stopTest(); 
&nbsp;
  }
}</pre></td></tr></table></div>

</p>
<p><br class="final-break" style="clear: both" /></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jeffdouglas.com/2010/07/22/create-and-email-a-document-with-salesforce-com/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
		<item>
		<title>Create and Email a PDF with Salesforce.com</title>
		<link>http://blog.jeffdouglas.com/2010/07/16/create-and-email-a-pdf-with-salesforce-com/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=create-and-email-a-pdf-with-salesforce-com</link>
		<comments>http://blog.jeffdouglas.com/2010/07/16/create-and-email-a-pdf-with-salesforce-com/#comments</comments>
		<pubDate>Fri, 16 Jul 2010 12:03:15 +0000</pubDate>
		<dc:creator>Jeff Douglas</dc:creator>
				<category><![CDATA[Apex]]></category>
		<category><![CDATA[Code Sample]]></category>
		<category><![CDATA[Salesforce]]></category>
		<category><![CDATA[Visualforce]]></category>

		<guid isPermaLink="false">http://blog.jeffdouglas.com/?p=2883</guid>
		<description><![CDATA[This is a continuation of my post a couple of days ago, Attach a PDF to a Record in Salesforce, and shows how to dynamically generate a PDF and attach it to an email. The code is fairly similar and has the same issue with testing the PageReference getContent() method. You can run this demo [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fblog.jeffdouglas.com%2F2010%2F07%2F16%2Fcreate-and-email-a-pdf-with-salesforce-com%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fblog.jeffdouglas.com%2F2010%2F07%2F16%2Fcreate-and-email-a-pdf-with-salesforce-com%2F&amp;source=jeffdonthemic&amp;style=normal&amp;service=bit.ly&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p style="clear: both">This is a continuation of my post a couple of days ago, <a href="http://blog.jeffdouglas.com/2010/07/14/attach-a-pdf-to-a-record-in-salesforce/" target="_blank">Attach a PDF to a Record in Salesforce</a>, and shows how to dynamically generate a PDF and attach it to an email. The code is fairly similar and has the same issue with testing the PageReference getContent() method.</p>
<p style="clear: both">
<h3 style="text-decoration:underline; clear: both"><a href="https://jeffdouglas-developer-edition.na5.force.com/examples/PdfEmailer" target="_blank">You can run this demo at my developer site.</a></h3>
</p>
<p style="clear: both"><a href="https://jeffdouglas-developer-edition.na5.force.com/examples/PdfEmailer"><img src="http://blog.jeffdouglas.com/wp-content/uploads/2010/07/email-pdf.png" alt="" title="email-pdf" width="500" height="237" class="alignnone size-full wp-image-2889" /></a>
<p><strong>PdfEmailer Visualforce Page</strong></p>
<p style="clear: both">The Visualforce page simply allows the user to enter their email address and select a sample Account from the picklist. This is Account that is passed to the PdfGeneratorTemplate Visualforce page to generate the PDF.</p>
<p style="clear: both">

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
</pre></td><td class="code"><pre class="java" style="font-family:monospace;">&lt;apex:page controller=&quot;PdfEmailController&quot;&gt;
  &lt;apex:sectionHeader title=&quot;PDF Example&quot; subtitle=&quot;Email a PDF&quot; 
    description=&quot;Example of how to email a dynamically generated PDF.&quot;/&gt;
&nbsp;
  &lt;apex:form &gt;
    &lt;apex:pageMessages /&gt;
    &lt;apex:pageBlock title=&quot;PDF Input&quot;&gt;
&nbsp;
      &lt;apex:pageBlockButtons &gt;
        &lt;apex:commandButton action=&quot;{!sendPdf}&quot; value=&quot;Send PDF&quot;/&gt;
      &lt;/apex:pageBlockButtons&gt;
&nbsp;
      &lt;apex:pageBlockSection &gt;
&nbsp;
        &lt;apex:pageBlockSectionItem &gt;
            &lt;apex:outputLabel value=&quot;Email to send to&quot; for=&quot;email&quot;/&gt;
          &lt;apex:inputText value=&quot;{!email}&quot; id=&quot;email&quot;/&gt;
        &lt;/apex:pageBlockSectionItem&gt;
&nbsp;
        &lt;apex:pageBlockSectionItem &gt;
            &lt;apex:outputLabel value=&quot;Account&quot; for=&quot;account&quot;/&gt;
            &lt;apex:selectList value=&quot;{!accountId}&quot; id=&quot;account&quot; size=&quot;1&quot;&gt;
                 &lt;apex:selectOptions value=&quot;{!accounts}&quot;/&gt;
            &lt;/apex:selectList&gt;
        &lt;/apex:pageBlockSectionItem&gt;
&nbsp;
      &lt;/apex:pageBlockSection&gt;
&nbsp;
    &lt;/apex:pageBlock&gt;
  &lt;/apex:form&gt;
&nbsp;
&lt;/apex:page&gt;</pre></td></tr></table></div>

</p>
<p style="clear: both"><strong>PdfEmailerController</strong></p>
<p style="clear: both">The Controller passes the Account ID that the user entered as a parameter for the Visualforce page being generated. It let creates the attachment from the PDF content. The Body of the attachment uses the Blob returned from the PageReference’s getContent method. You could also use the getContentAsPDF method which always returns the page as a PDF, regardless of the <apex:page> component’s renderAs attribute. However, this method always seems to throw an error in the test class. See the <a href="http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_pages_pagereference.htm" target="_blank">PageReference documentation</a> for more info. The method then constructs the SimpleEmailMessage object and then sends it on its way to the recipient&#8217;s inbox.</p>
<p>
<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
</pre></td><td class="code"><pre class="java" style="font-family:monospace;">public with sharing class PdfEmailController {
&nbsp;
  public ID accountId {get;set;}
  public String email {get;set;}
&nbsp;
  public List&lt;SelectOption&gt; accounts {
    get {
      if (accounts == null) {
        accounts = new List&lt;SelectOption&gt;();
        accounts.add(new SelectOption('0017000000LgRMb','United Oil &amp; Gas Corp.'));
        accounts.add(new SelectOption('0017000000LgRMV','Burlington Textiles Corp of America'));
      }
      return accounts;
    }
    set;
  }
&nbsp;
  public PageReference sendPdf() {
&nbsp;
    PageReference pdf = Page.PdfGeneratorTemplate;
    // add parent id to the parameters for standardcontroller
    pdf.getParameters().put('id',accountId);
&nbsp;
    // the contents of the attachment from the pdf
    Blob body;
&nbsp;
    try {
&nbsp;
      // returns the output of the page as a PDF
      body = pdf.getContent();
&nbsp;
    // need to pass unit test -- current bug  
    } catch (VisualforceException e) {
      body = Blob.valueOf('Some Text');
    }
&nbsp;
    Messaging.EmailFileAttachment attach = new Messaging.EmailFileAttachment();
    attach.setContentType('application/pdf');
    attach.setFileName('testPdf.pdf');
    attach.setInline(false);
    attach.Body = body;
&nbsp;
    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
    mail.setUseSignature(false);
    mail.setToAddresses(new String[] { email });
    mail.setSubject('PDF Email Demo');
    mail.setHtmlBody('Here is the email you requested! Check the attachment!');
    mail.setFileAttachments(new Messaging.EmailFileAttachment[] { attach }); 
&nbsp;
    // Send the email
    Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
&nbsp;
    ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO, 'Email with PDF sent to '+email));
&nbsp;
    return null;
&nbsp;
  }
&nbsp;
}</pre></td></tr></table></div>

</p>
<p><strong>PdfGeneratorTemplate Visualforce Page</strong>
<p>This is the Visualforce page that is generated in the Controller. It simply uses the StandardController and displays the Account name for the ID passed to it.
<p>
<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code"><pre class="java" style="font-family:monospace;">&lt;apex:page standardController=&quot;Account&quot; renderAs=&quot;pdf&quot;&gt;
  &lt;h1&gt;Congratulations!!&lt;/h1&gt;
  &lt;p&gt;You created a PDF for {!account.name}&lt;/p&gt;
&lt;/apex:page&gt;</pre></td></tr></table></div>

</p>
<p><strong>Test Class</strong>
<p>
<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
</pre></td><td class="code"><pre class="java" style="font-family:monospace;">@isTest
private class Test_PdfEmailController {
&nbsp;
  static Account account;
&nbsp;
  static {
&nbsp;
    account = new Account();
    account.Name = 'Test Account';
    insert account;
&nbsp;
  }
&nbsp;
  static testMethod void testPdfEmailer() {
&nbsp;
    PageReference pref = Page.PdfEmailer;
    pref.getParameters().put('id',account.id);
    Test.setCurrentPage(pref);
&nbsp;
    PdfEmailController con = new PdfEmailController();    
&nbsp;
    Test.startTest();
&nbsp;
    System.assertEquals(2,con.accounts.size());
&nbsp;
    // populate the field with values
    con.accountId = account.id;
    con.email = 'test@noemail.com';
    // submit the record
    pref = con.sendPdf();
&nbsp;
    Test.stopTest(); 
&nbsp;
  }
}</pre></td></tr></table></div>
</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jeffdouglas.com/2010/07/16/create-and-email-a-pdf-with-salesforce-com/feed/</wfw:commentRss>
		<slash:comments>26</slash:comments>
		</item>
		<item>
		<title>Attach a PDF to a Record in Salesforce</title>
		<link>http://blog.jeffdouglas.com/2010/07/14/attach-a-pdf-to-a-record-in-salesforce/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=attach-a-pdf-to-a-record-in-salesforce</link>
		<comments>http://blog.jeffdouglas.com/2010/07/14/attach-a-pdf-to-a-record-in-salesforce/#comments</comments>
		<pubDate>Wed, 14 Jul 2010 13:57:33 +0000</pubDate>
		<dc:creator>Jeff Douglas</dc:creator>
				<category><![CDATA[Apex]]></category>
		<category><![CDATA[Code Sample]]></category>
		<category><![CDATA[Salesforce]]></category>
		<category><![CDATA[Visualforce]]></category>

		<guid isPermaLink="false">http://blog.jeffdouglas.com/?p=2854</guid>
		<description><![CDATA[Salesforce.com makes it extremely easy to generate PDF documents on the fly by simply using the renderAs=&#8221;pdf&#8221; attribute for the &#60;apex:page&#62; component. It&#8217;s also a snap to attach these PDFs to records as Attachments. Below is a small Visualforce page and Controller that generates a PDF and saves it to an Account. Note: there is [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fblog.jeffdouglas.com%2F2010%2F07%2F14%2Fattach-a-pdf-to-a-record-in-salesforce%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fblog.jeffdouglas.com%2F2010%2F07%2F14%2Fattach-a-pdf-to-a-record-in-salesforce%2F&amp;source=jeffdonthemic&amp;style=normal&amp;service=bit.ly&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>Salesforce.com makes it extremely easy to generate PDF documents on the fly by simply using the renderAs=&#8221;pdf&#8221; attribute for the &lt;apex:page&gt; component. It&#8217;s also a snap to attach these PDFs to records as Attachments. Below is a small Visualforce page and Controller that generates a PDF and saves it to an Account.</p>
<p><strong>Note:</strong> there is a small issue when it comes to testing the Controller. Salesforce currently throws an error (Salesforce.com Error &#8220;Unable to retrieve object&#8221;) when getContent or getContentAsPDF is called from a test method. There&#8217;s an <a href="http://sites.force.com/ideaexchange/ideaView?c=09a30000000D9xt&#038;id=08730000000HzknAAC" target="_blank">Idea to make this work</a> properly. I encourage everyone to vote for this.</p>
<p><a href="http://blog.jeffdouglas.com/2010/07/14/attach-a-pdf-to-a-record-in-salesforce/attach-pdf/" rel="attachment wp-att-2867"><img src="http://blog.jeffdouglas.com/wp-content/uploads/2010/07/attach-pdf.png" alt="" title="attach-pdf" width="500" class="alignnone size-full wp-image-2867" /></a></p>
<p><strong>PdfGenerator Visualforce Page</strong></p>
<p>The Visualforce page allows the users to enter the ID of the Account to attach the PDF to as well as the name of the PDF. You could just have easily used a Controller Extension instead of entering the ID for the Account but I went this route for simplicity.</p>
<p>
<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
</pre></td><td class="code"><pre class="java" style="font-family:monospace;">&lt;apex:page controller=&quot;PdfGeneratorController&quot;&gt;
  &lt;apex:sectionHeader title=&quot;PDF Example&quot; subtitle=&quot;Attach a PDF&quot; 
    description=&quot;Example of how to attach a PDF to a record.&quot;/&gt;
&nbsp;
  &lt;apex:form &gt;
    &lt;apex:pageBlock title=&quot;PDF Input&quot;&gt;
&nbsp;
      &lt;apex:pageBlockButtons &gt;
        &lt;apex:commandButton action=&quot;{!savePdf}&quot; value=&quot;Save PDF&quot;/&gt;
      &lt;/apex:pageBlockButtons&gt;
      &lt;apex:pageMessages /&gt;
&nbsp;
      &lt;apex:pageBlockSection &gt;
&nbsp;
        &lt;apex:pageBlockSectionItem &gt;
            &lt;apex:outputLabel value=&quot;File Name&quot; for=&quot;pdfName&quot;/&gt;
          &lt;apex:inputText value=&quot;{!pdfName}&quot; id=&quot;pdfName&quot;/&gt;
        &lt;/apex:pageBlockSectionItem&gt;
&nbsp;
        &lt;apex:pageBlockSectionItem &gt;
            &lt;apex:outputLabel value=&quot;Account ID&quot; for=&quot;id&quot;/&gt;
          &lt;apex:inputText value=&quot;{!parentId}&quot; id=&quot;id&quot;/&gt;
        &lt;/apex:pageBlockSectionItem&gt;
&nbsp;
      &lt;/apex:pageBlockSection&gt;
&nbsp;
    &lt;/apex:pageBlock&gt;
  &lt;/apex:form&gt;
&nbsp;
&lt;/apex:page&gt;</pre></td></tr></table></div>

</p>
<p><strong>PdfGeneratorController Custom Controller</strong></p>
<p>The Controller passes the Account ID that the user entered as a parameter for the Visualforce page being generated. It then creates a new Attachment object and sets some attributes. It sets the ParentId to the value of the Account ID that the user entered so that the PDF is attached to that record. The Body of the attachment uses the Blob returned from the PageReference&#8217;s getContent method. You could also use the getContentAsPDF method which always returns the page as a PDF, regardless of the &lt;apex:page&gt; component&#8217;s renderAs attribute. However, this method <strong>always</strong> seems to throw an error in the test class. See the <a href="http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_pages_pagereference.htm" target="_blank">PageReference documentation</a> for more info. The method then redirects the user to the Account page so they can view the PDF attachment.</p>
<p>
<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
</pre></td><td class="code"><pre class="java" style="font-family:monospace;">public with sharing class PdfGeneratorController {
&nbsp;
  public ID parentId {get;set;}
  public String pdfName {get;set;}
&nbsp;
  public PageReference savePdf() {
&nbsp;
    PageReference pdf = Page.PdfGeneratorTemplate;
    // add parent id to the parameters for standardcontroller
    pdf.getParameters().put('id',parentId);
&nbsp;
    // create the new attachment
    Attachment attach = new Attachment();
&nbsp;
    // the contents of the attachment from the pdf
    Blob body;
&nbsp;
    try {
&nbsp;
        // returns the output of the page as a PDF
    	body = pdf.getContent();
&nbsp;
    // need to pass unit test -- current bug	
    } catch (VisualforceException e) {
    	body = Blob.valueOf('Some Text');
    }
&nbsp;
    attach.Body = body;
    // add the user entered name
    attach.Name = pdfName;
    attach.IsPrivate = false;
    // attach the pdf to the account
    attach.ParentId = parentId;
    insert attach;
&nbsp;
    // send the user to the account to view results
    return new PageReference('/'+parentId);
&nbsp;
  }
&nbsp;
}</pre></td></tr></table></div>

</p>
<p><strong>PdfGeneratorTemplate Visualforce Page</strong></p>
<p>This is the Visualforce page that is generated in the Controller. It simply uses the StandardController and displays the Account name for the ID passed to it.
<p>
<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code"><pre class="java" style="font-family:monospace;">&lt;apex:page standardController=&quot;Account&quot; renderAs=&quot;pdf&quot;&gt;
  &lt;h1&gt;Congratulations!!&lt;/h1&gt;
  &lt;p&gt;You created a PDF for {!account.name}&lt;/p&gt;
&lt;/apex:page&gt;</pre></td></tr></table></div>

</p>
<p><b>Test Class</b></p>
<p>
<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
</pre></td><td class="code"><pre class="java" style="font-family:monospace;">@isTest
private class Test_PdfGeneratorController {
&nbsp;
  static Account account;
&nbsp;
  static {
&nbsp;
    account = new Account();
    account.Name = 'Test Account';
    insert account;
&nbsp;
  }
&nbsp;
  static testMethod void testPdfGenerator() {
&nbsp;
    PageReference pref = Page.PdfGenerator;
    pref.getParameters().put('id',account.id);
    Test.setCurrentPage(pref);
&nbsp;
    PdfGeneratorController con = new PdfGeneratorController();    
&nbsp;
    Test.startTest();
&nbsp;
    // populate the field with values
    con.parentId = account.id;
    con.pdfName = 'My Test PDF';
&nbsp;
    // submit the record
    pref = con.savePdf();
&nbsp;
    // assert that they were sent to the correct page
    System.assertEquals(pref.getUrl(),'/'+account.id);
&nbsp;
    // assert that an attachment exists for the record
    System.assertEquals(1,[select count() from attachment where parentId = :account.id]);
&nbsp;
    Test.stopTest(); 
&nbsp;
  }
}</pre></td></tr></table></div>
</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jeffdouglas.com/2010/07/14/attach-a-pdf-to-a-record-in-salesforce/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Building a Dynamic Search Page in Visualforce</title>
		<link>http://blog.jeffdouglas.com/2010/07/13/building-a-dynamic-search-page-in-visualforce/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=building-a-dynamic-search-page-in-visualforce</link>
		<comments>http://blog.jeffdouglas.com/2010/07/13/building-a-dynamic-search-page-in-visualforce/#comments</comments>
		<pubDate>Tue, 13 Jul 2010 10:31:34 +0000</pubDate>
		<dc:creator>Jeff Douglas</dc:creator>
				<category><![CDATA[Apex]]></category>
		<category><![CDATA[Code Sample]]></category>
		<category><![CDATA[Salesforce]]></category>
		<category><![CDATA[Visualforce]]></category>

		<guid isPermaLink="false">http://blog.jeffdouglas.com/?p=2778</guid>
		<description><![CDATA[I brushed this code off and thought it might be useful to someone as a starting point for a dynamic search page. It has some cool functionality including passing search criteria via Javascript to the controller, search as you type, sorting of results by clicking on the column header plus much more. Hope you find [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fblog.jeffdouglas.com%2F2010%2F07%2F13%2Fbuilding-a-dynamic-search-page-in-visualforce%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fblog.jeffdouglas.com%2F2010%2F07%2F13%2Fbuilding-a-dynamic-search-page-in-visualforce%2F&amp;source=jeffdonthemic&amp;style=normal&amp;service=bit.ly&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>I brushed this code off and thought it might be useful to someone as a starting point for a dynamic search page. It has some cool functionality including passing search criteria via Javascript to the controller, search as you type, sorting of results by clicking on the column header plus much more. Hope you find it useful.</p>
<h3 style="text-decoration:underline"><a href="https://jeffdouglas-developer-edition.na5.force.com/examples/CustomerSearch" target="_blank"><font class="Apple-style-span" color="#000000">You can run this demo at my developer site.</font></a></h3>
<p><a href="https://jeffdouglas-developer-edition.na5.force.com/examples/CustomerSearch"><img src="http://blog.jeffdouglas.com/wp-content/uploads/2010/07/customer-search.png" alt="" title="customer-search" width="500" class="alignnone size-full wp-image-2782" /></a></p>
<p>Some of the interesting features of the Visualforce page and Apex controller include:
<ul>
<li>Instead of the typical overhead of using getters/setters in the controller to maintain the variables for the search form, I used <a href="http://blog.sforce.com/sforce/2009/10/passing-javascript-values-to-apex-controller.html" target="_blank">Dave Carroll&#8217;s blog</a> as an example to pass the variables via Javascript.</li>
<li>Since I&#8217;m using Javascript to pass my parameters, I can get fancy and make the search form more dynamic by running the search as the user types or selects an option in the picklist. No submit button is required.</li>
<li>Users can click on the column headers to toggle the direction of the search results by using a CommandLink component and passing the column name.</li>
<li>Build the picklist using Dynamic Apex&#8217;s <a href="http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_dynamic_describe_objects_understanding.htm" target="_blank">Describe functionality</a> so that it&#8217;s maintenance free.</li>
<li>Perform the search against multiple fields including multi-select picklists using dynamic SOQL and preventing SOQL injection attacks.</li>
</ul>
<p><b>ContactSearchController</b></p>
<p>Take a look at the Apex code below. The search interaction is split up between two separate but integral parts. When the search is fired from the Visualforce page via Javascript, the SOQL is constructed in the runSearch() method and is then passed to the runQuery() method to execute. The SOQL string is persisted so that when the user clicks on the table column the same SOQL can be issued again in the toggleSort() method but ordered by a different field name and sort direction.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
</pre></td><td class="code"><pre class="java" style="font-family:monospace;">public with sharing class ContactSearchController {
&nbsp;
  // the soql without the order and limit
  private String soql {get;set;}
  // the collection of contacts to display
  public List&lt;Contact&gt; contacts {get;set;}
&nbsp;
  // the current sort direction. defaults to asc
  public String sortDir {
    get  { if (sortDir == null) {  sortDir = 'asc'; } return sortDir;  }
    set;
  }
&nbsp;
  // the current field to sort by. defaults to last name
  public String sortField {
    get  { if (sortField == null) {sortField = 'lastName'; } return sortField;  }
    set;
  }
&nbsp;
  // format the soql for display on the visualforce page
  public String debugSoql {
    get { return soql + ' order by ' + sortField + ' ' + sortDir + ' limit 20'; }
    set;
  }
&nbsp;
  // 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();
  }
&nbsp;
  // toggles the sorting of query from asc&lt;--&gt;desc
  public void toggleSort() {
    // simply toggle the direction
    sortDir = sortDir.equals('asc') ? 'desc' : 'asc';
    // run the query again
    runQuery();
  }
&nbsp;
  // runs the actual query
  public void runQuery() {
&nbsp;
    try {
      contacts = Database.query(soql + ' order by ' + sortField + ' ' + sortDir + ' limit 20');
    } catch (Exception e) {
      ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Ooops!'));
    }
&nbsp;
  }
&nbsp;
  // runs the search with parameters passed via Javascript
  public PageReference runSearch() {
&nbsp;
    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');
&nbsp;
    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+'\')';
&nbsp;
    // run the query again
    runQuery();
&nbsp;
    return null;
  }
&nbsp;
  // use apex describe to build the picklist values
  public List&lt;String&gt; technologies {
    get {
      if (technologies == null) {
&nbsp;
        technologies = new List&lt;String&gt;();
        Schema.DescribeFieldResult field = Contact.interested_technologies__c.getDescribe();
&nbsp;
        for (Schema.PicklistEntry f : field.getPicklistValues())
          technologies.add(f.getLabel());
&nbsp;
      }
      return technologies;          
    }
    set;
  }
&nbsp;
}</pre></td></tr></table></div>

<p><b>CustomerSearch Visualforce Page</b></p>
<p>The Visualforce page has three sections: 1) a search form, 2) a results blockTable and 3) a debug panel displaying the SOQL that was executed. </p>
<p>The search form has a number of fields that fire the Javascript search using the onkeyup and onchange events. Instead of each form field passing the current values to actionFunction&#8217;s Javascript method, for ease of use, each form field calls the doSearch() function that gathers up the values and submits them. When the actionFunction renders it creates a Javascript function that POSTs the values to the controller in the same manner as CommandLink or CommandButton. </p>
<p>The search results BlockTable is rerendered when the search is submitted to the controller so that the results display properly. Users can click on the column headers to reorder the results of the query. This uses a CommandLink to pass the sort field to the controller and toggle the sort direction.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
</pre></td><td class="code"><pre class="java" style="font-family:monospace;">&lt;apex:page controller=&quot;ContactSearchController&quot; sidebar=&quot;false&quot;&gt;
&nbsp;
  &lt;apex:form &gt;
  &lt;apex:pageMessages id=&quot;errors&quot; /&gt;
&nbsp;
  &lt;apex:pageBlock title=&quot;Find Me A Customer!&quot; mode=&quot;edit&quot;&gt;
&nbsp;
  &lt;table width=&quot;100%&quot; border=&quot;0&quot;&gt;
  &lt;tr&gt;  
    &lt;td width=&quot;200&quot; valign=&quot;top&quot;&gt;
&nbsp;
      &lt;apex:pageBlock title=&quot;Parameters&quot; mode=&quot;edit&quot; id=&quot;criteria&quot;&gt;
&nbsp;
      &lt;script type=&quot;text/javascript&quot;&gt;
      function doSearch() {
        searchServer(
          document.getElementById(&quot;firstName&quot;).value,
          document.getElementById(&quot;lastName&quot;).value,
          document.getElementById(&quot;accountName&quot;).value,
          document.getElementById(&quot;technology&quot;).options[document.getElementById(&quot;technology&quot;).selectedIndex].value
          );
      }
      &lt;/script&gt; 
&nbsp;
      &lt;apex:actionFunction name=&quot;searchServer&quot; action=&quot;{!runSearch}&quot; rerender=&quot;results,debug,errors&quot;&gt;
          &lt;apex:param name=&quot;firstName&quot; value=&quot;&quot; /&gt;
          &lt;apex:param name=&quot;lastName&quot; value=&quot;&quot; /&gt;
          &lt;apex:param name=&quot;accountName&quot; value=&quot;&quot; /&gt;
          &lt;apex:param name=&quot;technology&quot; value=&quot;&quot; /&gt;
      &lt;/apex:actionFunction&gt;
&nbsp;
      &lt;table cellpadding=&quot;2&quot; cellspacing=&quot;2&quot;&gt;
      &lt;tr&gt;
        &lt;td style=&quot;font-weight:bold;&quot;&gt;First Name&lt;br/&gt;
        &lt;input type=&quot;text&quot; id=&quot;firstName&quot; onkeyup=&quot;doSearch();&quot;/&gt;
        &lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
        &lt;td style=&quot;font-weight:bold;&quot;&gt;Last Name&lt;br/&gt;
        &lt;input type=&quot;text&quot; id=&quot;lastName&quot; onkeyup=&quot;doSearch();&quot;/&gt;
        &lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
        &lt;td style=&quot;font-weight:bold;&quot;&gt;Account&lt;br/&gt;
        &lt;input type=&quot;text&quot; id=&quot;accountName&quot; onkeyup=&quot;doSearch();&quot;/&gt;
        &lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
        &lt;td style=&quot;font-weight:bold;&quot;&gt;Interested Technologies&lt;br/&gt;
          &lt;select id=&quot;technology&quot; onchange=&quot;doSearch();&quot;&gt;
            &lt;option value=&quot;&quot;&gt;&lt;/option&gt;
            &lt;apex:repeat value=&quot;{!technologies}&quot; var=&quot;tech&quot;&gt;
              &lt;option value=&quot;{!tech}&quot;&gt;{!tech}&lt;/option&gt;
            &lt;/apex:repeat&gt;
          &lt;/select&gt;
        &lt;/td&gt;
      &lt;/tr&gt;
      &lt;/table&gt;
&nbsp;
      &lt;/apex:pageBlock&gt;
&nbsp;
    &lt;/td&gt;
    &lt;td valign=&quot;top&quot;&gt;
&nbsp;
    &lt;apex:pageBlock mode=&quot;edit&quot; id=&quot;results&quot;&gt;
&nbsp;
        &lt;apex:pageBlockTable value=&quot;{!contacts}&quot; var=&quot;contact&quot;&gt;
&nbsp;
            &lt;apex:column &gt;
                &lt;apex:facet name=&quot;header&quot;&gt;
                    &lt;apex:commandLink value=&quot;First Name&quot; action=&quot;{!toggleSort}&quot; rerender=&quot;results,debug&quot;&gt;
                        &lt;apex:param name=&quot;sortField&quot; value=&quot;firstName&quot; assignTo=&quot;{!sortField}&quot;/&gt;
                    &lt;/apex:commandLink&gt;
                &lt;/apex:facet&gt;
                &lt;apex:outputField value=&quot;{!contact.firstName}&quot;/&gt;
            &lt;/apex:column&gt;
&nbsp;
            &lt;apex:column &gt;
                &lt;apex:facet name=&quot;header&quot;&gt;
                    &lt;apex:commandLink value=&quot;Last Name&quot; action=&quot;{!toggleSort}&quot; rerender=&quot;results,debug&quot;&gt;
                        &lt;apex:param name=&quot;sortField&quot; value=&quot;lastName&quot; assignTo=&quot;{!sortField}&quot;/&gt;
                    &lt;/apex:commandLink&gt;
                &lt;/apex:facet&gt;
                &lt;apex:outputField value=&quot;{!contact.lastName}&quot;/&gt;
            &lt;/apex:column&gt;
&nbsp;
            &lt;apex:column &gt;
                &lt;apex:facet name=&quot;header&quot;&gt;
                    &lt;apex:commandLink value=&quot;Account&quot; action=&quot;{!toggleSort}&quot; rerender=&quot;results,debug&quot;&gt;
                        &lt;apex:param name=&quot;sortField&quot; value=&quot;account.name&quot; assignTo=&quot;{!sortField}&quot;/&gt;
                    &lt;/apex:commandLink&gt;
                &lt;/apex:facet&gt;
                &lt;apex:outputField value=&quot;{!contact.account.name}&quot;/&gt;
            &lt;/apex:column&gt;
&nbsp;
            &lt;apex:column &gt;
                &lt;apex:facet name=&quot;header&quot;&gt;
                    &lt;apex:commandLink value=&quot;Technologies&quot; action=&quot;{!toggleSort}&quot; rerender=&quot;results,debug&quot;&gt;
                        &lt;apex:param name=&quot;sortField&quot; value=&quot;interested_technologies__c&quot; assignTo=&quot;{!sortField}&quot;/&gt;
                    &lt;/apex:commandLink&gt;
                &lt;/apex:facet&gt;
                &lt;apex:outputField value=&quot;{!contact.Interested_Technologies__c}&quot;/&gt;
            &lt;/apex:column&gt;
&nbsp;
        &lt;/apex:pageBlockTable&gt;
&nbsp;
    &lt;/apex:pageBlock&gt;
&nbsp;
    &lt;/td&gt;
  &lt;/tr&gt;
  &lt;/table&gt;
&nbsp;
  &lt;apex:pageBlock title=&quot;Debug - SOQL&quot; id=&quot;debug&quot;&gt;
      &lt;apex:outputText value=&quot;{!debugSoql}&quot; /&gt;           
  &lt;/apex:pageBlock&gt;    
&nbsp;
  &lt;/apex:pageBlock&gt;
&nbsp;
  &lt;/apex:form&gt;
&nbsp;
&lt;/apex:page&gt;</pre></td></tr></table></div>

]]></content:encoded>
			<wfw:commentRss>http://blog.jeffdouglas.com/2010/07/13/building-a-dynamic-search-page-in-visualforce/feed/</wfw:commentRss>
		<slash:comments>67</slash:comments>
		</item>
		<item>
		<title>Sharing Controller Context with a Visualforce Popup</title>
		<link>http://blog.jeffdouglas.com/2010/06/17/sharing-controller-context-with-a-visualforce-popup/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=sharing-controller-context-with-a-visualforce-popup</link>
		<comments>http://blog.jeffdouglas.com/2010/06/17/sharing-controller-context-with-a-visualforce-popup/#comments</comments>
		<pubDate>Thu, 17 Jun 2010 11:11:58 +0000</pubDate>
		<dc:creator>Jeff Douglas</dc:creator>
				<category><![CDATA[Salesforce]]></category>
		<category><![CDATA[Visualforce]]></category>

		<guid isPermaLink="false">http://blog.jeffdouglas.com/2010/06/17/sharing-controller-context-with-a-visualforce-popup/</guid>
		<description><![CDATA[&#8220;How do I popup a dialog in Visualforce&#8221;. I&#8217;m not sure what the deal is but this week I&#8217;ve received 3 emails asking me how to open a Visualforce popop window from a Visualforce page but both running in the same session. The question is asked fairly often on the message boards but there isn&#8217;t [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fblog.jeffdouglas.com%2F2010%2F06%2F17%2Fsharing-controller-context-with-a-visualforce-popup%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fblog.jeffdouglas.com%2F2010%2F06%2F17%2Fsharing-controller-context-with-a-visualforce-popup%2F&amp;source=jeffdonthemic&amp;style=normal&amp;service=bit.ly&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<blockquote style="clear: both"><p style="clear: both"><strong>&#8220;How do I popup a dialog in Visualforce&#8221;. </strong></p>
</blockquote>
<p style="clear: both">I&#8217;m not sure what the deal is but this week I&#8217;ve received 3 emails asking me how to open a Visualforce popop window from a Visualforce page but <strong><u>both</u></strong> running in the same session. The question is asked fairly often on the message boards but there isn&#8217;t a native solution. </p>
<p style="clear: both">The use case is that you have a Visualforce page with a commandbutton that launches a Visualforce popup. You want the popup to be able to access the controller&#8217;s context so you can share state. Unfortunately this is not currently possible with Visualforce and Apex. Opening a new window will start a new request which initializes a new instance of the controller. You <em>could</em> pass some variables to the new controller via Javascript but making a callback to the opening Visualforce is tedious as best.</p>
<p style="clear: both">Depending on what your popup needs to do, the best solution might be to create a modal instead of a new Visualforce page. Dave Carroll has a great article titled, &#8220;<a href="http://wiki.developerforce.com/index.php/Visualforce_Popup" target="_blank">Modal Dialogs in Visualforce using the Yahoo! User Interface Library</a>&#8220;, that shows how to use an In-Page DIV or Hidden DIV to create the modal. You can probably accomplish the same effect with other libraries but Dave&#8217;s solution with <a href="http://developer.yahoo.com/yui/" target="_blank">YUI!</a> is straight-forward, simple and well documented.</p>
<p><br class="final-break" style="clear: both" /></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jeffdouglas.com/2010/06/17/sharing-controller-context-with-a-visualforce-popup/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

