Salesforce - Developer - Visualforce

salesforce-developer

https://developer.salesforce.com/page/An_Introduction_to_Visualforce_View_State
https://trailhead.salesforce.com/en/force_com_dev_beginner/visualforce_fundamentals/visualforce_intro
https://developer.salesforce.com/docs/atlas.en-us.204.0.workbook_vf.meta/workbook_vf/visualforce_workbook_intro.htm
https://developer.salesforce.com/docs/atlas.en-us.204.0.pages.meta/pages/pages_intro.htm
https://developer.salesforce.com/docs/atlas.en-us.204.0.pages.meta/pages/pages_compref.htm
https://developer.salesforce.com/blogs/developer-relations/2014/03/twitter-bootstrap-and-visualforce-in-minutes.html
http://events.developerforce.com/conference/dreamforce?session=23931
https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_intro.htm

https://github.com/dohbutz/Intro-to-Visualforce
Visualforce Workbook and Visualforce Developer Guide.

Expression
Global Variables
Formula Expression
Conditional Expression
Standard Controllers
Standard List Controllers
Custom Controllers
Components
Output Components
Iteration Components
Tags
Forms
Static Resources

// Salesforce - Developer - Visualforce - Cheat sheet:

basicText = apexpages.currentpage().getparameters().get('parameterName');
outputText = basicText.replace('\r\n','<br/>');

String onsave = apexpages.currentpage().getparameters().get('onSave');
PageReference savePage = new PageReference(onSave);
savePage.setRedirect(true);
return savePage;

ApexPages.addmessage(
  new ApexPages.message(
    ApexPages.severity.ERROR, 
    'Unable to do something. Exception: ' + e.getMessage()
  )
);

URL currentURL = new URL('https://' + ApexPages.currentPage().getUrl());
Set<String> whitelistedDomains = new Set<String>();
whitelistedDomains.add(currentURL.getHost());
whitelistedDomains.add('www.salesforce.com');
whitelistedDomains.add('www.force.com');
if (whitelistedDomains.contains(new URL(onsave).getHost()) {
  ...
} else {
  ...
}

if (url.startsWith('/')) {
  url.replaceFirst('/+','');
}
PageReference savePage = new PageReference('/' + url);
savePage.setRedirect(true);
return savePage;
// Salesforce - Developer - Visualforce:

Visualforce is the component-based user interface framework for the Force.com 
platform. The framework includes a tag-based markup language, similar to HTML. 
Each Visualforce tag corresponds to a coarse or fine-grained user interface 
component, such as a section of a page, or a field. Visualforce has about 100 
built-in components, and a mechanism whereby developers can create their own 
components. 

Visualforce uses the traditional model-view-controller (MVC) paradigm, with the 
option to use auto-generated controllers for database objects, providing simple 
and tight integration with the database. You can write your own controllers, or 
extensions to controllers, using Apex Code. Visualforce also provides AJAX 
components, and embeds the formula expression language for action, data and 
component binding interaction. 

We can think of Visualforce as similar to JSP but perhaps with more 
functionality.

A developer creates Visualforce pages by composing components, HTML, and 
optional styling elements on the Force.com platform. Just like HTML, Visualforce 
can integrate with any standard web technology or JavaScript framework to allow 
for a more animated and rich user interface. Each page is then accessible by a 
unique URL. When someone accesses a page, the server renders the page. 

<apex:page standardController="Account">
    <apex:form>
        <apex:pageBlock title="Edit Account for {!$User.FirstName}">
            <apex:pageMessages/>
            <apex:pageBlockButtons>
                <apex:commandButton value="Save" action="{!save}"/>
            </apex:pageBlockButtons>
            <apex:pageBlockSection>
                <apex:inputField value="{!account.name}"/>
            </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>
</apex:page>

In the above code:

1. The page component wraps every Visualforce page, and its standardController 
   attribute lets us make use of standard, automatically-generated, controller 
   technology.

2. The pageBlock, pageBlockButtons and pageBlockSection tags provide standard 
   Salesforce styling for a section in a page, similar to what you see on a 
   detail page.

3. The inputField generates an appropriate input element, depending on the type 
   of the field.

4. The commandButton renders a button, which when pushed, invokes a standard 
   method called save() on the controller. 

5. The Account standard controller retrieved a record from the database 
   considering the record Id found in the request (i.e., the URL), and made it 
   available to the Visualforce page automatically.

6. The $User variable provides access to details of the currently logged-in user.

7. The {!account.name} expression retrieved the metadata associated with the 
   name field of the Account object, rendered an appropriate input element, and 
   initialized with the value from the Account retrieved from the database.

8. The label for the name field on Account is automatically displayed, and the 
   input is highlighted as required by virtue of the inputField component 
   having been nested within a pageBlockSection.

9. The save() method on the controller provides a means of persisting the object 
   back to the database. Had there not been a record in the request, this same 
   action would attempt an insert of the account information provided in the 
   form.

10. Any errors that occur in the submission of the form, either standard or 
    custom, will be displayed by the pageMessages component. 

Visualforce follows the MVC pattern.  It is the View portion of the MVC picture.  
The model, or data structure, can be defined as either sObjects (the entity 
definitions for persisted data) or classes in Apex.  The view, or presentation 
layer, consists of Pages and components.  The controller, or logic layer, 
includes any custom controller logic written in Apex, or standard behavior 
generated by the Force.com platform for each business entity. 

In the above code, the view, our Visualforce page, contains the 
apex:inputField component, which is bound through the expression on its value 
attribute to the controller's get method on its account property.  The account 
property provides the view with the Account business entity object, the model.

The label for the field is automatically outputed by apex:inputField.  The value 
was derived through that component's value attribute expression, which calls 
into the controller layer for the get method on the controller's account 
property. Both the page and the controller are aware of the data structure and 
can interact with it directly — in this case the Account entity definition. As 
you can see, the expression uses simple dot notation to refer to the name field 
on the specific account instance. 

// Salesforce - Developer - Visualforce - Controllers and Extensions:

Controllers and extensions provide the logic interaction and behavior for an 
application. Force.com provides standard controllers for all standard and custom 
business entities. These controllers provide access to standard platform 
behavior including saving, logic, and navigation. In the example above, the 
standard controller for account was specified so standard action methods such 
as save can be bound to action supporting components, such as apex:commandButton. 

The signature for the save action method in the standard controller:

public PageReference save() {} 

Clicking the button invokes the standard save process. Navigation is managed 
through the PageReference object that is returned from the method. 

Custom controllers, written in Apex, deliver the flexibility to define your own 
logic, navigation, algorithms, and database and web services interactivity. With 
the stateful programming model provided by Visualforce, custom controllers can 
maintain state between pages making development of wizards straightforward. 
Custom controllers can themselves leverage the standard controller. 

Assume that you have two database objects, Account and Contact. A simple 
controller class for a two step wizard that creates an Account and a related 
Contact might be defined as such: 

public class MyWizardController {

    public Account account { get; set; }
    public Contact contact { get; set; }

    public MyWizardController() {
        account = new Account();
        contact = new Contact();
    }

    public PageReference next() {
        return Page.step2;
    }

    public PageReference previous() {
        return Page.step1;
    }

    public PageReference save() {
        Database.insert(account);
        contact.accountId = account.id;
        ApexPages.StandardController contactController = 
                        new ApexPages.StandardController(contact);
        return contactController.save();
    }
}  

In the above code, Page.step1 references a Visualforce page called step1, and if 
a button is bound to this action, the controller will redirect the user to the 
step1 page.

Visualforce controllers and extensions must be written in Apex.  These controllers 
typically  look no different than other Apex code, though they do have access 
to additional data types, classes, methods, and properties.  For example, in 
Visualforce controllers, we have access to page parameters, and Visualforce 
pages are first-class citizens within Apex, allowing us to redirect to various pages, 
render the pages as PDF, etc.

Here is a simple controller:

public class MyController {
  PageReference where;
  public PageReference dynamicJump() {
    if (ApexPages.currentPage().getParameters().get('p') != null) {
      where = Page.foo;
      where.setRedirect(true);
    } else {
      where = Page.bar;
      where.getParameters().put('p', 'nowHasParam');
    }
    return where;
  }
}

Page.foo is a Visualforce page named 'foo'.  When we returns a page object, which 
we have invoke the setRedirect method to true, Salesforce will issue the redirect.

Controllers can also execute DML, query the database, and return results.

Extensions provide the ability to augment standard or custom controllers. With 
extensions you can extend data access, adding logic or conditional navigation to 
an existing controller. An extension class is defined by providing a constructor 
which takes the controller type being extended as its argument. The following 
class definition extends the standard controller: 

public class AccountExtension {

    public Account account { get; set; }
    public AccountExtension(ApexPages.StandardController controller) {
        account = (Account) controller.getRecord();
    }    
}

Adding this controller to the page requires a simple change to the page 
component tag: 

<apex:page standardController="Account" extensions="AccountExtension">

// Visualforce Components:

A Visualforce page can contain a mixture of HTML and Visualforce components. 
The HTML and component tags need to be well-formed, and all pages begin with the 
page component.

<apex:page sidebar="false" showHeader="false">
</apex:page>

There are varying degrees of granularity with standard output components. At the 
fine end of the spectrum is apex:outputPanel, which is a simple container that, 
in the case of HTML rendering, produces a div element: 

<apex:page >
    <apex:outputPanel layout="block" style="font-weight:bold">
        Hello World!
    </apex:outputPanel>
</apex:page>

At the coarse end of the spectrum is apex:enhancedList:

<apex:page>
    <apex:enhancedList type="Contact" height="350"/>
</apex:page>

The above code produces a grid displaying contacts, completed with pagination, 
filtering, sorting, and a few more buttons and controls.

<apex:page standardController="Contact">
   <apex:pageBlock title="Simple Title">
      <b>Hello <i>{!$User.FirstName}</i>.</b>
   </apex:pageBlock>

   <apex:detail subject="{!Contact.Id}" relatedList="false" />
</apex:page>

In order for the above line of code to work, you need to have the Id of the 
contact in the URL. The standard controller does the work to supply this value 
dynamically into the merge field within the detail tag.

Notice the <apex:detail> tag.  It produces the standard contact detail panel. 
This looks and feels and behaves just like the standard contact detail panel, 
except of course it's embedded within our own page. 

It's worth stressing this point: You can now construct your own Salesforce user 
interface pages that looks and feel just like the standard ones, enhanced in any 
way you like, reusing existing, standard Salesforce display components. 
Alternatively, you can make it look completely different, banishing all of the 
Salesforce look and feel.

The <apex:detail> component renders the detail page layout for a given object. 
Most components take optional attributes that refine the behavior in some way. 
Passing relatedList="false" to the <apex:detail> component ensures that it 
doesn't show any related lists beneath the details, as typically found when you 
view a contact. 

When creating forms, the most common input elements are covered by the generic 
types such as apex:inputCheckbox, apex:selectList, and apex:inputText. However, 
do not overlook the power of the apex:inputField component, as it delivers field 
type awareness, requiredness, editability, and formatting automatically based on 
the respective field definition. 

<apex:page standardController="Account">
    <apex:form>
        <apex:pageBlock title="Edit Account for {!$User.FirstName}">
            <apex:pageMessages/>
            <apex:pageBlockButtons>
                <apex:commandButton value="Save" action="{!save}"/>
            </apex:pageBlockButtons>
            <apex:pageBlockSection>
                <apex:inputField value="{!account.name}"/>
                <apex:inputField value="{!account.industry}"/>
            </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>
</apex:page>

// Visualforce - AJAX Components:

<apex:page standardController="Account">
    <apex:form >
        <apex:pageBlock id="in" title="Edit Account for {!$User.FirstName}">
            <apex:pageMessages />
            <apex:pageBlockButtons >
                <apex:commandButton value="Save" action="{!quickSave}" 
                    rerender="out, in" status="status"/>     
            </apex:pageBlockButtons>
            <apex:pageBlockSection >
                <apex:inputField value="{!account.name}"/>
                <apex:inputField value="{!account.industry}"/>
            </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>
    <apex:pageBlock id="out" title="Read View">               
        <apex:actionStatus startText="updating..." id="status"/>
        <apex:pageBlockSection>
            <apex:outputField value="{!account.name}"/>
            <apex:outputField value="{!account.industry}"/>
        </apex:pageBlockSection>
    </apex:pageBlock>
</apex:page>

In the above code:

1. The rerender attribute on the commandButton changes the behavior from full to 
   partial page, and specifies what areas of the page will be updated on the 
   response — in this case, the apex:pageBlock component tags with the named 
   identifiers.

2. The status attribute on commandButton binds the operation indication to the 
   identified apex:actionStatus component.

3. The quickSave() method on the standard controller performs the same database 
   operation as the save() method, but returns the user to the same page rather 
   than navigating away. 

When the user changes a value and clicks on the "Save" button, the status bar 
produced by the <apex:actionStatus> component will indicate the record is being 
updated.

// Visualforce - Custom Components:

Visualforce also allow us to create custom components. Custom Visualforce 
components are developed using a markup-based approach through composition of 
HTML or other Visualforce components (standard or custom). Custom components are 
referenced by name in a similar fashion to standard components with the 
difference being the namespace given to them. 

A page that includes a custom component might simply look like this: 

<apex:page>
     <c:mycomponent>
</apex:page>

With the definition of the component being simply: 

<apex:component >
    <fieldset>
        <legend>MyComponent</legend>
        <h1>Hello World!</h1>
    </fieldset>
</apex:component>

Custom components also support strongly typed attributes. Allowing the consumer 
of the component to specify the text rather than always seeing "Hello World!" 
would require a simple attribute definition and passing of the desired value: 

<apex:page >
    <c:mycomponent text="Hello from the page!"/>
</apex:page>

With the added attribute component in the custom component definition: 

<apex:component >
    <apex:attribute name="text" type="String" description="My text to display"/>
    <fieldset>
        <legend>MyComponent</legend>
        <h1>{!text}</h1>
    </fieldset>
</apex:component>

Custom components can also have their own controllers, and attribute values can 
be passed into these controllers. Attributes support all primitives, Apex 
classes, and sObject definitions, including arrays of each.

See https://developer.salesforce.com/page/An_Introduction_to_Visualforce

// Visualforce - Using Visualforce Pages:

Visualforce pages can be incorporated into an application through multiple 
mechanisms:

1. Display a Visualforce Page from (or as) a Tab.

2. Display a Visualforce Page within a Standard Page Layout.  Visualforce pages 
   can be added to standard page layouts. To make Visualforce pages available in 
   the page layout editor, set the standard controller of the Visualforce page 
   you are trying to add inline to the page to that object. This standard 
   controller can be both a standard or custom object. However, you can only 
   have one object assigned to the standard controller at a time. 

3. Display a Visualforce Page by Overriding Standard Buttons or Links. Instead 
   of having standard buttons access standard functionality and pages, you can 
   override them to instead invoke your custom Visualforce pages. Simply go to 
   the Buttons and Links page for the object you want to override, and click 
   Edit next to the appropriate button or link. If your standard controller is 
   set properly, you should see the Visualforce page in the override picklist. 

4. Display a Visualforce Page Using Custom Buttons or Links.  Custom links and 
   buttons can be added to standard page layouts, letting you call in to your 
   Visualforce pages. 

5. Display a Visualforce Page as the Target of a Link.  Because each Visualforce 
   page is addressable by a URL, so you can simply link to the it.

// Visualforce - Styling:

We can manage the look and feel for our Visualforce pages using CSS by setting 
appropriate value for the given component's style or styleClass attribute:

<apex:page >
  <apex:outputPanel style="border:2px solid red">
      My Styled Panel
  </apex:outputPanel>
</apex:page>

Inline styles are not ideal for efficient Visualforce pages. Using a style 
class, or reference to a style sheet, will render better performance overall in 
a custom page.

<apex:page showHeader="false" standardStyleSheets="false">
  <apex:styleSheet value="{!$Resource.styles}"/>
  <apex:outputPanel styleClass="border_red">
      My Styled Panel
  </apex:outputPanel>
</apex:page>

In the above code, the $Resource global refers to a static resource with a name 
of 'styles'.  Salesforce allows us to upload static resources to the platform, 
and during this process we can give the resource a name.

In addition to the various discrete types of resources, static resources also 
support structured archive file formats such as zip. 

<apex:page showHeader="true" standardStyleSheets="false">
    <apex:styleSheet value="{!URLFOR($Resource.styles,'styles.css')}"/>
    <apex:outputPanel styleClass="mystyle" layout="block">
        My Styled Panel
    </apex:outputPanel>
</apex:page>

In the above code:

1. The static resource itself is named styles and is referenced through the 
   $Resource global variable.

2. The URLFOR() function provides a mechanism to drill into the structure of the 
   archive for the proper element — styles.css, in this case.

3. The relative reference in the stylesheet for img/mybackground.png is 
   maintained through the blowout of the structure as the archive contains the 
   folder named "img" at it's root and the respective file within it.

4. The resource and its referenced elements are cached by the browser at a 
   versioned URL. 

// Visualforce - PDF File Generation:

The default rendering for Visualforce pages is HTML, but it is also possible to 
specify PDF as the rendering output for easily printing dynamic content. This 
rendering type is controlled through the renderAs attribute on page. The 
following simple page will be converted to PDF format on the server before being 
returned to the browser: 

<apex:page renderAs="pdf" showHeader="false">
  <h1>Hello PDF World!</h1>
</apex:page>

This attribute supports expressions for dynamic determination of the rendering 
format. 

// Visualforce - Using Visualforce as Email Templates:

Email Templates also support Visualforce markup technology to create rich email 
messages. To create an email template using Visualforce, we probably can type 
"Email Template" into the Quick Find box, click on "Email Template", click on 
the "New" button, and select "Visualforce".

Visualforce email templates are designated with the messaging:emailTemplate 
component tag. Additional email-specific components allow for specification of 
plain text and HTML bodies, as well as attachments. Attachments support the PDF 
rendering as well. The following is a basic example of how the same multi-level 
object data can be provided in an email to be sent to a user: 

<messaging:emailTemplate subject="Contacts for {!relatedTo.Name}" 
  recipientType="User" relatedToType="Account">
   <messaging:plainTextEmailBody >
       Account Name: {!relatedTo.name}
       Contact Names: 
    <apex:repeat value="{!relatedTo.Contacts}" var="contact">
        {!contact.name}
    </apex:repeat>
   </messaging:plainTextEmailBody>
   <messaging:attachment renderAs="pdf" filename="contactlist">
       <h1>{!relatedTo.Name}</h1>
       <apex:dataTable value="{!relatedTo.Contacts}" var="contact">
           <apex:column value="{!contact.name}"/>
           <apex:column value="{!contact.phone}"/>            
           <apex:column value="{!contact.email}"/>            
       </apex:dataTable>
   </messaging:attachment>
</messaging:emailTemplate>

Note the following:

1. The standard controller behind this email template provides access to the 
   recipient User and the related Account exactly like a Visualforce page would.

2. The text body of the email is as specified within the 
   messaging:plainTextEmailBody component tags.

3. The attachment component contains markup that will be attached as HTML or as 
   PDF similar to the page mechanism. 

// Visualforce - Mobile:

Visualforce tabs, as described above, can also be flagged as "mobile ready", 
which makes them available for any mobile configuration. Try to edit a 
Visualforce page or tab and look for the "Mobile Ready" check box.

Once added to a user's mobile configuration settings, a capable mobile device 
with the salesforce.com mobile client will include this tab. When selected, it 
launches a live browser connection to show the Visualforce page underlying the 
tab. For example, the following simple page renders the appropriate platform 
image depending upon the device type detected within the c:mobileSample 
component: 

<apex:page showHeader="false">
   <c:mobileSample/>
</apex:page>

The markup for the c:mobileSample component simply displays an image stored 
within a static resource named mobileImages, but determines which image to 
display at runtime based on the browser's reported user agent value as inspected 
in the component's controller. 

<apex:component controller="mobileSampleCon">
   <apex:image value="{!URLFOR($Resource.mobileImages, deviceType + '.jpg')}"/>
</apex:component>

public class mobileSampleCon {

   public String deviceType { get; set; }

   public MobileSampleCon() {
       String userAgent = ApexPages.currentPage().getHeaders().get('USER-AGENT');

       if(userAgent.contains('iPhone')) deviceType = 'iPhone';
       else if(userAgent.contains('BlackBerry')) deviceType = 'BlackBerry';
   }
}

There is also an open source library of Mobile Templates that allow you to build 
engaging enterprise mobile apps with high-impact visual design templates that 
utilize mobile-optimized HTML5 and CSS3. Combine these modular design templates 
with Salesforce Platform Mobile Services and Developer Mobile Packs to view, 
edit and update customer data, view backend reports, find nearby records, and 
more. 

Mobile Templates: https://developer.salesforce.com/en/mobile/services/mobile-templates
// Salesforce - Developer - Visualforce:

Visualforce is a framework for building custom Force.com user interfaces.  It
provides full control of user interface and behavior.  It is created using the
Visualforce markup language.  It can include standard web technologies like
JavaScript, Flash, and CSS.

Visualforce enables developers to extend Salesforce’s built-in features, 
replace them with new functionality, and build completely new apps. Use 
powerful built-in standard controller features, or write your own custom 
business logic in Apex. You can build functionality for your own organization, 
or create apps for sale in the AppExchange.

Salesforce provides a range of ways that you can use Visualforce within your 
organization. You can extend Salesforce’s built-in features, replace them with 
new functionality, and build completely new apps.

We can display a Visualforce Page within a standard page layout. We can extend 
our page layouts by embedding Visualforce pages on them to display completely 
custom content on a standard page.

We can display a Visualforce Page by overriding standard buttons or links.  
Replace built-in functionality in Salesforce by overriding the standard buttons 
and links to go to a Visualforce page instead of the normal page.

We can display a Visualforce Page using custom buttons or links.  Instead of 
overriding the standard features of your Salesforce pages, you can add new 
features to them. Add custom links and buttons that go to Visualforce pages to 
any object’s page layout.

We can link directly to a Visualforce page.  Every Visualforce page has a unique 
URL, so you can simply link to a page. Share the link in other apps, emails, 
embedded in documents, and so on.

Visualforce page is accessible via a URL.

Use Visualforce to create custom mobile apps and add them to Salesforce1 for 
your mobile users.

Things that can be included in a Visualforce page:

1. Visualforce markup language elements
2. Standard web-based content:
   1. HTML
   2. JavaScript (including Ajax) (but we should not)
   3. CSS
   4. Images
   5. Flash
3. Text
4. File-based content
5. Salesforce objects and fields

We can create Visualforce page using:

1. Inline Editor
2. Developer Console
3. Force.com IDE

<apex:page standardController="Account">
  <!-- This is a comment -->
  <h1>Congratulations</h1>
  <p/>
  This is your new page: myNewPage
  <apex:detail/>
</apex:page>

Standard controllers access Force.com objects and actions.  Custom controllers 
use Apex code for new behaviors.

Controllers control the behaviors of your page.

To reference force.com objects and data, use: {! ... }

To display a field: <apex:inputField value="{!Position__c.status__c}"/>

To call an action: <apex:commandButton action="{!save}" value="Save"/>

To execute a formular: <p>Today's date is {! TODAY()}</p>

In the above code, Position__c is a custom object, and status__c is a custom
field in that custom object.  The <apex:inputField> tag render this as a select-
dropdown depending on the number of options that this custom field can accept.  
It also get the label from that custom field.

The action attribute of the <apex:commandButton> above is part of the controller
specified with the <apex:page> tag above.

When we create Visualforce page, it is a page on its own.  We need to have way
to integrate it into our existing application.  For that, we can override 
existing page layout and create a link to our new Visualforce page.  We can also
create custom buttons and links to our Visualforce page.  We can also embed our
new Visualforce page into our existing page layout.

Click on Admin User
Click on Settings
Click on Personal
Click on Advanced User Details
Click on Edit
Check the "Development Mode" check box
Click Save
Click on the Home tab
Change the URL to /apex/HelloWorld
Click on "Create Page ..."
Click on the "HelloWorld" in the lower left corner.

<apex:page standardController="Position_c">
  <b>Hello {! $User.FirstName}</b>
  <apex:form>
    <apex:pageBlock mode="edit">
      <apex:pageBlockSection title="Update Position" columns="3">
        <apex:inputField value="{!Position__c.name}"/>
        <apex:inputField value="{!Position__c.status__c}"/>
        <apex:commandButton action="{!save}" value="Update"/>
      </apex:pageBlockSection>
    </apex:pageBlock>
  </apex:form>
  <apex:detail relatedList="false"/>
  <apex:relatedList list="Job_Applications__r"/>
  <apex:relatedList list="Interviewers__r"/>
</apex:page>

Click Setup
Click on Create -> Objects 
Click on the Positions object
Go down to the "Button, Links, and Actions" section
Click on the Edit link next to View
Select the Visualforce Page radio button
Select the Visualforce page that we just created.  This list only display the 
  list of pages that is associated with this particular class via the
  standardController option or the customController option.
Click Save.

To render a Visualforce page as a PDF, add renderAs="PDF" to the <apex:page> tag.

http://github.com/dohbutz/Intro-to-Visualforce

We can use Visualforce to:

1. Create custom tab
2. Customize the Detail page
3. Create complete web site
4. Create Mobile application

To create a Visualforce page:

1. Click on Setup
2. Drill down on Develop (left hand side under the Build section)
3. Click on Pages.
4. Click on New.

<apex:page controller="clsController">
  <apex:image value="{! $Resource.banner}" width="100%"/>
  <apex:pageBlock title="Nominate Contacts">
    <apex:pageBlockTable value="{!contacts}" var="contact">

    </apex:pageBlockTable>
  </apex:pageBlock>
</apex:page>

public with sharing class clsController {
  public List<Contact> contacts {get; set;}
  public clsController() {
    contacts = [select id,name, phone from contact limit 10];
  }
}

In the above code, <apex:pageBlockTable> tag is a loop.  The value="{!contact"}
attribute reference the "contacts" member variable from the controller which
is a collection or result set coming from the database.  Each record is assigned
to the "contact" variable via the var="contact" attribute.

We can upload static resources (images, JavaScript libraries, etc) to the 
force.com platform.

To completely hide the Salesforce header, add showHeader="false" to the
<apex:page> tag.

<apex:page standardController="Account" extensions="AccountContactListController">
  <!--<img src="{!$Resource.banner}"/>-->
  <apex:form >
    <!-- actionFunction is for calling controller's method -->
    <apex:actionFunction action="{!doQuery}" name="apexDoQuery" reRender="myData"/>

    <!-- Filter Section -->
    <div style="padding: 10px">
      <label>Filter by Last Name:&nbsp;
        <apex:inputText value="{!searchString}" onKeyup="apexDoQuery()"/>
      </label>
    </div>

    <!-- my Page Block -->
    <apex:pageBlock title="Nominate Contacts" id="myData">
      <apex:pageBlockButtons >
        <apex:commandButton action="{!save}" value="Save"/>
      </apex:pageBlockButtons>
      <apex:pageblockTable value="{!contacts}" var="con"> 
        <!-- con in myContactList -->
        <apex:column headerValue="Name">
          <a href="/{!con.Id}">
            <apex:outputField value="{!con.Name}"/>
          </a>
        </apex:column>
        <apex:column value="{!con.Phone}"/>
        <apex:column headerValue="Email" >
          <apex:inputField value="{!con.Email}"/>
        </apex:column> 
        <apex:column headerValue="Nominate" >
          <apex:inputField value="{!con.Nominate__c}"/>
        </apex:column>     
      </apex:pageblockTable>
    </apex:pageBlock>
  </apex:form>
  <style>
        .filterDiv{ padding: 10px; }
        label{ padding: 2px; }
  </style>
</apex:page>

public with sharing class AccountContactListController 
{
    //Global Variables
    public List<Contact> contacts {get;set;}
    public String searchString {get;set;}
    private String accountId; //only use if view on standard controller

    //Constructor for standard page
    public AccountContactListController(ApexPages.StandardController controller) 
    {
        searchString='';
        accountId = controller.getId();
        doQuery();
    }

    //methods for getting list of contacts
    public void doQuery()
    {
        String queryString = '';
        if(searchString != null) //add in % in the query string
            queryString = '%'+searchString+'%';

        //if viewing on standard controller (account), add in filter for accountId
        contacts = [SELECT id, name, email, phone, Nominate__c
                    FROM Contact 
                    WHERE lastname like :queryString
                    AND AccountId = :accountId
                    ORDER BY lastname asc
                    LIMIT 10];
    }

    //save all records that were updated
    public void save() 
    {
        update contacts;
    }

}

<apex:page showHeader="false" controller="ContactListController"> 
  <link rel="stylesheet" href="{!URLFOR($Resource.bootstrap, 
    '/bootstrap/css/bootstrap.css')}"/>
  <link rel="stylesheet" href="{!URLFOR($Resource.bootstrap, 
    '/bootstrap/css/bootstrap-responsive.css')}"/>
  <script src="{!URLFOR($Resource.jQueryZip2,'jquery-1.9.1.js')}"></script>
  <script type="text/javascript" src="{!URLFOR($Resource.bootstrap, 
    '/bootstrap/js/bootstrap.js')}"></script>
  <style>
        label
        {
            color: white;
        }
        label span
        {
            padding: 0px 10px;
        }
        .filterInput
        {
            margin-top: 10px;
        }
        input[type="submit"].btn 
        {
            margin-top: 10px;
        }
        .mySaveBtn
        {
            clear:left;
            width:40px;
            margin: 10px auto;
        }
        body
        { 
            background: url("{!$Resource.background}");
        }
        #wrapper
        {
            margin: 10px auto;
            padding:5px;
            width: 75%;
            background: rgba(60, 58, 65, 0.5);
            border-radius: 10px;
        }
        .table th
        {
            color:white;
        }
        .myName
        {
            color:white;
        }
        .table td, .table th
        {
            border-top: 1px solid rgba(255, 255, 255, 0.3);
        }
        #myTitle{ color:white; text-align:center; font-size:18px; font-weight:bold;}
  </style>
  <div id="wrapper">
    <div id="myTitle">Nominate Your Customers</div>
    <apex:form >
      <!-- actionFunction is for calling controllers method -->
      <apex:actionFunction action="{!doQuery}" name="apexDoQuery" reRender="myData"/>

      <!-- Filter Section -->
      <label class="pull-left">
        <span>Filter by Last Name:</span>
        <apex:inputText styleClass="filterInput" 
          value="{!searchString}" onKeyup="apexDoQuery()"/>
      </label>
      <div class="mySaveBtn">
        <apex:commandButton action="{!save}" value="Save"/>
      </div>

      <!-- my Page Block -->
      <apex:outputPanel id="myData">
        <table class="table">
          <tr>
            <th>Name</th>
            <th>Email</th>
            <th>Nominate</th>
          </tr>
          <apex:repeat value="{!contacts}" var="con"> <!-- con in myContactList -->
            <tr>
              <td nowrap="nowrap" style="color:white !important;">
                <apex:outputField value="{!con.Name}" />
              </td>
              <td>
                <apex:inputField value="{!con.Email}"/>
              </td>
              <td >
                <apex:inputField value="{!con.Nominate__c}"/>
              </td>
            </tr>   
          </apex:repeat>
        </table>
      </apex:outputPanel>
    </apex:form>
  </div>
</apex:page>

<apex:page controller="ContactListSimpleController">
    <apex:image value="{!$Resource.banner2}" width="100%"/>
    <apex:form >
        <apex:pageBlock title="Nominate Contacts">

            <apex:pageBlockButtons >
                <apex:commandButton value="Save" action="{!save}"/>
            </apex:pageBlockButtons>

            <apex:pageBlockTable value="{!contacts}" var="contact">
                <!-- for loop of contact in contacts -->
                <apex:column value="{!contact.name}"/>
                <apex:column value="{!contact.accountid}"/>
                <apex:column value="{!contact.phone}"/>
                <apex:column headerValue="Email">
                    <apex:inputField value="{!contact.email}"/>
                </apex:column>
                <apex:column headerValue="Nominate">
                    <apex:inputField value="{!contact.Nominate__c}"/>
                </apex:column> 
            </apex:pageBlockTable>

        </apex:pageBlock>
    </apex:form>
</apex:page>

public with sharing class ContactListSimpleController
{
    public List<Contact> contacts {get;set;} //global variables

    //constructor
    public ContactListSimpleController()
    {
        contacts = [
            select name, accountid, phone, email, nominate__c 
            from contact limit 10
        ];
    }

    //save method
    public void save()
    {
        update contacts;
    }
}

<apex:page controller="SearchableContactListController">

    <apex:image url="{!$Resource.banner2}" width="100%" />
    <apex:form >
        <!-- actionFunction is for calling controller's method -->
        <apex:actionFunction action="{!doQuery}" name="apexDoQuery" reRender="myData"/>

        <!-- Filter Section -->
        <div class="filterDiv">
            <label>Filter by Last Name:</label>
            <apex:inputText value="{!searchString}" onkeyup="apexDoQuery()"/>
        </div>

        <!-- my Page Block -->
        <apex:pageBlock title="Nominate Contacts" id="myData">
            <apex:pageBlockButtons >
                <apex:commandButton action="{!save}" value="Save"/>
            </apex:pageBlockButtons>
            <apex:pageblockTable value="{!contacts}" var="con">
                <!-- con in myContactList -->
                <apex:column headerValue="Name">
                    <a href="/{!con.Id}">
                        <apex:outputField value="{!con.Name}"/>
                    </a>
                </apex:column>
                <apex:column value="{!con.accountid}"/>
                <apex:column value="{!con.Phone}"/>
                <apex:column headerValue="Email" >
                    <apex:inputField value="{!con.Email}"/>
                </apex:column> 
                <apex:column headerValue="Nominate" >
                    <apex:inputField value="{!con.Nominate__c}"/>
                </apex:column>  
            </apex:pageblockTable>
        </apex:pageBlock>

    </apex:form>

    <style>
        .filterDiv{ padding: 10px; }
        label{ padding: 2px; }
    </style>
</apex:page>

public with sharing class SearchableContactListController {

    //Global Variables
    public List<Contact> contacts {get;set;}
    public String searchString {get;set;}

    //Constructor for stand alone page
    public SearchableContactListController()
    {
        searchString='';
        doQuery();
    }

    //methods for getting list of contacts
    public void doQuery()
    {
        String queryString = '';
        if(searchString != null) //add in % in the query string
            queryString = '%'+searchString+'%';

        contacts = [SELECT id, name, email, phone, accountid, Nominate__c
                    FROM Contact c
                    WHERE lastname like :queryString
                    LIMIT 10];
    }

    //save all records that were updated
    public void save() 
    {
        update contacts;
    }
}

@isTest
private class VisualforceTestClass{

    public static TestMethod void test(){

        Contact c = new Contact(lastname='x');
        insert c;

        ContactListSimpleController clsc = new ContactListSimpleController();

        SearchableContactListController sclc = new SearchableContactListController();
        sclc.doQuery();
        sclc.Save();

        ContactListController clc = new ContactListController();
        clc.doQuery();
        clc.Save();

        ApexPages.StandardController sc = new ApexPages.StandardController(c);
        AccountContactListController aclc = new AccountContactListController(sc);
        aclc.doQuery();
        aclc.Save();
    }

}
// Salesforce - Developer - Visualforce:

<apex:page standardController="Contact" >
    <apex:form >

        <apex:pageBlock title="Edit Contact">

            <apex:pageBlockSection columns="1">
                <apex:inputField value="{!Contact.FirstName}"/>
                <apex:inputField value="{!Contact.LastName}"/>
                <apex:inputField value="{!Contact.Email}"/>
                <apex:inputField value="{!Contact.Birthdate}"/>
            </apex:pageBlockSection>

            <apex:pageBlockButtons >
                <apex:commandButton action="{!save}" value="Save"/>
            </apex:pageBlockButtons>

        </apex:pageBlock>

    </apex:form>
</apex:page>

In the above code, we use Contact as a standardController.  We also use the
<apex:form>, <apex:pageBlock>, <apex:pageBlockSection>, and pageBlockButtons
tags.  This page displays a contact data entry form.

It connects to the Visualforce standard controller, a part of the Visualforce 
framework that provides automatic data access and modification, standard 
actions, and more.  When accessed without a record ID, the page displays a 
blank data entry form. When you click Save, a new record is created from the 
form data.  When accessed with a record ID, the page looks up the data for that 
contact record and displays it in an editable form. When you click Save, your 
changes for the contact are saved back to the database.  Each input field is 
smart about how it presents its value.  The email field knows what a valid 
email address looks like, and displays an error if an invalid email is entered. 
The date field displays a date widget when you click into the field to make 
entering a date easier.  The Save button calls the save action method, one of a 
number of standard actions provided by the standard controller.
// Salesforce - Developer - Visualforce - Creating a Visualforce page:

To create a Visualforce page in the Developer Console:

1. Open the Developer Console under Your Name.  The Developer Console opens in 
   a new window.
2. Click File | New | Visualforce Page.
3. Enter HelloWorld for the name of the new page, and click OK.  A new, blank 
   Visualforce page opens in the Developer Console.
4. In the editor, enter the following: <apex:page>HTML</apex:page>
5. Click File | Save.
6. To see your new page, click Preview. The rendered page opens in a new window.
7. In the editor, add some additional text to your page, and save it.  

The preview window automatically refreshes to reflect your changes when you save 
the page. We’ll leave out the save instruction in the future, but you should save your 
pages in between steps.

Click File | Open to see a list of existing Visualforce pages. Double-click a page to 
open it. You can also open other Salesforce entities, such as Apex classes and 
triggers, Visualforce components, and so on.

Beside using the Developer Console to create Visualforce pages, we can also use
the regular web GUI to create Visualforce page:

1. Click on the Setup link in the top right corner of the screen.
2. Type Visualforce into the Quick Search box.
3. Click on Visualforce Pages
4. Click on New

There are also a number external tools available that can create Visualforce 
page, such as the Force.com IDE plug-in for Eclipse and MavensMate for 
SublimeText.  These tools can connect to your Salesforce organization and be 
used for Visualforce development.
// Salesforce - Developer - Visualforce:

// Using the auto-suggest features of the Developer Console:

When using Developer Console to create Visualforce page, the Developer Console 
can automatically suggest various things such as attributes.  Use auto-suggest 
to quickly add attributes and values to Visualforce component tags.
// Salesforce - Developer - Visualforce:

Setting showHeader="false" is the standard for pages with mostly custom user 
interfaces. The page still includes some Salesforce style sheets, which let you 
match Salesforce choices for fonts, size, and so on. To suppress all Salesforce 
output, add standardStylesheets="false" to remove the styles as well.
// Salesforce - Developer - Visualforce:

// Adding and Composing Components to Form a Page Structure:

We can add components to our Visualforce page and arrange them to build the 
page’s structure.  Follow these steps to add new Visualforce tags to your page, 
and to use them to create a structure for the page.

1. In your HelloWorld page, add a <apex:pageBlock> component below the text 
   “Hello World”.  <apex:pageBlock> is a structured user interface element that 
   groups related items on a page. Use auto-suggest to add it, and set the title 
   attribute to “A Block Title”.

2. Add a <apex:pageBlockSection> component inside the <apex:pageBlock> component. 
   Set the title attribute to “A Section Title”.  <apex:pageBlockSection> is 
   another component that adds structure and hierarchy to a page. When rendered, 
   <apex:pageBlockSection> elements can be collapsed by the user to hide all 
   but the section title.

pageBlock and pageBlockSection can have title.  pageBlockSection is collapsible.  
pageBlockSection is nested inside the pageBlock tag.
// Salesforce - Developer - Visualforce:

Visualforce pages that you want to embed within an object’s page layouts, 
use as object-specific custom actions, or use as mobile cards in Salesforce1 
must use the standard controller for the relevant object.
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License