Mi primera Visualforce

This entry will talk about how to start working with Visualforce and Apex. We can find thousand of blogs in English that talk about this topic, however it is more difficult to find information in Spanish. Because of that, this entry will be in my home language so it will try to help Salesforce newbies in my country.

Esta será la primera de una serie de entradas que hablarán sobre Visualforce y Apex. Escribir una única entrada contando todo lo que me gustaría compartir, podría llegar a ser un post difícil de seguir, ó incluso llegar a aburrirte cerrando la ventana antes de terminar, y eso es lo que quiero evitar.

Aunque la entrada está escrita en Español, seguiré usando los términos ingleses por si tu entorno está en ese idioma.

Comencemos por el principio. Una vez que ya tienes tu entorno (org) Salesforce te ofrece ya algunos objetos que llamamos Standard. Dependiendo de la organización que tengas, podrás acceder a unos u otros, pero en principio tendrás acceso por lo menos a Accounts y Opportunities, así que vamos a utilizar esto dos objetos para los casos prácticos.

Cómo puedes leer en esta entrada, Salesforce se basa en el patrón MVC – Modelo Vista – Controlador. Cuando un usuario interactúa con una página, cualquier acción se manda al controlador el cual se encarga de ejecutar el proceso que la acción necesita con la ayuda del Modelo, y cuando éste finaliza, devuelve a la página el resultado para que lo pueda mostrar. Esto se puede hacer de dos formas, utilizando la funcionalidad Standard y la Custom. Recuerda estas dos palabras porque vamos a hacer referencia a ellas en muchos sitios.

  • ¿Qué significa Standar? Todo aquello que Salesforce te ofrece y puedes utilizar sin añadir una sola línea de código.
  • ¿Qué significa Custom? Si lo que Salesforce te ofrece no es lo que necesitas, lo puedes modificar. Para ello Salesforce te ofrece la posibilidad de hacerlo con sólo clicks de ratón, ó usando Apex y Visualforce.

Todo objeto en Salesforce, ya sea Standard ó Custom (el que creas tú con clicks de ratón) ofrece una vista que puedes utilizar en tu aplicación. Este es un ejemplo de un registro del objeto Account.

Account Record

Esta vista se puede modificar sin una línea de código. ¿Cómo? Edita el Page Layout del objeto hasta conseguir el look and feel que desees.

  • Si es un objeto Standar, cómo Account, ve a Setup | App Setup | Customize |  | Page Layout
  • Si lo has creado tú, es decir, es un objeto Custom, ve a Setup | App Setup | Create | Objects . En esta página, selecciona tu objeto y busca la sección Page Layout

Pero como hemos dicho anteriormente, puede que necesites algo más que ordenar los campos en el Page Layout del objeto.

Para ello crearemos una página visualforce que llamaremos accountview ya que nos servirá para mostrar los datos de la cuenta en modo lectura.

Esta página la enlazaremos con un controlador, y al igual que antes, todo objeto, Standard y Custom tiene su propio Controlador Standard y para usarlo, sólo tenemos que indicar el API name del object que vamos a usar. Posteriormente añadiremos una cuantas secciones con los tags pageBlock (para definir la cabecera la página) y pageBlockSection (nos ayuda a definir una sección) NOTA: podemos añadir tantos bloques y secciones en nuestra página, aunque lo más normal suele tener un único bloque con múltiples secciones.

<!-- accountview -->
<apex:page standardController="Account">
    <apex:form>
        <apex:pageBlock title="Vista Cuenta">
            <apex:pageBlockSection title="Campos Cuenta">
            </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>
</apex:page>     

¿Cómo lo visualizamos en nuestro entorno? Simplemente tendremos que añadir a la URL /apex/, en nuestro caso: https://c.eu2.visual.force.com/apex/accountview y este es el resultado: Captura de pantalla 2015-02-08 a las 14.06.29 Nuestro siguiente paso será añadir campos a la sección Campos Cuenta utilizando el tag outputField. Vamos a crear una página con una apariencia similar a la que nos ofrece Salesforce, pero este ejemplo te puede ayudar a empezar a buscar cómo conseguir el look and feel que realmente quieres. Revisa los links que ofrezco para saber más de los tags que utilizamos en estos ejemplos. Todos ofrecen distintos atributos para personalizar la vista de la página.

<!-- accountview -->
<apex:page standardController="Account">
    <apex:form>
        <apex:pageBlock title="Vista Cuenta">
            <apex:pageBlockSection title="Campos Cuenta">
                <apex:outputField value="{!account.name}"/>
                <apex:outputField value="{!account.site}"/>
                <apex:outputField value="{!account.type}"/>
                <apex:outputField value="{!account.accountNumber}"/>
            </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Y si volvemos a refrescar la página, vemos como en la sección Campos Cuenta aparece lo que hemos añadido, el Nombre, Tipo, Site y Número de Cuenta.

Captura de pantalla 2015-02-08 a las 14.13.08

Viendo esta imagen nos pueden surgir dos dudas.

  1. ¿Por qué el nombre de los campos viene en inglés? Porque estamos usando el controlador Standard de objeto Account, y la llamada account. traerá la etiqueta que hemos definido para ese campo. Mi entorno está en inglés, de ahí el obtener Account Name en vez de Nombre de Cuenta.
  2. ¿Por qué sólo veo la etiqueta de los campos y no el valor? Para poder mostrar los valores, debemos indicarle qué cuenta quiero mostrar. Salesforce asigna un identificador único (15 ó 18 caracteres) a todos sus registro. Es lo que llamaremos Id. Si añadimos ese id al final de la URL, le estamos diciendo a Salesforce que queremos ver la información relacionada a ese registro.
    1. ¿Cómo obtenemos este Id? Muy fácil, si abrimos el registro que queremos, pero usando su vista Standard, la URL nos lo proporciona.

Captura de pantalla 2015-02-08 a las 15.03.03

Después, podemos usar ese Id en nuestra nueva URL quedando así: https://c.eu2.visual.force.com/apex/accountview?id=001b000000Cw7X8 

Captura de pantalla 2015-02-08 a las 15.06.23

Podría seguir contándoos más cosas sobre las páginas Visualforce, pero creo que por hoy os he dado bastante información. En futuros post partiremos de este ejemplo para complicar la personalización de esta página.

Mi recomendación antes del próximo post:

  1. Lee y asimila cómo funciona el Modelo Vista Controlador de Salesforce.
  2. Familiarízate con los objetos Standard, su campos, sus Page Layout, etc.
  3. Crea algún objeto custom por ti mimo.
  4. Crea tu primera página Visualforce usando el Controlador Standard.
    1. Investiga los tags de hoy:
      1. apex:page
      2. apex:form
      3. apex:pageBlock
      4. apex:pageBlockSection
      5. apex:outputField

Hasta la próxima!!

Salesforce Actions

Have you ever tried to look for Salesforce Actions in google? Unless you are completely sure what you are looking for, you can be lost reading many entries that talk about different features.

This new post will cover these points and also show examples using them.

  1. Global Actions variables
  2. Action attributes on Visualforce pages
  3. Chatter Actions
  4. Quick Actions
  5. Invocable Actions with APIs

Global variables help you to show general information about the current user and the organization. They are used on Visualforce pages, with the syntax {$GlobalVariable.Value}

But here, we will focus on the Action one, that allows you to refer Standard Actions related to an object like create, edit, update or delete. For instance, this piece of code will show a link in a page that goes to a New Account Standard UI page:

<apex:page>
    <apex:outputLink value="{!URLFOR($Action.Account.New)}">
        Create New Account
    </apex:outputLink>
</apex:page>

We can continue talking about actions on visualforce pages. When we want to do something after clicking on a button, we must define an action there. How? Just adding the action attribute on the tag. For instance, bellow code is a visualforce page that allows you create a new Account record after entering its Name and clicking on the save button that the tag <apex:commandButton> shows.

<apex:page standardController="Account">
    <apex:form >
        <apex:pageBlock >
            <apex:pageBlockButtons >
                <apex:commandButton value="Save Account" action="{!save}"/>
            </apex:pageBlockButtons>
            <apex:pageBlockSection >
                <apex:inputField value="{!Account.Name}"/>
            </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Remember that in order to show this page you only need to add /apex/<yourpagename> to the url:

 https://<instance>.visual.force.com/apex/<yourpagename>

And this is an example of the result:

Captura de pantalla 2015-03-20 a las 12.41.02

Chatter Actions allow you to do something on an object via chatter. What does it mean? On Chatter, apart from the common actions like Comment, Link, Post, etc, we can create some others in order to perform a new action quickly. As you can see on Salesforce help, there are different actions, and here, I will create a custom action related to the Account standard object.

Tip: remember to have chatter enabled

Steps are:

1. Go to Setup | App Setup | Customize | Accounts | Buttons, Links and Actions and create a new Action in order to create an Opportunity related to the Account

2. Include in the Page Layout those fields that you want to populate during the Opportunity creation

3. Add the new Quick Action into your chatter post.

These images shows above steps:

Captura de pantalla 2015-03-20 a las 13.04.30

4. Open your Account and select the new Quick Action.

Captura de pantalla 2015-03-20 a las 13.13.28

5. Populate Opportunity fields with the information and click save

6. A new Opportunity and a chatter post on Account record are created

Captura de pantalla 2015-03-20 a las 13.14.37

Like previous point, Quick Actions will allow you to perform an action faster than usual in Salesforce. One of the main differences is that Quick Actions help you defining a global action in the org and you will be able to run it from your User chatter post instead of just the post related to a record.

Salesforce already provides Quick Actions for Standard objects, so my action will allow me to create a new custom object record, Trip Request.

Tip: remember to have chatter enabled

Steps are:

1. Go to Setup | App Setup | Create | Global Actions | Actions In a similar way as before, define the new action.

2. Include in the Page Layout those fields that you want to populate during the Trip Request creation

3. Add the new Quick Action into the chatter post.

4. In order to run it, you just need to go to your chatter feed:

Captura de pantalla 2015-03-20 a las 13.26.38

or you can also run it from your SF1 mobile app

Captura de pantalla 2015-03-20 a las 13.30.15

5. Populate Trip Request fields with the information and click save

6. A new Trip Request and a chatter post related to your user record are created

Captura de pantalla 2015-03-20 a las 13.37.20

If someone talk about Invocable Actions, we could think that is something more difficult than what it is actually.

As you can see in the help, via REST API we are able to get all actions that we can find in the org and can be called by API.

Tip: bellow examples are run via Salesforce Workbench

An easy example is to execute this line on Workbench:

/services/data/v33.0/actions

Tip: It is available only via REST API 32.0 onwards

What do we get? All actions, custom and standard one.

Captura de pantalla 2015-03-20 a las 14.06.03Workbench also allows us to navigate across the options, and in this way we can see how under custom we can find the 2 actions we have created on above sections:

The one related to Account that creates Opportunities:

Captura de pantalla 2015-03-20 a las 14.07.11And the Quick Action that creates Trip Requests:

Captura de pantalla 2015-03-20 a las 14.06.18