UI Flashcards

1
Q

Create Visualforce Pages

A
  • Create Visualforce Pages in the Developer Console
  • Create a page using the “quick fix” tool available in Visualforce development mode:

In your browser, enter a URL in the following form: https://yourSalesforceOrgURL/apex/nameOfNewPage, where the value of yourSalesforceOrgURL is the URL used to access your Salesforce org (for example, MyDomainName.my.salesforce.com) and the value of nameOfNewPage is the value you want to give to the Name field on your page definition (example - https://MyDomainName.my.salesforce.com/apex/HelloWorld)
Page names can’t be longer than 40 characters.
Because the page does not yet exist, you are directed to an intermediary page from which you can create your new page. Click Create page nameOfNewPage to create the new page. Both the page Name and Label are assigned the nameOfNewPage value you specified in the URL.

  • Create Pages in Setup:
    From Setup, enter Visualforce Pages, then select Visualforce Pages.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

View created Visualforce Page

A

Once your page has been created, you can access it by clicking Preview (Setup > Visualforce Pages). You can also view it manually by entering a URL in the following form: http://yourSalesforceOrgURL/apex/nameOfNewPage, where the value of yourSalesforceOrgURL is your Salesforce organization’s URL (for example, MyDomainName.my.salesforce.com) and the value of nameOfNewPage is the value of the Name field on your page definition.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Enable Visualforce Development Mode

A

Development mode provides you with:

A special development footer on every Visualforce page that includes the page’s view state, any associated controller, a link to the component reference documentation, and a page markup editor that offers highlighting, find-replace functionality, and auto-suggest for component tag and attribute names.
The ability to define new Visualforce pages just by entering a unique URL.
Error messages that include more detailed stack traces than what standard users receive.
Enable Visualforce Development Mode:
User Profile (Personal settings) > My Personal Information > Advanced User Details: Development Mode checkbox, Show View State in Development Mode checkbox
Show View State in Development Mode checkbox enables the View State tab on the development footer. This tab is useful for monitoring the performance of your Visualforce pages.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Customization of Visualforce integration into Lightning

A

In Salesforce Classic, the default value of the sidebar attribute and showHeader attribute is true. However, in Lightning Experience and the Salesforce mobile app, the value of these attributes is overridden and is always false. There’s no way to suppress the Lightning Experience header.

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Visualforce Expressions

A

Dynamic data is accessed in markup through the use of global variables, calculations, and properties made available by the page’s controller. Together these are described generally as Visualforce expressions. Use expressions for dynamic output or passing values into components by assigning them to attributes.

A Visualforce expression is any set of literal values, variables, sub-expressions, or operators that can be resolved to a single value. Method calls aren’t allowed in expressions.

The expression syntax in Visualforce is:** {! expression }**
The resulting value can be a primitive (integer, string, and so on), a Boolean, an sObject, a controller method such as an action method, and other useful results.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Visualforce Global Variables

A

{! $GlobalName.fieldName }
Use global variables to access and display system values and resources in your Visualforce markup.

For example, Visualforce provides information about the logged-in user in a global variable called $User: {! $GlobalName.fieldName }.
Example:
{!$User.FirstName } {!$User.LastName } {! $User.Username }

Visualforce expressions are case-insensitive, and spaces within the {! … }are ignored. So these expressions all produce the same value:

{!$User.FirstName} {!$USER.FIRSTNAME} {!$user.firstname }

There are nearly two dozen global variables that can be used within Visualforce. They’re useful for getting information about the currently logged in user, as you saw, but also for getting details about the organization ( $Organization), settings ( $Setup), details about custom objects ( $ObjectType), actions available on those objects ( $Action), and so on.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Visualforce Formula Expressions

A

Examples: {!$User.FirstName & ‘ ‘ & $User.LastName}
{! TODAY() + 7}

<p>Tomorrow will be day number {! DAY(TODAY() + 1) }</p>

<p>Let's find a maximum: {! MAX(1,2,3,4,5,6,5,4,3,2,1) } </p>

<p>The square root of 49 is {! SQRT(49) }</p>

<p>Is it true? {! CONTAINS('salesforce.com', 'force.com') }</p>

<p>The year today is {! YEAR(TODAY()) }</p>

Visualforce supports formulas that let you manipulate values.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Visualforce Conditional Expressions

A

Use a conditional expression to display different information based on the value of the expression.
You can do this in Visualforce by using a conditional formula expression, such as IF(). The IF()expression takes three arguments.
Example:

<p>{! IF( CONTAINS('salesforce.com','force.com'), 'Yep', 'Nope') }</p>

<p>{! IF( DAY(TODAY()) < 15, 'Before the 15th', 'The 15th or after') }</p>

({! IF($User.isActive, $User.Username, ‘inactive’) })

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Visualforce: Accessing Data with a Standard Controller

A

Every standard controller includes a getter method that returns the record specified by the id query string parameter in the page URL. This method allows the associated page markup to reference fields on the context record by using {!object} syntax, where object is the lowercase name of the object associated with the controller. For example, a page that uses the Account standard controller can use {!account.name} to return the value of the name field on the account that is currently in context.

For the getter method to succeed, the record specified by the id query string parameter in the URL must be of the same type as the standard controller. For example, a page that uses the Account standard controller can only return an account record.

As with queries in the Lightning Platform API, you can use merge field syntax to retrieve data from related records:
You can traverse up to five levels of child-to-parent relationships. For example, if using the Contact standard controller, you can use {!contact.Account.Owner.FirstName} (a three-level child-to-parent relationship) to return the name of the owner of the account record that is associated with the contact.
You can traverse one level of parent-to-child relationships. For example, if using the Account standard controller, you can use {!account.Contacts} to return an array of all contacts associated with the account that is currently in context.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Visualforce: Associating a Standard Controller with a Visualforce Page

A

To associate a standard controller with a Visualforce page, use the standardController attribute on the <apex:page> tag and assign it the name of any Salesforce object that can be queried using the Lightning Platform API.</apex:page>

For example, to associate a page with the standard controller for a custom object named MyCustomObject, use the following markup:

<apex:page>
</apex:page>

When you use the standardController attribute on the <apex:page> tag, you cannot use the controller attribute at the same time.</apex:page>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Visualforce: Using Standard Controller Actions

A

Action methods perform logic or navigation when a page event occurs, such as when a user clicks a button, or hovers over an area of the page. Action methods can be called from page markup by using {! } notation in the action parameter of one of the following tags:

<apex:commandButton> creates a button that calls an action
<apex:commandLink> creates a link that calls an action
<apex:actionPoller> periodically calls an action
<apex:actionSupport> makes an event (such as “onclick”, “onmouseover”, and so on) on another, named component, call an action
<apex:actionFunction> defines a new JavaScript function that calls an action
<apex:page> calls an action when the page is loaded
The following table describes the action methods that are supported by all standard controllers. You can associate these actions with any Visualforce component that includes an action attribute.
**save, quicksave, edit, delete, cancel, list**

For example, the following page allows you to update an account. When you click Save, the save action is triggered on the standard controller, and the account is updated.
<apex:page>
<apex:form>
<apex:pageBlock>
<apex:pageBlockButtons>
<apex:commandButton></apex:commandButton>
</apex:pageBlockButtons>
<apex:pageBlockSection>
<apex:inputField></apex:inputField>
<apex:inputField></apex:inputField>
<apex:inputField></apex:inputField>
<apex:inputField></apex:inputField>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>

Command buttons and links that are associated with save, quicksave, edit, or delete actions in a standard controller are only rendered if the user has the appropriate permissions. Likewise, if no particular record is associated with a page, command buttons and links associated with the edit and delete actions are not rendered.
</apex:page></apex:actionFunction></apex:actionSupport></apex:actionPoller></apex:commandLink></apex:commandButton>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Visualforce: Validation Rules and Standard Controllers

A

If a user enters data on a Visualforce page that uses a standard controller, and that data causes a validation rule error, the error can be displayed on the Visualforce page. If the validation rule error location is a field associated with an <apex:inputField> component, the error displays there. If the validation rule error location is set to the top of the page, use the <apex:pageMessages> or <apex:messages> component within the <apex:page> to display the error.</apex:page></apex:messages></apex:pageMessages></apex:inputField>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Visualforce: Styling Pages that Use Standard Controllers

A

Any page associated with a standard controller automatically inherits the style that is used for standard Salesforce pages associated with the specified object.
You can override the styling of a page that uses a standard controller with the tabStyle attribute on the <apex:page> tag. For example, the following page uses the Account standard controller, but renders a page that highlights the Opportunities tab and uses the Opportunity tab's yellow coloring:</apex:page>

<apex:page>
</apex:page>

To use the styling associated with MyCustomObject:

<apex:page>
</apex:page>

To use the styling associated with a custom Visualforce tab, set the attribute to the name (not label) of the tab followed by a double-underscore and the word tab. For example, to use the styling of a Visualforce tab with the name Source and a label Sources, use:

<apex:page>
</apex:page>

Alternatively, you can override standard controller page styles with your own custom stylesheets and inline styles.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Visualforce: Checking for Object Accessibility

A

If a user has insufficient privileges to view an object, any Visualforce page that uses a controller to render that object will be inaccessible. To avoid this error, you should ensure that your Visualforce components will only render if a user has access to the object associated with the controller.

You can check for the accessibility of an object like this:
{!$ObjectType.objectname.accessible}
This expression returns a true or false value.
For example, to check if you have access to the standard Lead object, use the following code:
{!$ObjectType.Lead.accessible}
For custom objects, the code is similar:
{!$ObjectType.MyCustomObjectc.accessible}

To ensure that a portion of your page will display only if a user has access to an object, use the render attribute on a component. For example, to display a page block if a user has access to the Lead object, you would do the following:

<apex:page>
<apex:pageBlock>
<p>This text will display if you can see the Lead object.</p>
</apex:pageBlock>
</apex:page>

It is good practice to provide an alternative message if a user cannot access an object. For example:

<apex:page>
<apex:pageBlock>
<p>This text will display if you can see the Lead object.</p>
</apex:pageBlock>
<apex:pageBlock>
<p>Sorry, but you cannot see the data because you do not have access to the Lead object.</p>
</apex:pageBlock>
</apex:page>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Visualforce: Standard List Controllers

A

Standard list controllers allow you to create Visualforce pages that can display or act on a set of records. Examples of existing Salesforce pages that work with a set of records include list pages, related lists, and mass action pages. Standard list controllers can be used with the following objects:
Account
Asset
Campaign
Case
Contact
Contract
Idea
Lead
Opportunity
Order
Product2
Solution
User
Custom objects

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Visualforce: Associating a Standard List Controller with a Visualforce Page

A

Using a standard list controller is very similar to using a standard controller. First you set the standardController attribute on the <apex:page> component, then you set the recordSetVar attribute on the same component.
**<apex:page>**</apex:page></apex:page>

When you use the standardController attribute on the <apex:page> tag, you can’t use the controller attribute at the same time.</apex:page>

The recordSetVar attribute not only indicates that the page uses a list controller, it sets the variable name of the record collection. This variable can be used to access data in the record collection.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Visualforce: List View - Access Records with Expression Syntax

A

When using a standard list controller, the returned records automatically sort on the first column of data defined by the current view. When using an extension or custom list controller, you can control the sort method.
As with queries in the Lightning Platform API, you can use expression language syntax to retrieve data from related records. As with standard controllers, you can traverse up to five levels of child-to-parent relationships and one level of parent-to-child relationships.

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Visualforce: List View - Access Records with IDs

A

In a typical page interaction, a user selects records from a listview before navigating to a page, and Visualforce sends them to the controller. You can also specify records manually by setting selected records directly on to the controller.

The standard list controller is based on the StandardSetController Apex class. Use the method ApexPages.StandardSetController.setSelected() to set the list of records from your Apex controller.
*public with sharing class MyControllerExtension {
private ApexPages.StandardSetController setController;

public MyControllerExtension(ApexPages.StandardSetController setController) {
    this.setController = setController;
    
    Account [] records = [SELECT Id, Name FROM Account LIMIT 30];
    setController.setSelected(records);
} }* The standard list controller is based on the StandardSetController Apex class. To retrieve a list of records assigned to the list controller, use the method ApexPages.StandardSetController.setSelected().

In the MyControllerExtension’s constructor, make a SOQL request to select the ID and Name from the Account object and limit the first 30 results. Then, definesetController.setSelected(records) so that the records are selected on page load.
A standard list controller can return up to 10,000 records. Custom controllers can work with larger results sets.

It’s also possible to pass a list of record IDs into a URL by including them as multiple query parameters. For example, a URL that has three Account IDs looks like: /apex/pageName?ids=001xx00account1&ids=001xx00account2&ids=001xx00account3.

Some browsers have a hard limit on the length of a URL. If your URL has too many IDs, then there is a greater chance of reaching that limit, causing your page to misbehave. Instead of manually including IDs in a URL string, it’s better to set the selected records on to the controller.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Visualforce: Standard List Controller Actions

A

Action methods can be called from page markup by using {! } notation in the action parameter of one of the following tags:

<apex:commandButton> creates a button that calls an action
<apex:commandLink> creates a link that calls an action
<apex:actionPoller> periodically calls an action
<apex:actionSupport> makes an event (such as “onclick”, “onmouseover”, and so on) on another, named component, call an action
<apex:actionFunction> defines a new JavaScript function that calls an action
<apex:page> calls an action when the page is loaded
Actions: save, quicksave, list, cancel,
for page navigations - first, last, next, previous
Example:
*<apex:page>
<apex:form>
<apex:selectList>
<apex:selectOptions></apex:selectOptions>
</apex:selectList>
<apex:commandButton></apex:commandButton>
</apex:form>
</apex:page>*
</apex:page></apex:actionFunction></apex:actionSupport></apex:actionPoller></apex:commandLink></apex:commandButton>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Visualforce: List View - Pagination

A

By default, a list controller returns 20 records on the page. To control the number of records displayed on each page, use a controller extension to set the pageSize.

<apex:page>
<apex:pageBlock>
<apex:form>
<apex:pageBlockSection>
<apex:dataList>
{!a.name}
</apex:dataList>
</apex:pageBlockSection>
<apex:panelGrid>
<apex:commandLink>Previous</apex:commandlink>
<apex:commandLink>Next</apex:commandlink>
</apex:panelGrid>
</apex:form>
</apex:pageBlock>
</apex:page>
</apex:commandLink></apex:commandLink></apex:panelGrid></apex:form></apex:pageBlock></apex:page>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Visualforce: Using List Views with Standard List Controllers - Filter

A

Many Salesforce pages include list views that allow you to filter the records displayed on the page. For example, on the opportunities home page, you can choose to view a list of only the opportunities you own by selecting My Opportunities from the list view drop-down. On a page that is associated with a list controller, you can also use list views.

For example, to create a simple list of accounts with a list view, create a page with the following markup:

<apex:page>
<apex:pageBlock>
<apex:form>
<apex:panelGrid>
<apex:outputLabel></apex:outputLabel>
<apex:selectList>
<apex:actionSupport></apex:actionSupport>
<apex:selectOptions></apex:selectOptions>
</apex:selectList>
</apex:panelGrid>
<apex:pageBlockSection>
<apex:dataList>
{!a.name}
</apex:dataList>
</apex:pageBlockSection>
</apex:form>
</apex:pageBlock>
</apex:page>

This page is associated with the standard account controller and the <apex:selectlist> component is populated by {!listviewoptions}, which evaluates to the list views the user can see. When the user chooses a value from the drop-down list, it is bound to the filterId property for the controller. When the filterId is changed, the records available to the page changes, so, when the <apex:datalist> is updated, that value is used to update the list of records available to the page.</apex:datalist></apex:selectlist>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

Visualforce: Editing Records with List Controllers

A

You can edit a set of records using list controllers, too. For example, if you create a page with the following markup:

<apex:page>
<apex:form>
<apex:pageBlock>
<apex:pageMessages></apex:pageMessages>
<apex:pageBlockButtons>
<apex:commandButton></apex:commandButton>
</apex:pageBlockButtons>
<apex:pageBlockTable>
<apex:column></apex:column>
<apex:column>
<apex:inputField></apex:inputField>
</apex:column>
<apex:column>
<apex:inputField></apex:inputField>
</apex:column>
</apex:pageBlockTable>
</apex:pageBlock>
</apex:form>
</apex:page>

(you see a page that allows you to update and save the Stage and Close Date on your opportunities)
Command buttons and links that are associated with save, quicksave, or edit actions in a list controller are not rendered if the user does not have the appropriate permissions. Likewise if no particular record is associated with a page, command buttons and links associated with the edit actions are not rendered.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

Visualforce: Standard Controller - Display Fields from Related Records

A

Use dot notation to display data from related records.

For example, while viewing the object details for Account, you might have noticed that the Account object has a field called Account Owner, and that its type is Lookup(User). In other words, this field has a relationship to a User record. By clicking the Account Owner field label link, you’ll discover its Field Name is Owner.

The Owner relationship represents a User. And, if from Setup you go to Object Manager | User | Fields & Relationships, you’ll find that User has a Name field. Let’s use this information to display it.

In the body of the page, before the account name, add the following line.

Account owner: {! Account.Owner.Name } <br></br>
The dot notation ( Account.Owner.Name) indicates that you want to traverse the relationship between the records. You know that Account.Owner indicates the Owner field of the account record. The extra Name at the end indicates that the owner field isn’t a simple field representing a string, but a relationship to another record (it’s a Lookup(User)), and that you’d like to get the record represented by the value of the Owner field (it’s a User record), and display the Name field on that record.

23
Q

Visualforce - Display Individual Fields

A

Use <apex:outputField> to display individual fields from a record.</apex:outputField>

<apex:outputField></apex:outputField>

<apex:outputField></apex:outputField>

<apex:outputField></apex:outputField>

<apex:outputField></apex:outputField>

The four fields are added to the page. But the formatting perhaps isn’t what you expected. The field values are displayed all on one line, without labels, and without other formatting. That’s not what we want, and it’s quite a contrast to the <apex:detail> and <apex:relatedList> components, which automatically use the platform styling. By itself, the <apex:outputField> only outputs the field’s value. But when you wrap it in <apex:pageBlock> and <apex:pageBlockSection> components, its behavior changes quite a bit.
Wrap the <apex:outputField> lines with <apex:pageBlock> and <apex:pageBlockSection>components, so that your markup looks like this.</apex:pageBlockSection></apex:pageBlock></apex:outputField></apex:pageBlockSection></apex:pageBlock></apex:outputField></apex:relatedList></apex:detail>

24
Q

Visualforce: controller extension

A

A controller extension is an Apex class that extends the functionality of a standard or custom controller. Use controller extensions when:
You want to leverage the built-in functionality of a standard controller but override one or more actions, such as edit, view, save, or delete.
You want to add new actions.
You want to build a Visualforce page that respects user permissions. Although a controller extension class executes in system mode, if a controller extension extends a standard controller, the logic from the standard controller does not execute in system mode. Instead, it executes in user mode, in which permissions, field-level security, and sharing rules of the current user apply.

Although custom controllers and controller extension classes execute in system mode and thereby ignore user permissions and field-level security, you can choose whether they respect a user’s organization-wide defaults, role hierarchy, and sharing rules by using the with sharing keywords in the class definition. For information, see “Using the with sharing, without sharing, and inherited sharing Keywords”

25
Q

Visualforce: custom controller

A

A custom controller is an Apex class that implements all of the logic for a page without leveraging a standard controller. Use custom controllers when you want your Visualforce page to run entirely in system mode, which does not enforce the permissions and field-level security of the current user.

26
Q

Visualforce: Building a Custom Controller

A

A custom controller is an Apex class that uses the default, no-argument constructor for the outer, top-level class. You cannot create a custom controller constructor that includes parameters.

To create a custom controller:
Create new Apex Class.
public class MyController {

private final Account account;

public MyController() {
    account = [SELECT Id, Name, Site FROM Account 
               WHERE Id = :ApexPages.currentPage().getParameters().get('id')];
}

public Account getAccount() {
    return account;
}

public PageReference save() {
    update account;
    return null;
} } The following Visualforce markup shows how the custom controller above can be used in a page:

<apex:page>
<apex:form>
<apex:pageBlock>
You belong to Account Name: <apex:inputField></apex:inputField>
<apex:commandButton></apex:commandButton>
</apex:pageBlock>
</apex:form>
</apex:page>

The custom controller is associated with the page because of the controller attribute of the <apex:page> component.</apex:page>

As with standard controllers and controller extensions, custom controller methods can be referenced with {! } notation in the associated page markup. In the example above, the getAccount method is referenced by the <apex:inputField> tag's value attribute, while the <apex:commandButton> tag references the save method with its action attribute.</apex:commandButton></apex:inputField>

Like other Apex classes, all custom controllers run in system mode. Consequently, the current user’s credentials are not used to execute controller logic, and the user’s permissions and field-level security do not apply.

You can choose whether a custom controller respects a user’s organization-wide defaults, role hierarchy, and sharing rules by using the with sharing keywords in the class definition.

A custom controller can also be used to create new records. For example:

public class NewAndExistingController {

public Account account { get; private set; }

public NewAndExistingController() {
    Id id = ApexPages.currentPage().getParameters().get('id');
    account = (id == null) ? new Account() : 
        [SELECT Name, Phone, Industry FROM Account WHERE Id = :id];
}

public PageReference save() {
    try {
        upsert(account);
    } catch(System.DMLException e) {
        ApexPages.addMessages(e);
        return null;
    }
    //  After successful Save, navigate to the default view page
    PageReference redirectSuccess = new ApexPages.StandardController(Account).view();
    return (redirectSuccess);
} } The following Visualforce markup shows how the custom controller above can be used in a page:

<apex:page>
<apex:form>
<apex:pageBlock>
<apex:pageMessages></apex:pageMessages>
<apex:pageBlockSection>
<apex:inputField></apex:inputField>
<apex:inputField></apex:inputField>
<apex:inputField></apex:inputField>
</apex:pageBlockSection>
<apex:pageBlockButtons>
<apex:commandButton></apex:commandButton>
</apex:pageBlockButtons>
</apex:pageBlock>
</apex:form>
</apex:page>

27
Q

Visualforce: Building a Controller Extension

A

A controller extension is any Apex class containing a constructor that takes a single argument of type ApexPages.StandardController or CustomControllerName, where CustomControllerName is the name of a custom controller you want to extend.

The following class is a simple example of a controller extension:

public class myControllerExtension {

private final Account acct;

// The extension constructor initializes the private member
// variable acct by using the getRecord method from the standard
// controller.
public myControllerExtension(ApexPages.StandardController stdController) {
    this.acct = (Account)stdController.getRecord();
}

public String getGreeting() {
    return 'Hello ' + acct.name + ' (' + acct.id + ')';
} } The following Visualforce markup shows how the controller extension from above can be used in a page:

<apex:page>
{!greeting} <p></p>
<apex:form>
<apex:inputField></apex:inputField> <p></p>
<apex:commandButton></apex:commandButton>
</apex:form>
</apex:page>

The extension is associated with the page using the extensions attribute of the <apex:page> component.</apex:page>

As with all controller methods, controller extension methods can be referenced with {! } notation in page markup. In the example above, the {!greeting} expression at the top of the page references the controller extension’s getGreeting method.

Because this extension works in conjunction with the Account standard controller, the standard controller methods are also available. For example, the value attribute in the <apex:inputField> tag retrieves the name of the account using standard controller functionality. Likewise, the <apex:commandButton> tag references the standard account save method with its action attribute.</apex:commandButton></apex:inputField>

Multiple controller extensions can be defined for a single page through a comma-separated list. This allows for overrides of methods with the same name. For example, if the following page exists:

<apex:page>
<apex:outputText></apex:outputText>
</apex:page>

with the following extensions:
public class ExtOne {
public ExtOne(ApexPages.StandardController acon) { }

public String getFoo() {
    return 'foo-One';
} } public class ExtTwo {
public ExtTwo(ApexPages.StandardController acon) { }

public String getFoo() {
    return 'foo-Two';
} } The value of the <apex:outputText> component renders as foo-One. Overrides are defined by whichever methods are defined in the “leftmost” extension, or, the extension that is first in the comma-separated list. Thus, the getFoo method of ExtOne is overriding the method of ExtTwo.

Like other Apex classes, controller extensions run in system mode. Consequently, the current user’s credentials are not used to execute controller logic, and the user’s permissions and field-level security do not apply. However, if a controller extension extends a standard controller, the logic from the standard controller does not execute in system mode. Instead, it executes in user mode, in which the permissions, field-level security, and sharing rules of the current user apply.

You can choose whether a controller extension respects a user’s organization-wide defaults, role hierarchy, and sharing rules by using the with sharing keywords in the class definition.

28
Q

Visualforce: Controller Methods

A

Visualforce markup can use the following types of controller extension and custom controller methods:
Action
Getter
Setter
Action Methods
Action methods perform logic or navigation when a page event occurs, such as when a user clicks a button, or hovers over an area of the page. Action methods can be called from page markup by using {! } notation in the action parameter of one of the following tags:

<apex:commandButton> creates a button that calls an action
<apex:commandLink> creates a link that calls an action
<apex:actionPoller> periodically calls an action
<apex:actionSupport> makes an event (such as “onclick”, “onmouseover”, and so on) on another, named component, call an action
<apex:actionFunction> defines a new JavaScript function that calls an action
<apex:page> calls an action when the page is loaded
For example, in the sample page in Building a Custom Controller, the controller's save method is called by the action parameter of the <apex:commandButton> tag.
**Getter Methods**
Getter methods return values from a controller. Every value that is calculated by a controller and displayed in a page must have a corresponding getter method, including any Boolean variables. For example, in the sample page in Building a Custom Controller, the controller includes a getAccount method. This method allows the page markup to reference the account member variable in the controller class with {! } notation. The value parameter of the <apex:inputField> tag uses this notation to access the account, and dot notation to display the account's name. Getter methods must always be named getVariable.

Important

It’s a best practice for getter methods to be idempotent, that is, to not have side effects. For example, don’t increment a variable, write a log message, or add a new record to the database. Visualforce doesn’t define the order in which getter methods are called, or how many times they might be called in the course of processing a request. Design your getter methods to produce the same outcome, whether they are called once or multiple times for a single page request.

**Setter Methods**
Setter methods pass user-specified values from page markup to a controller. Any setter methods in a controller are automatically executed before any action methods.

For example, the following markup displays a page that implements basic search functionality for Leads. The associated controller includes getter and setter methods for the search box input, and then uses the search text to issue a SOSL query when the user clicks Go!. Although the markup doesn’t explicitly call the search text setter method, it executes before the doSearch action method when a user clicks the command button.
While a getter method is always required to access values from a controller, it’s not always necessary to include a setter method to pass values into a controller. If a Visualforce component is bound to an sObject that is stored in a controller, the sObject's fields are automatically set if changed by the user, as long as the sObject is saved or updated by a corresponding action method. An example of this behavior is shown in the sample page in Building a Custom Controller.

Setter methods must always be named setVariable.

Important

It’s a best practice for setter methods to be idempotent, that is, to not have side effects. For example, don’t increment a variable, write a log message, or add a new record to the database. Visualforce doesn’t define the order in which setter methods are called, or how many times they might be called in the course of processing a request. Design your setter methods to produce the same outcome, whether they are called once or multiple times for a single page request.
</apex:inputField></apex:commandButton></apex:page></apex:actionFunction></apex:actionSupport></apex:actionPoller></apex:commandLink></apex:commandButton>

29
Q

Visualforce: Controller Class Security

A

Like other Apex classes, you can specify whether a user can execute methods in a custom controller or controller extension class based on the user’s profile.

If you’ve installed a managed package in your org, you can set security only for the Apex classes in the package that are declared as global or for classes that contain methods declared as webService.

If users have the Author Apex permission, they can access all Apex classes in the associated organization, regardless of the security settings for individual classes.

Permission for an Apex class is checked only at the top level. For example, class A calls class B. User X has a profile that can access class A but not class B. User X can execute the code in class B, but only through class A; user X cannot invoke class B directly. Likewise, if a Visualforce page uses a custom component with an associated controller, security is only checked for the controller associated with the page. The controller associated with the custom component executes regardless of permissions.

To set Apex class security from the class list page:

From Setup, enter Apex Classes in the Quick Find box, then select Apex Classes.
Next to the name of the class that you want to restrict, click Security.
Select the profiles that you want to enable from the Available Profiles list and click Add, or select the profiles that you want to disable from the Enabled Profiles list and click Remove.
Click Save.
To set Apex class security from the class detail page:

From Setup, enter Apex Classes in the Quick Find box, then select Apex Classes.
Click the name of the class that you want to restrict.
Click Security.
Select the profiles that you want to enable from the Available Profiles list and click Add, or select the profiles that you want to disable from the Enabled Profiles list and click Remove.
Click Save.

30
Q

Visualforce custom controllers limits, Large Sets of Data

A

Visualforce custom controllers and controller extensions are subject to Apex governor limits. Additionally, Visualforce iteration components, such as <apex:pageBlockTable> and <apex:repeat>, are limited to a maximum of 1,000 items in the collection they iterate over.</apex:repeat></apex:pageBlockTable>

Sometimes your Visualforce pages may need to work with or display larger sets of data, but not need to make modifications to that data; for example, if you are providing custom reporting and analytics. Visualforce offers developers a “read-only mode”, which relaxes the limit on the number of rows which can be queried in one request, and increases the limit on the number of collection items which can be iterated over within the page.

You can specify read-only mode either for an entire page or, with certain limitations, on individual components or methods.

You can only iterate over large sets of data if you specify read-only mode for the entire page.

Normally, queries for a single Visualforce page request may not retrieve more than 50,000 rows. In read-only mode, this limit is relaxed to allow querying up to 1,000,000 rows.

In addition to querying many more rows, the readOnly attribute also increases the maximum number of items in a collection that can be iterated over using components such as <apex:dataTable>, <apex:dataList>, and <apex:repeat>. This limit increased from 1,000 items to 10,000.</apex:repeat></apex:dataList></apex:dataTable>

31
Q

Visualforce: Setting Read-Only Mode for an Entire Page

A

To enable read-only mode for an entire page, set the readOnly attribute on the <apex:page> component to true.
For example, here is a simple page that will be processed in read-only mode:</apex:page>

<apex:page>
<p>Here is a statistic: {!veryLargeSummaryStat}</p>
</apex:page>

While Visualforce pages that use read-only mode for the entire page can’t use data manipulation language (DML) operations, they can call getter, setter, and action methods which affect form and other user interface elements on the page, make additional read-only queries, and so on.

32
Q

Visualforce: Setting Read-Only Mode for Controller Methods

A

Visualforce controller methods can, with some important limitations, use the Apex ReadOnly annotation, even if the page itself isn’t in read-only mode.
Visualforce controller methods with the @ReadOnly annotation automatically take advantage of read-only mode. However, restrictions on the @ReadOnly annotation means that, for Visualforce controller methods, a read-only method must also have the @RemoteAction annotation. The @RemoteAction annotation requires that the method be:
Either global or public
static
Enabling read-only mode by using the @ReadOnly annotation must be done on the top level method call. If the top level method call doesn’t have the@ReadOnly annotation, the normal restrictions on maximum queried rows are enforced for the entire request, even if secondary methods are annotated with @ReadOnly.

Using the @ReadOnly annotation on a controller method allows you to retrieve a larger collection of records as the result of a Visualforce expression. However, it doesn’t increase the maximum number of items in a collection for iteration components. If you want to iterate over larger collections of results, you need to enable read-only mode for the entire page.

33
Q

Considerations for Creating Custom Controllers and Controller Extensions

A

Note the following considerations when creating controller extensions and custom controllers:
* Unless a class has a method defined as webService, custom extension and controller classes and methods are generally defined as public. If a class includes a web service method, it must be defined as global.
* Use sets, maps, or lists when returning data from the database. This makes your code more efficient because the code makes fewer trips to the database.
* The Apex governor limits for Visualforce controller extensions and custom controllers are the same as the limits for anonymous block or WSDL methods.
* If you are building a custom controller or controller extension, be careful that you do not inadvertently expose sensitive data that would normally be hidden from users. Consider using the with sharing keywords on class definitions to enforce permissions. Also be careful using Web services, which are secured as top-level entry points by the profile, but execute in the system context once they are initiated.
* Apex methods and variables are not instantiated in a guaranteed order.
* You can’t use data manipulation language (DML) operations in a “getxxx” method in a controller.
* You can’t use data manipulation language (DML) operations in a constructor method in a controller.
* You can’t use the @future annotation in a “getxxx” or “setxxx” method in a controller, or in the constructor for a controller.
* Primitive Apex data types such as String or Integer are passed by value to the component’s controller.
Non-primitive Apex data types such as lists and sObjects are passed by reference to component’s controller. This means that if component’s controller changes the name of an account, the changes are available in page’s controller.
* If your org uses person accounts
When referencing an account record’s name field with a custom controller using the <apex:inputField> component you must specify isPersonAccount in your query. If you create a new account and set name, the record will be a business account. If you create a new account and set lastname, it will be a person account.
As a best practice, create a custom name formula field that will render properly for both person accounts and business accounts, then use that field instead of the standard field in your Visualforce pages.
* If you plan on including your Visualforce page in a Salesforce AppExchange package, in your controller or controller extension, you cannot explicitly reference fields that exist only in a person account.</apex:inputField>

34
Q

Visualforce: Order of Execution in a Visualforce Page

A

When a user views a Visualforce page, instances of the controller, extensions, and components associated with the page are created by the server. The order in which these elements are executed can affect how the page is displayed to the user.

To fully understand the order of execution of elements on a Visualforce page, you must first understand the page’s lifecycle–that is, how the page is created and destroyed during the course of a user session. The lifecycle of a page is determined not just by the content of the page, but also by how the page was requested. There are two types of Visualforce page requests:
A get request is an initial request for a page either made when a user enters an URL or when a link or button is clicked that takes the user to a new page.
A postback request is made when user interaction requires a page update, such as when a user clicks on a Save button and triggers a save action.

35
Q

Visualforce: Order of Execution for Visualforce Page Get Requests

A

A get request is an initial request for a page either made when a user enters an URL or when a link or button is clicked that takes the user to a new page.
In the diagram above the user initially requests a page, either by entering a URL or clicking a link or button. This initial page request is called the get request.

  • The constructor methods on the associated custom controller or controller extension classes are called, instantiating the controller objects.
  • If the page contains any custom components, they are created and the constructor methods on any associated custom controllers or controller extensions are executed. If attributes are set on the custom component using expressions, the expressions are evaluated after the constructors are evaluated.
  • The page then executes any assignTo attributes on any custom components on the page. After the assignTo methods are executed, expressions are evaluated, the action attribute on the <apex:page> component is evaluated, and all other method calls, such as getting or setting a property value, are made.</apex:page>
  • If the page contains an <apex:form> component, all of the information necessary to maintain the state of the database between page requests is saved as an encrypted view state. The view state is updated whenever the page is updated.</apex:form>
  • The resulting HTML is sent to the browser. If there are any client-side technologies on the page, such as JavaScript, the browser executes them.

As the user interacts with the page, the page contacts the controller objects as required to execute action, getter, and setter methods.

Once a new get request is made by the user, the view state and controller objects are deleted.
Note

If the user is redirected to a page that uses the same controller and the same or a proper subset of controller extensions, a postback request is made. When a postback request is made, the view state is maintained.

If the user interaction requires a page update, such as when the user clicks a Save button that triggers a save action, a postback request is made. For more information on postback requests, see Order of Execution for Visualforce Page Postback Requests.

36
Q

Visualforce Controllers

UI

A

A developer can either use a standard controller provided by Lightning Platform, or add custom controller logic with a class written in Apex:
A standard controller consists of the same functionality and logic that is used for a standard Salesforce page. For example, if you use the standard Accounts controller, clicking a Save button in a Visualforce page results in the same behavior as clicking Save on a standard Account edit page. If you use a standard controller on a page and the user doesn’t have access to the object, the page displays an insufficient privileges error message. Resolve this error by checking the user’s accessibility for an object and displaying components appropriately. A standard list controller enables you to create Visualforce pages that can display or act on a set of records. Examples of existing Salesforce pages that work with a set of records include list pages, related lists, and mass action pages.
A custom controller is a class written in Apex that implements all of a page’s logic, without leveraging a standard controller. If you use a custom controller, you can define new navigation elements or behaviors, but you must also reimplement any functionality that was already provided in a standard controller. Like other Apex classes, custom controllers execute entirely in system mode, in which the object and field-level permissions of the current user are ignored. You can specify whether a user can execute methods in a custom controller based on the user’s profile - with sharing keywords.
A controller extension is a class written in Apex that adds to or overrides behavior in a standard or custom controller. Extensions allow you to use the functionality of another controller while adding your own custom logic. Standard controllers execute in user mode, in which the permissions, field-level security, and sharing rules of the current user are enforced.
Extending a standard controller allows you to build a Visualforce page that respects user permissions. Although the extension class executes in system mode, the standard controller executes in user mode. As with custom controllers, you can specify whether a user can execute methods in a controller extension based on the user’s profile.

37
Q

What is a Visualforce Page?

UI

A

Developers can use Visualforce to create a Visualforce page definition. A page definition consists of two primary elements:
Visualforce markup
A Visualforce controller
Visualforce Markup
Visualforce markup consists of Visualforce tags, HTML, JavaScript, or any other Web-enabled code embedded within a single <apex:page> tag. The markup defines the user interface components that are included on the page, and the way they appear.
**Visualforce Controllers**
A Visualforce controller is a set of instructions for what happens when a user interacts with components specified in associated Visualforce markup. One type of interaction is when a user clicks a button or link. Controllers also provide access to the data displayed in a page, and can modify component behavior.</apex:page>

38
Q

Create Visualforce pages

UI

A

Visualforce is a framework that allows developers to build custom user interfaces that can be hosted natively on Lightning Platform. The Visualforce framework includes a tag-based markup language similar to HTML. It also has a set of server-side “standard controllers” that make basic database operations, such as queries and saves, simple to perform.
Developers create Visualforce pages by composing components, HTML, and optional styling elements. Visualforce can integrate with any standard web technology or JavaScript framework to allow for a more animated and rich user interface.

39
Q

Where Can Visualforce Pages Be Used?

UI

A

Developers can use Visualforce pages to:
Override standard buttons, such as the New button for accounts, or the Edit button for contacts
Override tab overview pages, such as the Accounts tab home page
Define custom tabs
Embed components in detail page layouts
Create dashboard components or custom help pages
Customize, extend, or integrate the sidebars in the Salesforce console (custom console components)
Add navigation menu items and actions in the Salesforce mobile app

40
Q

Lightning Web Components: Simple Component Creation

A

You create (1) a JavaScript file, (2) an HTML file, and optionally (3) a CSS file.
HTML provides the structure for your component.
JavaScript defines the core business logic and event handling.
CSS provides the look, feel, and animation for your component.
Those are the essential pieces of your component.

Here’s a very simple Lightning web component that displays “Hello World” in an input field.
HTML:
~~~

<template>
<input value={message}></input>
</template>

Javascript:

import { LightningElement } from ‘lwc’;
export default class App extends LightningElement {
message = ‘Hello World’;
}
~~~
CSS:
~~~
input {
color: blue;
}
~~~
At minimum, all you really need is an HTML file and a JavaScript file with the same name in the same folder (also with a matching name). You deploy those to an org with some metadata and you’re good to go. Salesforce compiles your files and takes care of the boilerplate component construction for you automatically.

41
Q

LWC: HTML

A

Lightning web component HTML files all include the template tag. The template tag contains the HTML that defines the structure of your component. Let’s look at the HTML for a simplified version of the productCard component from the ebikes repo.

Follow along by pasting these examples in VS Code.

  1. Create a project by selecting SFDX: Create Project from the Command Palette in VS Code. Accept the standard template and give it the project name bikeCard.
  2. Under force-app/main/default, right-click the lwc folder and select SFDX: Create Lightning Web Component.
  3. Enter app for the name of the new component. Press Enter and then press Enter again to accept the default force-app/main/default/lwc.
  4. Say you want to display data, but you know it can take some time to load. You don’t want the user wondering what’s up. You can use lwc:if and lwc:else conditional directives within your template to determine which visual elements are rendered.
  5. Let’s explore using a base Lightning web component. And of course, there are lots of components, including field types, display controllers, navigation items, and more. All of them are listed in the Component Reference.
  6. app.html
    ~~~

<template>
<template lwc:if={ready}>
<div>
<div>Name: {name}</div>
<div>Description: {description}</div>
<lightning-badge label={material}></lightning-badge>
<lightning-badge label={category}></lightning-badge>
<div>Price: {price}</div>
<div><img src={pictureUrl} alt={name}/></div>
</div>
</template>

<template>
<div>Loading…</div>
</template>

</template>
~~~
The identifiers in the curly braces {} are bound to the fields of the same name in the corresponding JavaScript class.
5. app.js:
~~~
import { LightningElement } from ‘lwc’;
export default class App extends LightningElement {
name = ‘Electra X4’;
description = ‘A sweet bike built for comfort.’;
category = ‘Mountain’;
material = ‘Steel’;
price = ‘$2,700’;
pictureUrl = ‘https://s3-us-west-1.amazonaws.com/sfdc-demo/ebikes/electrax4.jpg’;
ready = false;
connectedCallback() {
setTimeout(() => {
this.ready = true;
}, 3000);
}
}
~~~
6. The export statement defines a class that extends the LightningElement class. As a best practice, the name of the class usually matches the file name of the JavaScript class, but it’s not a requirement.

42
Q

LWC: Component Build Structure

A

A component simply needs a folder and its files with the same name. They’re automatically linked by name and location.
~~~
–app
—-app.js
—-app.html
—-app.css
~~~
All Lightning web components have a namespace that’s separated from the folder name by a hyphen. For example, the markup for the Lightning web component with the folder name app in the default namespace c is <c-app>.</c-app>

However, the Salesforce platform doesn’t allow hyphens in the component folder or file names. What if a component’s name has more than one word, like “mycomponent”? You can’t name the folder and files my-component, but we do have a handy solution.

Use camel case to name your component myComponent. Camel case component folder names map to kebab-case in markup. In markup, to reference a component with the folder name myComponent, use <c-my-component>.</c-my-component>

For example, the LWC Samples repo has the viewSource folder containing the files for the viewSource component. When the hello component references the viewSource component in HTML, it uses c-view-source.

43
Q

LWC Module

A

Lightning Web Components uses modules (built-in modules were introduced in ECMAScript 6) to bundle core functionality and make it accessible to the JavaScript in your component file. The core module for Lightning web components is lwc.

Begin the module with the import statement and specify the functionality of the module that your component uses.

The import statement indicates the JavaScript uses the LightningElement functionality from the lwc module.
LightningElement is the base class for Lightning web components, which allows us to use connectedCallback().
The connectedCallback() method is one of our lifecycle hooks. You’ll learn more about lifecycle hooks in the next section. For now, know that the method is triggered when a component is inserted in the document object model (DOM). In this case, it starts the timer.
~~~
// import module elements
import { LightningElement} from ‘lwc’;
// declare class to expose the component
export default class App extends LightningElement {
ready = false;
// use lifecycle hook
connectedCallback() {
setTimeout(() => {
this.ready = true;
}, 3000);
}
}
~~~

44
Q

LWC: Lifecycle Hooks

A

Lightning Web Components provides methods that allow you to “hook” your code up to critical events in a component’s lifecycle. These events include when a component is:

Created
Added to the DOM
Rendered in the browser
Encountering errors
Removed from the DOM

A lifecycle hook is a callback method that triggers at a specific phase of a component instance’s lifecycle. With LWC, you can use the following lifecycle hooks.
constructor() - method fires when a component instance is created
The constructor flows from parent to child, which means that it fires in the parent first
The first statement must be super() with no parameters. This call establishes the correct prototype chain and value for this. Always call super() before touching this.
Don’t use a return statement inside the constructor body, unless it is a simple early-return (return or return this).
Don’t use the document.write() or document.open() methods.
Don’t inspect the element’s attributes and children, because they don’t exist yet.
Don’t inspect the element’s public properties, because they’re set after the component is created.
connectedCallback() - lifecycle hook fires when a component is inserted into the DOM. This hook flows from parent to child.
Establish communication with the current document or container and coordinate behavior with the environment.
Perform initialization tasks, such as fetch data, set up caches, or listen for events
Subscribe and Unsubscribe from a Message Channel.
Navigate to different page types, like records and list views using the lightning/navigation module.
Work with third-party web components.
disconnectedCallback() - lifecycle hook fires when a component is removed or hidden from the DOM
renderedCallback() - lifecycle hook is unique to Lightning Web Components. Use it to perform logic after a component has finished the rendering phase. This hook flows from child to parent.
After a component is connected and rendered, any changes or mutations to its state trigger the rerendering process:
The component gets marked as “dirty.”
A microtask rerender the component gets enqueued.

For example, components get rerendered when a property’s value changes and that property is used either directly in a component template or indirectly in the getter of a property that is used in a template.
A component is usually rendered many times during the lifespan of an application. To use this hook to perform a one-time operation, use a boolean field like hasRendered to track whether renderedCallback() has been executed. The first time renderedCallback() executes, perform the one-time operation and set hasRendered = true. If hasRendered = true, don’t perform the operation.
It’s best to add event listeners declaratively in an HTML template. However, if you do need to add an event listener to a template element programmatically, do it in renderedCallback(). You don’t need to remove the listener. If a listener is added to the same element repeatedly, the browser ignores the duplicates.
errorCallback() hook is unique to Lightning Web Components. Implement it to create an error boundary component that captures errors in all the descendent components in its tree. Like a JavaScript catch{} block, errorCallback() captures errors that occur in lifecycle hooks or during an event handler declared in an HTML template. You can code the error boundary component to log stack information and render an alternative view to tell users what happened and what to do next.
~~~
<!-- boundary.html -->

<template>
<template lwc:if={error}>
<error-view error={error} info={stack}></error-view>
</template>

<template>
<healthy-view></healthy-view>
</template>

</template>
// boundary.js
import { LightningElement } from “lwc”;
export default class Boundary extends LightningElement {
error;
stack;
errorCallback(error, stack) {
this.error = error;
}
}
~~~

45
Q

LWC: Decorators

A

Decorators are often used in JavaScript to modify the behavior of a property or function.

To use a decorator, import it from the lwc module and place it before the property or function.
~~~
import { LightningElement, api } from ‘lwc’;
export default class MyComponent extends LightningElement{
@api message;
}
~~~
Examples of Lightning Web Components decorators include:

@api: Marks a field as public. Public properties define the API for a component. An owner component that uses the component in its HTML markup can access the component’s public properties. All public properties are reactive, which means that the framework observes the property for changes. When the property’s value changes, the framework reacts and rerenders the component.
Note
Field and property are almost interchangeable terms. A component author declares fields in a JavaScript class. An instance of the class has properties. To component consumers, fields are properties. In a Lightning web component, only fields that a component author decorates with @api are publicly available to consumers as object properties.

@track: Tells the framework to observe changes to the properties of an object or to the elements of an array. If a change occurs, the framework rerenders the component. All fields are reactive. If the value of a field changes and the field is used in a template—or in the getter of a property used in a template—the framework rerenders the component. You don’t need to decorate the field with @track. Use @track only if a field contains an object or an array and if you want the framework to observe changes to the properties of the object or to the elements of the array. If you want to change the value of the whole property, you don’t need to use @track.
Note
Prior to Spring ‘20, you had to use @track to mark fields (also known as private properties) as reactive. You’re no longer required to do that. Use @track only to tell the framework to observe changes to the properties of an object or to the elements of an array. Some legacy examples may still use @track where it isn’t needed, but that’s OK because using the decorator doesn’t change the functionality or break the code.

@wire: Gives you an easy way to get and bind data from a Salesforce org.

46
Q

LWC: Component Configuration File

A

Component configuration file with the extension .js-meta.xml. This file provides metadata for Salesforce, including the design configuration for components intended for use in Lightning App Builder.
Required:
apiVersion binds the component to a Salesforce API version.
isExposed ( true or false) If isExposed is false, the component isn’t exposed to Lightning App Builder or Experience Builder.
To allow the component to be used in Lightning App Builder or Experience Builder, set isExposed to true and define at least one <target>, which is a type of Lightning page.
Optional:
**targets** specify which types of Lightning pages the component can be added to in the Lightning App Builder.
**targetConfigs** let you specify behavior specific to each type of Lightning page, including things like which objects support the component.
~~~
<?xml version="1.0" encoding="UTF-8" ?></target>

<LightningComponentBundle>
<apiVersion>57.0</apiVersion>
<isExposed>true</isExposed>
<masterLabel>Product Card</masterLabel>
<targets>
<target>lightning\_\_AppPage</target>
<target>lightning\_\_RecordPage</target>
<target>lightning\_\_HomePage</target>
<target>lightningCommunity\_\_Page</target>
</targets>
<targetConfigs>
<targetConfig>
<objects>
<object>Product\_\_c</object>
</objects>
</targetConfig>
</targetConfigs>
</LightningComponentBundle>

~~~

47
Q

LWC: Displaying a Component in an Org

A

You have two options for displaying a Lightning web component in the UI.

  1. Set the component to support various flexipage types (home, record home, and so on) then add it to a flexipage using the Lightning App Builder. This is the simplest approach and the one you follow in this unit.
  2. You can also create a tab which points to an Aura component containing your Lightning web component. You can see the required pieces in the repo.
    Wrapper Components
    Tabs
    Visibility Settings
    Default application configuration file
48
Q

LWC: Deploy Your Files

A

Now, you need to deploy the component files to your org.

  1. Authenticate with your org using SFDX: Authorize an Org from the Command Palette in VS Code. When prompted, accept the Project Default and press Enter to accept the default alias. If prompted to allow access, click Allow.
  2. Right-click on the force-app/main/default folder and select SFDX: Deploy This Source to Org.
49
Q

LWC: Allow Ebike Images to Display

A

The images we are using are hosted on an Amazon AWS site. In order to allow the images to display in our app we need to add the URL to the Trusted URLs list.

  1. To open your org, use SFDX: Open Default Org from the Command Palette in VS Code.
  2. In Setup, enter trusted urls in the Quick Find box and then select Trusted URLs.
  3. Click New Trusted URL.
    For API Name enter ebikes.
    For URL enter https://s3-us-west-1.amazonaws.com.
    For Description enter Allow ebike images to display.
    Leave Active selected.
    Make sure img-src (images) is selected.
  4. Click Save.
50
Q

LWC: Create a New Page for Your Component

A

Since we set up our component configuration file to enable the use of the component in Lightning App Builder, use the UI to create an app and add your component to it.

  1. To open your org, use SFDX: Open Default Org from the Command Palette in VS Code.
  2. In Setup, enter Lightning App Builder in the Quick Find box and then select Lightning App Builder.
    Click New.
    Select App Page and click Next.
    Give it the label Bike Card and click Next.
    Select One Region and click Done.
    In Lightning App Builder, scroll down the Components list until you see your Bike Card component.
  3. Drag your Bike Card component to the top of the page layout until the bike appears.
    Click Save.
    Click Activate.
    Keep Activate for all users selected. And, optionally, change the name or icon for your app.
    Click Save. You’re asked to add your page to navigation menus, but you don’t need to. You can still get to your page in this environment.
    Click Skip and Save.
    Click Back to exit the Lightning App Builder.
  4. From the App Launcher (), find and select Bike Card.
    Open it and see your component working in the UI.
51
Q

LWC: Events Up, Properties Down

A
  1. The c-todo-item child component dispatches an event to the parent c-todo-app component. For example, the child can pass an event object to the parent when a user clicks a button so the parent can handle the event and change the current page.
  2. The c-todo-app parent component passes a property or invokes a method in the child component. For example, the parent can set a text value in a child component, or invoke a method in the child component.
52
Q

LWC: Passing Information Up

A

Information can be passed up using events and event listeners.

The child component dispatches the event and the parent component listens for it. Dispatching the event includes creating an event object the child can pass to the parent component. The parent has a handler to respond to the event.

For example, a child component like this one contains a nextHandler() method that creates a simple event object using CustomEvent() and dispatches the event type ‘next’ when the user clicks a Next button.
Event types can be any string but should conform to the DOM event standard of no uppercase letters, no spaces, and use underscores to separate words if necessary.
~~~
// todoItem.js
import { LightningElement } from ‘lwc’;

nextHandler() {
this.dispatchEvent(new CustomEvent(‘next’));
}
}
~~~
The parent component listens for the event with the inline event handler prefixed with ‘on’(onnext).
~~~
<!-- todoApp.html -->

<template>
<c-todo-item onnext={nextHandler}></c-todo-item>
</template>

And passes the event object to an event handler.

// todoApp.js
import { LightningElement } from ‘lwc’;
export default class TodoApp extends LightningElement {

nextHandler(){
this.page = this.page + 1;
}
}
~~~

53
Q

LWC: Passing Information Down

A

Information can be passed down using public properties and public methods.

You can make a component property public by prefacing it with the @api decorator. Then, set the public property by an external component.

For example, if the c-todo-item child component has the following:
~~~
// todoItem.js
import { LightningElement, api } from ‘lwc’;
export default class TodoItem extends LightningElement {
@api itemName;
}
~~~
Set the value from the parent with the following:
~~~
<!-- todoApp.html -->

<template>
<c-todo-item></c-todo-item>
</template>

Notice that the **itemName** variable gets set using the kebab case attribute **item-name**. Property names in JavaScript are in camel case while HTML attribute names are in kebab case (dash-separated) to match HTML standards. The item-name attribute in markup maps to the itemName JavaScript property.

Public properties are great solutions for passing down primitive values, simple objects, and arrays.

Also, you can use getters & setters to execute some logic when properties are get or set. And remember, annotate them with the @api decorator to make them public for other components.

Similarly, you can create public methods that are callable from a parent component. Create a public method in the child component by defining it with the @api decorator, then call it from the parent component.

Let's say that we have a child component like this one

// videoPlayer.js
import { LightningElement, api } from ‘lwc’;
export default class VideoPlayer extends LightningElement {
@api play() {
// Play music!
}
}
~~~
When the c-video-player component is included in a parent component, we can invoke the method from the parent component like this:
~~~
// methodCaller.js
import { LightningElement } from ‘lwc’;
export default class MethodCaller extends LightningElement {
handlePlay() {
this.template.querySelector(‘c-video-player’).play();
}
}
~~~
We defined a method handlePlay() that fires the event. Then we use the querySelector() DOM method to search for a DOM element called c-video-player and invoke its public method.

54
Q

LWC: Handling Events in HTML

A

So our selector app needs to handle one type of event—the user clicking a tile. When this happens, the detail component should re-render with the information from the related tile. You can handle events in HTML (add an event listener in the template) or JavaScript (write an event listener function). We recommend using the HTML approach, as follows.

Each tile component listens for the user click because the tile component’s HTML (tile.html) contains an onclick event listener.
~~~

<template>
<div>
<a onclick={tileClick}>
<div>{product.fields.Name.value}</div>
<img class="product-img" src={product.fields.Picture_URL\_\_c.value} alt={product.fields.Name.value}/>
</a>
</div>
</template>

When a user clicks one of the tile instances in the UI, the onclick listener calls the handler function tileClick in the tile.js JavaScript file.

import { LightningElement, api } from ‘lwc’;
export default class Tile extends LightningElement {
@api product; tileClick() {
const event = new CustomEvent(‘tileclick’, {
// detail contains only primitives
detail: this.product.fields.Id.value
});
// Fire the event from c-tile
this.dispatchEvent(event);
}
}
~~~