Sunday, May 17, 2009

Formating Page Created using <apex:page RenderAs="PDF">

VisualForce allows you to create PDF documents, but did you know those files can be easily manipulated with CSS, for example you can break a document on different pages, you can set footers and headers, you can set the page size, you can add page numbering…

You can find a very good document on how to use CSS to format PDF files here

This page creates a PDF file that:

  • Users Letter as the paper size
  • Has margins of 1/4 centimeters
  • Has a title on every page
  • Every page shows the page number in this format (page # of #)
  • Control what content goes on each page.
VisualForce Page:
<apex:page renderAs="PDF">
    <style>
        @page {
            size: letter;
            margin: 25mm;
            @top-center {
                content: "Sample";
            }
            @bottom-center {
                content: "Page " counter(page) " of " counter(pages);
            }
        }
        .page-break {
            display:block;
            page-break-after:always;
        }
        body {
            font-family: Arial Unicode MS;
        }
    </style>
    <div class="page-break">Page A</div>
    <div class="page-break">Page B</div>
    <div>Page C</div>
</apex:page>

How to set up a VisualForce page to edit multiple rows at the same time?

This code explains how to build a simple page that allows you to edit several records at the same time. The code builds this table:

You can edit any email, but only those marked with the checkbox will be saved on the database once the “Save” button is clicked, additionally there is a link on each row that will navigate to the edit page and fully edit the record. This is not a very good user interface, but allows me to demonstrate some techniques.

VisualForce Page:

<apex:page controller="MultiRow" >
    <apex:form >
        <apex:pageblock >
            <apex:pageBlockButtons >
                <apex:commandButton value="Save" action="{!Save}" />
            </apex:pageBlockButtons>
            <apex:pageBlockSection columns="1">
                <apex:dataTable value="{!Contacts}" var="c" border="1" rowClasses="odd,even" styleClass="tableClass" cellpadding="3">
                    <apex:column >
                        <apex:facet name="header">Actions</apex:facet>
                        <apex:inputCheckbox value="{!c.Checked}"/>
                        <apex:commandLink value="Full Edit" action="{!URLFOR($action.Contact.Edit, c.ID)}" target="_blank" />
                    </apex:column>
                    <apex:column >
                        <apex:facet name="header">Name</apex:facet>
                        <apex:outputText value="{!c.Name}"/>
                    </apex:column>
                    <apex:column >
                        <apex:facet name="header">Email</apex:facet>
                        <apex:inputText value="{!c.Email}" />
                    </apex:column>
                </apex:dataTable>
            </apex:pageBlockSection>
        </apex:pageblock>
    </apex:form>
</apex:page>
Controller:
public class MultiRow {
    public List<multiRowContact> Contacts { get; set; }

    public MultiRow() {
        LoadData();        
    }

    public PageReference Save() {
        for (multiRowContact MRC : Contacts) {
            MRC.Save();
        }
        LoadData();
        return null;
    }
    private void LoadData() {
        Contacts = new List<multiRowContact>();
        for (List<Contact> cs : [SELECT c.ID, c.Name, c.Email FROM Contact c WHERE c.AccountID = '0018000000OdcOt']) {
            for (Contact c : cs) {
                multiRowContact MRC = new multiRowContact();
                MRC.ID = c.ID;
                MRC.Checked = false;
                MRC.Name = c.Name;
                MRC.Email = c.Email;
                Contacts.add(MRC);
            }
        }
    }

    private class multiRowContact {
        public String ID { get; set; }
        public String Name { get; set; }
        public String Email { get; set; }
        public Boolean Checked { get; set; }
        public void Save() {
            if (Checked) {
                System.debug('Saving...ID: ' + ID);
                Contact c = [SELECT c.Email FROM Contact c WHERE c.ID = :ID LIMIT 1];
                c.Email = Email;
                update c;
            }
        }
    }
}

URLFOR() explained

Although this is a very useful function in Salesforce.com, it is not properly documented.

Few days ago, I found a very good blog that explains this function, I have decided to summarize Sam Arjmandi’s article, but for full details please visit his article here.

URLFOR function returns a relative URL using this syntax:

{!URLFOR(target, id, [inputs], [no override])}
Target: Action, s-control or static resource.
Id: Resource name (string type) or record ID (depends on the “target”).
Inputs: Additional parameters passed. Format: [param1="value1", param2="value2"]
No override: A Boolean flag. Set to true if to display a standard Salesforce page regardless of whether you have defined an override for it elsewhere. (default false)

So, how to use this function for files and folders ?

Resource file: URLFOR($Resource.LogoImg)
Resource zip file or folder: URLFOR($Resource.CorpZip, 'images/logo.gif')

But equally important, is that the URL for actions that can be performed on custom and standard objects can be easily found using this function. These actions are implemented by all objects:

View record: URLFOR($Action.Account.View, account.id)
Create new record: URLFOR($Action.Account.New)
Edit record: URLFOR($Action.Account.Edit, account.id)
Delete record: URLFOR($Action.Account.Delete, account.id)
View List: URLFOR($Action.Account.Tab, $ObjectType.Account)

Note that some objects support other additional actions; for example Contact also supports "Clone" and Case also supports "CloseCase" action. To find out which action can be invoked on a particular object, check the buttons and links which can be overridden for that object. For standard objects go to Setup > App Setup > Customize > Desired Standrd Object > Buttons and Links and you will see a page like this:

Just use the name of the function like this: URLFOR($Action.Object.Name, Object.ID)

Saturday, May 16, 2009

<apex:inputCheckBox> OnChange vs. OnClick Events

VisualForce allows most of its tags to react to JavaScript events, and they are usually quite straightforward and easy to implement. But, there are few events that can be tricky…

One of them, is the OnChange event for the <apex:inputCheckbox> tag. When a checkbox is checked or uncheck it generates the OnChange event, but only after the user selects a different input element in the page, after the checkbox loses its focus.

A better user experience could be achieved if the checkbox fired its event without waiting for the focus to be lost. This can be easily achieved using the OnClick event:
VisualForce code:

<apex:inputCheckbox onClick="{!SomeMethod}" />

Governor Limits for multi-tenant communities

I don’t like rules, especially when I am caught by the cops on the highway going over the speed limit, on the other hand I’m glad people stop on red lights and drive on the correct side of the road.

There are some laws that are required to prevent chaos. Can you imagine if people could drive on the roads as fast, in any direction and in any vehicle they pleased? Imagine being run over in a red light by a “monster truck” just because they did not want to wait? Or having to avoid oncoming traffic in the lane you are driving? There has to be some order and some rules to protect our rights in the communities we live.

Fortunately, there are rules, but usually those who do not follow them (even due to ignorance) are heavily fined. In a perfect society, we would be politely reminded if any of our actions could affect other community members and possibly prevent us from doing those actions that could affect others.

The applications we develop for salesforce.com run on a multi-tenant community, and we have rules that protect us from other community member’s actions, and to protect them from our actions. These rules are collectively known as Governor Limits!

Different Document Types

You already know that Salesforce.com allows you to easily create web pages to display information from your objects, but did you know you can also create other types of documents quite easily?

Two formats are currently supported: Microsoft Excel and Acrobat Reader (PDF).

These properties for the <apex:page> tag will create an Excel document called “Cases.XLS” with the contents of your page:

<apex:page contentType="application/vnd.ms-excel#Cases.xls" cache="true">
The cache=”true” property is quite important, especially when the user browses your ORG with Microsoft Internet Explorer.

These properties will create an Acrobat Reader document called “Cases.pdf” with the contents of your page:

<apex:page contentType="application/x-download#Casessomedocument.pdf" renderas=”PDF” >
Note: Your page should not have <apex:input*> tags. First of all, it does not make sense to have these tags if the forms are not to be posted back to Salesforce.com. Second, the rendering of these tags may not be as expected. But, it is quite valid to use links.

Assignment Rules Using APEX

Did you know you can use the assignment rules functionality that is provided to you with the standard Salesforce.com interface with Apex code?

This code creates a Case, sets the owner using the standard assignment rules, and sends the email to the new Case owner. It could also be used for any other object that support assignment rules.

Apex Code:

// Instantiate a new Case
Case newCase = new Case();

// Put here the code to initialize the fields with the information...

// Instantiate the database options
Database.DMLOptions dlo = new Database.DMLOptions();

// This line assigns the ID for the assignment rule you want to use
// dlo.assignmentRuleHeader.assignmentRuleId = getAssignmentRuleId();

// This line assigns the active assignment rule
dlo.assignmentRuleHeader. useDefaultRule = true;

// This line sends email to the related contact.
dlo.EmailHeader.triggerAutoResponseEmail = true;

// This line sends email to the new case owner
dlo.EmailHeader.triggerUserEmail = true;

// Set the options just defined
newCase.setOptions(dlo);

// Create case.
insert newCase;

API access with no password expiration

When you create an API integration package, you may want to have it run by an account whose password never expires.

By default the applications that connect to Salesforce.com via the API require a username, a password and a token. How would you set this up, so that the credentials do not expire?

  1. Create a profile for your API user
    1. Ensure the API checkbox is checked.
    2. Ensure password not expire checkbox is checked.
    3. Set other security options required by your application.
  2. Create a user you will use for the API logins and assign it to this profile.
  3. The application should run on a computer in a trusted IP address range (it could be located inside your network, on a trusted ISP, or it may connect to the network using a VPN).
    1. Login in via the API from the computer where the application is installed
    2. Check the IP address used here (Setup > Personal Setup > My Personal Information > Personal Information > Login History (Related List))
    3. Ensure that IP address is in a range defined here (Setup > Administration Setup > Security Controls> Network Access > Trusted IP Range Edit)

By executing the step #3, we are avoiding the use of a security token. This is still secure, because we are specifying the IP range of the computer where we know the application will always execute.

Saturday, May 9, 2009

What should go in the List parameter for a <apex:relatedList List=""> tag?

To answer this question, I decided to build a VisualForce page that would be as close as possible to the pages created using the standard page layouts.

For this task, I created two custom objects to represent a flight. One custom object would contain information about the flight and the second custom object would have information for the city. This picture ilustrates how I set up the relationships between them.

This is how I defined each of my objects:

This is the definition for "City":

Nothing special here, but note there is a field called "ABC" (it will be important when I explain the rules for naming child relationships)

This is the definition for "Flight":

There are some basic fields ("Arrival","Departure", ...) and there are two lookup fields to "City". One for the "Origin" and one for the "Destination".

This is how I defined the relationships:

This image illustrates how the "Origin" field is defined:

Note there is an error in the definition of the "Child Relationship Name".

This entry is very important to answer this post's question. These are the rules to the values you can enter:

  1. Only alphanumeric characters (Letters, numbers and underscore) are allowed
  2. Must begin with a letter
  3. Can’t end with an underscore
  4. Can’t contain two consecutive underscore characters.
  5. Must be unique across all city fields
    1. Can not be "ABC", because there is one field named "ABC" in City. I defined this field, to explain this point.
    2. Can not be the name of a different relationship… Although it may not be technically accurate, it helps if you think these relationships create a field in the destination object (City in this case).
With these rules, I used these "child relationship names":

  • Origin_Flights
  • Destination_Flights

Now I can answer this blog's question:

<apex:relatedList list="Origin_Flights__r" />
<apex:relatedList list="Destination_Flights__r" />
Simulating a standard page layout in VisualForce

My next step, create a page that looked as closed as possible to the ones using standard page layouts. Basically, this was my goal:

As you can see, there are a lot of standard related lists. How could I get their names? Eclipse will tell you:

With that information, I created a page that looked as close to the standard page layout as I could.

Before I show you the results, let me tell you there are some differences, but I will leave them for a future post. For example, I did not created the JavaScript to show the related lists Divs on mouse over. The section header is not identical (some links are missing)

This is what I got:

Finally, here is the code...

VisualForce Page:

<apex:page standardController="City__c" showHeader="true" tabStyle="City__c">
    <apex:sectionHeader title="City" subtitle="{!City__c.Name}" help="/help/doc/user_ed.jsp?loc=help&target=getstart_help.htm§ion=Getting_Started" />
    This page is made in visualFroce simulating a Page Layout Page... This is the description... blah... blah... blah<br/><br/>
    <apex:detail relatedList="false" title="false" />
    <apex:relatedList list="OpenActivities"/>
    <apex:relatedList list="ActivityHistories"/>
    <apex:relatedList list="NotesAndAttachments"/>
    <apex:relatedList list="Origin_Flights__r" />
    <apex:relatedList list="Destination_Flights__r" />
    <apex:relatedList list="ProcessSteps"/>
    
<H1>Other Related Lists Available from VisualForce</H1>

    <apex:pageblock title="City History">
        <apex:pageBlockTable value="{!City__c.Histories}" var="h">
            <!-- h.ID, h.ParentId -->
            <apex:column headerValue="Date">
                <apex:outputField value="{!h.CreatedDate}"/>
            </apex:column>
            <apex:column headerValue="User">
                <apex:outputField value="{!h.CreatedById}"/>
            </apex:column>
            <apex:column headerValue="Field">
                <apex:outputText value="{!h.Field}"/> <!-- This is a picklist -->
            </apex:column>
            <apex:column headerValue="From">
                <apex:outputField value="{!h.OldValue}"/>
            </apex:column>
            <apex:column headerValue="To">
                <apex:outputField value="{!h.NewValue}"/>
            </apex:column>
            <apex:column headerValue="IsDeleted">
                <apex:outputField value="{!h.IsDeleted}"/>
            </apex:column>
        </apex:pageBlockTable>
    </apex:pageblock>
    <apex:pageblock title="City Tags">
        <apex:pageBlockTable value="{!City__c.Tags}" var="t">
            <!-- t.Id, t.ItemId-->
            <apex:column headerValue="TagDefinitionId">
                <apex:outputField value="{!t.TagDefinitionId}"/>
            </apex:column>
            <apex:column headerValue="CreatedDate">
                <apex:outputField value="{!t.CreatedDate}"/>
            </apex:column>
            <apex:column headerValue="SystemModstamp">
                <apex:outputField value="{!t.SystemModstamp}"/>
            </apex:column>
            <apex:column headerValue="IsDeleted">
                <apex:outputField value="{!t.IsDeleted}"/>
            </apex:column>
            <apex:column headerValue="Name">
                <apex:outputField value="{!t.Name}"/>
            </apex:column>
            <apex:column headerValue="Type">
                <apex:outputField value="{!t.Type}"/>
            </apex:column>
        </apex:pageBlockTable>
    </apex:pageblock>
</apex:page>