Tag: Controller

  • Salesforce Lightning Web Components Developer Guide Chapter 2: Markup Basics

    Salesforce Lightning Web Components Developer Guide Chapter 2: Markup Basics

    Here is the second article in our series, where we delve into the LWC basics. In the previous article, we discussed the basic principles and structure of LWC components. Today we will talk about LWC markup.

    First of all, what is LWC markup? LWC is a component-based development model where each component consists of two main parts: markup (HTML) and controller (JavaScript). Markup defines how the component is displayed on the page, while JavaScript defines the component’s behavior. In this article, we won’t discuss FrontEnd development but will only explore a few aspects of LWC markup.

    So, how does the interaction between markup and JavaScript in LWC work? There are several ways.

    Let’s start by understanding the use of directives. Directives are special HTML attributes that tell Lightning Web Components what to do with an element. Directives are used in markup to pass information to JavaScript. For example, the change directive tells LWC which JavaScript function to call when the value of an input field changes.

    The concept of directives in LWC is that we can use HTML attributes with special names instructing the component on what to do with a particular element. This allows for the change in the behavior and display of the component based on the values passed through these attributes.

    Directives for Conditional Elements Rendering

    “lwc:if”, “lwc:elseIf”, and “lwc:else” – these directives are used for conditional rendering of elements. For example, we can use “lwc:if” to display elements on the page only if a certain condition is met. For example:

    <template> 
         <template lwc:if={showGreeting}> 
              <p>Hello, World!</p> 
         </template> 
    </template>

    In this example, if the showGreeting variable has a value of true, the <p> element will be displayed on the page.

    It’s important to note that when you use “lwc:if” in a template tag, it means that all content within that tag will be added to the DOM when the specified condition is met and removed from the DOM when the condition is not met. For example:

    <template lwc:if={shouldRender}> 
         <p>This text will be added to the DOM only if shouldRender is true.</p> 
    </template>

    In this example, if the shouldRender variable has a value of true, the <p> element will be added to the DOM and displayed on the page. If the value of shouldRender is false, the <p> element will be removed from the DOM and will not be displayed on the page.

    On the other hand, you can also use the CSS hidden attribute, for example, the standard slds-hidden. This means the element remains in the DOM but becomes invisible to the user. For example:

    <div class=”slds-hidden”> 
         <p>This text will be hidden if shouldRender is false.</p> 
    </div>

    In this example, the <div> element and the <p> element will be added to the DOM and will remain there even if we don’t see the element. It will only be hidden from the user.

    dont miss out iconDon’t forget to check out: Understanding Decorators and Lifecycle Hooks in Lightning Web Components (LWC)

    So, when you use “lwc:if”, elements are added and removed from the DOM according to the current state of the variable, and when you use CSS, the element remains in the DOM but can be hidden using the hidden attribute. Consider these features when developing your components. For example, you may prefer “lwc:if” in cases where you want to display data from an object on your markup that will be formed in JavaScript after certain user actions. When using CSS, this element will enter the DOM and try to get data from an object that is still undefined at that moment, which will result in an error.

    So, using “lwc:if” and CSS to hide elements from the user can be helpful in various cases, depending on the component’s needs. Both approaches can be used for conditional rendering of elements on the page; however, they have different approaches to manipulating the DOM, which can affect the efficiency and performance of the component.

    It’s also worth noting that there is a directive “if:true”, but Salesforce does not recommend using them as they plan to discontinue their support and eventually remove them in the future.

    Directives for Iterating in Markup “for:each”

    Next, let’s look at “for:each”. This is a directive in LWC that allows repeating one or more HTML elements for each element in an array or object in a list. This directive is useful for displaying lists of data on the page and other needs, such as when the same part of the page can be repeated several times – we can build a basic small component and dynamically call it the required number of times from the parent.

    Using the “for:each” directive consists of two steps:

    1. Assign a variable in the template representing each element of the array or object.

    2. Specify which template element should be repeated for each element of the array or object.

    Here’s an example of using the “for:each” directive to display a list of items:

    JavaScript

    @track listItems= [ {Id: 1, Name: 'John Doe'}, {Id: 2, Name: 'Jane Smith'}, {Id: 3, Name: 'Bob Johnson'} ]; 
         HTML <template> <ul> 
              <template for:each={listItems} for:item="item"> 
                   <li key={item.id}>{item.name}</li>
              </template> 
         </ul> 
    </template>

    In this example, we use the for:each directive to repeat the <li> HTML element for each element in the listItems array. The for:item variable specifies which template variable will represent each array element.

    In addition, we use the key attribute to specify a unique identifier for each element. This helps to maintain the state of elements when the data list changes.

    Also, the “for:each” directive can be used with objects. In this case, the “for:key” directive is used instead of the “key” attribute to specify the field that contains a unique identifier for each object.

    <template> <ul> 
         <template for:each={objectList} for:item="key"> 
               <li for:key={key}>{objectList[key]}</li> 
               </template> 
         </ul> 
    </template>

    In this example, we use the “for:each” directive to iterate over the HTML element <li> for each key in the “objectList” object.

    You can also use the “for:each” directive with nested lists, where an array contains objects that, in turn, contain arrays.

    <template> 
         <ul> 
              <template for:each={listItems} 
                  for:item="item"> 
                       <li key={item.id}> 
                       {item.name} 
                       <ul> 
                  <template for:each={item.subitems} 
                  for:item="subitem"> 
                  <li key={subitem.id}>{subitem.name}</li> 
              </template> 
              </ul> 
         </li> 
         </template> 
         </ul> 
    </template>

    In this example, we use “the for each” directive twice – to iterate over the list of parent items and the list of nested elements for each parent item. We also use the “key” attribute for each item to maintain the state of items when the data list changes.

    The “for:each” directive allows you to use conditions to display items in the list. For example, in the following example, we display only the items in the list that have “isSelected” set to true:

    <template> 
         <ul> 
              <template for:each={listItems} 
                   for:item="item"> 
              <template lwc:if={item.isSelected}> 
         <li key={item.id}>{item.name}</li> 
         </template> 
              </template> 
         </ul> 
    </template>

    In this example, we use the “lwc:if” directive within a template that is used with the “for:each” directive. This allows us to display only those list elements for which the “isSelected” property equals true.

    So, the “for:each” directive is a powerful tool in LWC that makes it easy to display data lists on a page and allows you to use conditions to display specific list elements.

    Event Directives in Lightning Web Components

    Event directives in LWC enable you to add event handlers to elements in your component. When a specific event occurs, such as a button click, text input, or loss of focus, the registered handler is called, allowing you to perform certain actions or change the component’s state.

    <template> 
         <lightning-button onclick={handleClick}>Click me!</lightning-button> 
    </template>

    In this example, we add an event handler, “handleClick,” which is called when a user clicks the button. This is one of the most common event directives, but there are many event directives available in LWC, each with its unique features. Event directives can also depend on the type of HTML tag you are using. While we won’t delve into all of them in detail here, it’s recommended to refer to the documentation for a list of all available lightning tags for LWC and their detailed descriptions, including some special event directives.

    Here are some tips for using event directives effectively:

    • Use clear and informative event handler names: Give your event handlers names that clearly indicate what they do. For example, use “handleInputChange” or “handleButtonClick” instead of generic names like “handleEvent” or “onEvent.”

    • Separate logic: Create separate functions to handle different events to keep your component easy to understand and maintain.

    • Consider performance: If you’re working with many elements with event handlers, you may need to address performance concerns. Try to minimize unnecessary event handlers or optimize their performance if possible.

    • Use documentation: Consult the LWC documentation to learn about available event directives and their properties. You can discover additional features and options that can enhance your components.

    Now, let’s talk about data binding.

    dont miss out iconCheck out another amazing blog by Sparkybit here: Salesforce Lightning Web Components Developer Guide: Chapter 1

    Data Binding

    Data binding is the process of linking properties of a JavaScript object with elements in the markup. When the value of a JavaScript object property changes, it automatically updates the corresponding value in the markup, and vice versa. To reference a JavaScript variable in the markup, you use the variable name enclosed in curly braces. For example, if you have a “name” variable in your JS file, you can reference it in your markup like this:

    <template> 
         <div>Hello, {name}!</div> 
    </template>

    In this example, the value of the “name” variable will be displayed in the markup, and if it changes, it will update on the page.

    Now, let’s discuss styles in LWC.

    Styling in Lightning Web Components

    Styling is an essential part of any front-end framework, including LWC. You can apply styles using CSS classes or direct style marking in tags. LWC also provides a set of style classes based on the Salesforce Lightning Design System (SLDS), which you can use to style your components.

    One of the primary advantages of using SLDS style classes is that they ensure a consistent appearance across all Salesforce applications. This helps ensure that LWC components seamlessly integrate with other Salesforce interface elements. To use SLDS classes, add the appropriate class names to your HTML elements. For example, to style a button as the primary style, you can use the “slds-button slds-button_brand” classes:

    <lightning-button variant="brand" label="Click me!" class="slds-m-top_small"></lightning-button>

    In this example, the “slds-m-top_small” class is used to add a margin above the button. You can read more about SLDS styles in this article.

    Apart from SLDS style classes, LWC also provides various Lightning input and button components that you can use to create forms and other interface elements. These components include <lightning-input>, <lightning-combobox>, <lightning-textarea>, <lightning-button>, and many others. These components offer a consistent appearance and are designed to work seamlessly with other Salesforce interface components.

    It’s essential to note that LWC components and SLDS style classes are not identical to their native HTML and CSS counterparts. While they may have similar names and functionalities, they are specifically designed for use on the Salesforce platform. This means there might be some differences in behavior and appearance compared to native HTML and CSS. Additionally, some features available in native HTML and CSS may not be available in LWC.

    To Sum Up

    In summary, we’ve covered the basics of LWC markup and communication between markup and JavaScript. We’ve shown how to use iteration, conditional operators, and variable references from JavaScript in the markup. These tools will help you create powerful and efficient Lightning Web Components components that interact with data on the page and provide a high-quality user experience.

    In the next article, we’ll dive into communication between LWC components, exploring the methods, advantages, disadvantages, and limitations.

    Sparkybit, Salesforce consulting and development company. We make Salesforce perform at its best by fitting it to Clients’ custom business needs. 9 years of sharpened expertise, 25+ successful long-term projects globally.

    contact@sparkybit.com

    Copyright belongs to Sparkybit GmbH, Im Dörener Feld 3, 33100, Paderborn, Germany.
    2023 © Sparkybit. All rights reserved.

  • How to Display Images from File Tab to Salesforce App by using Aura Component?

    How to Display Images from File Tab to Salesforce App by using Aura Component?

    What are Aura Components?

    Aura components are a type of user interface framework used in Salesforce. They are built using the Aura framework, which is a collection of client-side technologies and server-side tools that help developers create dynamic web applications with a focus on performance and reusability.

    Aura components are designed to be reusable building blocks for creating custom user interfaces in Salesforce. They can be used to create standalone web apps or as part of a larger Salesforce app. Aura components are modular and can be easily reused across different applications and projects, making them a powerful tool for developers.

    Some of the key features of Aura components include a component-based architecture, an event-driven programming model, server-side and client-side caching, and support for various data formats and APIs. Aura components can also be easily customized with CSS and JavaScript to match the look and feel of the rest of your Salesforce app.

    Overall, Aura components provide developers with a flexible and powerful way to create custom user interfaces in Salesforce that are both performant and reusable.

    dont miss out iconDon’t forget to check out: Use Aura Component in Screen Flow | Salesforce Flow Builder Tutorial

    How to Display Images from File Tab to Salesforce App?

    Step1: Create component for displaying image 

    The first step is to create an Aura component that displays an image. The component has an attribute named “PictureId” that will hold the ID of the image. The image is displayed using an <img> tag with a source (src) attribute that concatenates the Salesforce content URL with the PictureId attribute value.

    <aura:component controller="Galleryimage" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" > 
    <aura:attribute name="PictureId" type="Id" default="" /> 
    <img src="/sfc/servlet.shepherd/version/download/" + v. PictureId /> 
    </aura:component>

    Step 2: Creating Controller  

    The second step is to create a controller for the component. The controller uses the “doInit” function, which is called when the component is initialized. The “doInit” function makes an Apex server call to fetch the ID of the image from the “Galleryimage” Apex class. When the response is received, the “PictureId” attribute of the component is set to the ID of the image.

    ({ 
        doInit : function(component, event, helper) { 
            var action = component.get("c.getId"); 
            action.setCallback(this, function(response) { 
                var state = response.getState(); 
                // if (state === "SUCCESS") { 
                var picture = response.getReturnValue(); 
                // console.log("id", picture ); 
                component.set("v.PictureId",picture); 
    }); 
            $A.enqueueAction(action);   
        } 
    })

    Step 3: Apex class for fetching Id of Images available in File 

    The third step is to create an Apex class named “Galleryimage” that will fetch the ID of images available in the File tab. The Apex class has a method named “getId” that returns a list of ContentVersion objects that have the ID of the images.

    public class Galleryimage { 
    @Auraenabled 
        public static List<contentVersion> getId(){ 
            List<contentVersion> picView=[Select Id from contentVersion]; 
            return picView; 
        }    
    }

    dont miss out iconCheck out another amazing blog by Rupesh here: How do you Add LWC Component to Action Button?

    Conclusion

    So, you can show images dynamically from the file tab by using the aura component. Above mentioned steps are necessary for getting the ids of images from file. 

  • What is the Search Box In Aura Component? | The Developer Guide

    What is the Search Box In Aura Component? | The Developer Guide

    A search box in an Aura component is a user interface element that allows users to input text and search for relevant information within the component or its associated data. In Aura, the search box can be implemented using the <lightning:input> component with the type=”search” attribute. This component provides a text input field along with a search icon that can be used to initiate the search. 

    When a user types in the search box and clicks the search icon or presses enter, the component can execute a server-side controller action or a client-side JavaScript function to retrieve and display the search results. The search functionality can be customized to match the requirements of the component, such as searching based on specific fields or filters. 

    Overall, the search box is a common UI element used in many Aura components to allow users to quickly find the data they need. 

    Component: 

    <aura:component controller="searchAccountController" > 
        <aura:attribute name="keywordHolder" type="string" />   
        <aura:attribute name="accountList" type="list" />   
        <lightning:input name="AccountSearch"  label="Enter Account Name" value="{!v.keywordHolder}"/>   
        <lightning:button label="Search Account" onclick="{!c.findAccount}" /> 
        <aura:iteration var="acc" items="{!v.accountList}" >    
        {!acc.Name} 
        {!acc.type} 
        </aura:iteration>  
    </aura:component>

    dont miss out iconDon’t forget to check out: Use Aura Component in Screen Flow | Salesforce Flow Builder Tutorial

    Controller:  

    ({ 
     findAccount : function(component, event, helper) {  
            var action=component.get('c.fetchAccount'); 
            action.setParams({ 
                searchKeyWord : component.get("v.keywordHolder")          
            });           
            action.setCallback(this,function(response){           
                var state=response.getState(); 
                var response1=response.getReturnValue(); 
                if(state==="SUCCESS") 
                { 
                    component.set("v.accountList",response1); 
                }          
            }); 
            $A.enqueueAction(action); 
     } 
    })

    Apex Controller:  

    public class searchAccountController { 
    @AuraEnabled 
     public static List < account > fetchAccount(String searchKeyWord) { 
      String searchKey = searchKeyWord + '%'; 
      List < Account > returnList = new List < Account > (); 
      List < Account > lstOfAccount = [select id, Name, Type, Industry, Phone, Fax from account where Name LIKE: searchKey limit 1]; 
      for (Account acc: lstOfAccount) { 
       returnList.add(acc); 
      } 
      return returnList; 
     } 
    }

    dont miss out iconCheck out another amazing blog by Narendra Kumar here: How to Send Emails Using Lightning Web Component (LWC)?

    Output: 

  • What are Aura Components in Salesforce? | The Ultimate Guide

    What are Aura Components in Salesforce? | The Ultimate Guide

    The Lightning Component framework may be a UI framework for developing web apps for mobile and desktop devices. It’s a contemporary framework for building single-page applications with dynamic, responsive user interfaces for Lightning Platform apps. It uses JavaScript on the client side and Apex on the server side. 

    The Lightning Component framework is a framework for developing web apps. 

    Creating and Editing Aura Components

    1. Select File | New | Lightning Component to create an Aura component. 
    2. In the New Lightning Bundle panel, enter helloWorld for the component name.
    3. Click Submit

    Your component markup should look like the following: 

    What is a Component? 

    A component is a bundle that includes a definition resource, written in markup, and may include additional, optional resources like a controller, stylesheet, and so on. 

    A resource is sort of like a file but stored in Salesforce rather than on a file system. 

    There are the opening and closing <aura:component> tags, with some static HTML in between.  

    A bundle is sort of like a folder. It groups the related resources into a single component. Resources in a bundle are auto-wired together via a naming scheme for each resource type. Auto-wiring just means that a component definition can reference its controller, helper, etc., and those resources can reference the component definition. They are hooked up to each other (mostly) automatically.

    dont miss out iconDon’t forget to check out: Use Aura Component in Screen Flow | Salesforce Flow Builder Tutorial

    What is an App? 

    • An app uses <aura:application> tags instead of <aura:component> tags. 
    • Only an app has a Preview button in the Developer Console. 

    What Are Apps For?

    • When writing markup, you can add a component to an app, but you can’t add an app to another app, or an app to a component. 
    • An app has a standalone URL that you can access while testing, and which you can publish to your users. We often refer to these standalone apps as “my.app.” 
    • You can’t add apps to Lightning Experience or the Salesforce app—you can only add components. After the last unit this might sound weird; what exactly do you add to the App Launcher, if not an app? What you add to App Launcher is a Salesforce app, which wraps up an Aura component, something defined in a <aura:component>. An Aura components app—that is, something defined in a <aura:application> —can’t be used to create Salesforce apps. A bit weird, but there it is. 

    Component Attributes

    Attributes on components are like instance variables in objects. They’re a way to save values that change, and a way to name those value placeholders.

    For example, let’s say we wanted to write a helloMessage component that prints a custom message. We can envision adding a message attribute to this component to customize its output.

    Example:

    <aura:component> 
        <aura:attribute name="message" type="String"/> 
        <p>Hello! [ message goes here, soon ]</p> 
    </aura:component>

    dont miss out iconCheck out another amazing blog here: Overview of Aura Components in Salesforce | The Developer Guide

    Expressions 

    An expression is basically a formula, or a calculation, which you place within expression delimiters (“ {!” and “ }”). 

    {!<expression>

    An expression is any set of literal values, variables, sub-expressions, or operators that can be resolved to a single value. 

    <aura:component> 
        <aura:attribute name="message" type="String"/> 
        <p>{!'Hello! ' + v.message}</p> 
    </aura:component>
  • Aura Component Framework and Attributes | All You Need to Know

    Aura Component Framework and Attributes | All You Need to Know

    What is the Lightning Component?

    A UI framework called component framework is used to create single page applications for desktop and mobile platforms. On the client side, JavaScript is used, and on the server, Apex. Compared to many other frameworks, the Lightning Component Framework makes it much simpler to design programs that function on both mobile and desktop devices. 

    Lightning comes with the Lightning Component Framework and a number of innovative developer tools. Lightning makes it simpler to create applications that are responsive across all devices. 

    Both the Lightning Web Components paradigm and the classic Aura Components model can be used to create Lightning components. 

    Where we use lightning component in Salesforce org

    • Lightning app builder
    • Community builder
    • Lightning pages
    • Lightning experience record pages
    • Quick action

    dont miss out iconDon’t forget to check out: Use Aura Component in Screen Flow | Salesforce Flow Builder Tutorial

    What are the Lightning Component Attributes?

    Attribute in lightning component is like a variable and it stores the different type of value.

    Syntax:

    <aura:attribute name="Anyname" type ="string" description="some description"  default="some default string"/>

    A parameter of an attribute, the most important one, is its name and type, and another parameter where we can specify an attribute’s description is its description. The parameter description is not necessary. In a similar vein, we have a default parameter that provides an attribute with a default value. We have an access parameter that allows us to choose public, private, or global access for an attribute when setting its access. The attribute is open to the public by default. 

    We have a required parameter that we can set to true or false to make an attribute compulsory. 

    • Boolean

    Syntax: 

    <aura:attribute name="xyz" type="Boolean" />

    We use the Boolean attribute when we want to store boolean values. 

    • Integer 

    Syntax: 

    <aura:attribute name="xyz" type="Integer" />

    We use integer attribute when we want to store integer value. 

    • String

    Syntax: 

    <aura:attribute name="xyz" type="String" />

    We use string attribute when we want to store string value.

    dont miss out iconCheck out another amazing blog by Narendra Kumar here: What are Decorators in a Lightning Web Component?

    • Date

    Syntax: 

    <aura:attribute name="xyz" type="Date" />

    We use date attribute when we want to store date value.

    • DateTime

    Syntax: 

    <aura:attribute name="xyz" type="DateTime" />

    We use datetime attribute when we want to store datetime value.

    • Double 

    Syntax: 

    <aura:attribute name="xyz" type="Double" />

    We use double attribute when we want to store double value.

    • Decimal

    Syntax: 

    <aura:attribute name="xyz" type="Decimal" />

    Decimal is better than Double for maintaining precision for floating-point calculations. It’s preferable for currency fields. 

    • Long

    Syntax: 

    <aura:attribute name="xyz" type="Long" />

    Long values can contain numbers with no fractional portion. Use this data type when you need a range of values wider than those provided by Integer. 

  • Aura Components in Salesforce – Here’s All You Need to Know!

    Aura Components in Salesforce – Here’s All You Need to Know!

    What is Aura Component?

    A UI framework for creating web applications for desktop and mobile platforms is called the Aura Lightning Component Framework. This contemporary framework can be used to create dynamic single-page applications. On the client and server sides, it employs JavaScript as the controller of the component class. Numerous user interface (UI) elements offered by the lightning namespace come pre-configured to use the Salesforce Lightning Design System (SLDS). Salesforce administrators use these parts to build single-page web applications that offer a seamless platform experience for a range of tasks. 

    Where we Can Use Lightning Components?

    Your Salesforce org can be customised in a variety of ways using Aura Lightning components. Additionally, you can use Lightning components to build apps that are already available on the Salesforce Org. Additionally, it is possible to develop apps that run on several platforms. The necessary files are stored in “Bundles” by Lightning Components and Applications:   

    1. Component – The layout of the component is configured using a markup language.

    2. Controller – For client-side processing, a JavaScript Controller is required, but an apex controller is used for server-side processing.

    3. Design File – When a component is used in Lightning pages or Lightning App Builder, its design-time behaviour is described in a design file.

    4. Documentation File – Users who have received your component can find sample code or reference materials in a documentation file.

    5. Helper – A helper’s purpose is to store reusable JavaScript operations that the controller manages.

    6. SVG File –Custom icons that can be used as extra references can be included in an SVG file.

    dont miss out iconDon’t forget to check out: Javascript for Lightning Web Component | Salesforce Lightning

    We will discuss the Aura Lightning Component

    1: First we will create Lightning Component.

    For this Open Developer Console -> New -> Lightning Component. 

    Name the Lightning Component and Check all Component Configuration and we can add our components to the Salesforce. 

    Code:- 

    <aura:component implements=”force:appHostable,flexipage:availableForAll  
    PageTypes,flexipage:availableForRecordHome,force:hasRecordId, 
    forceCommunity:availableForAllPageTypes,force:lightningQuickAction”          access=”global” > 
    <h1>Hello Lightning!</h1> 
    </aura:component>

    2: To preview that Aura Component, We have to use the Lightning Application in which we call that Aura Component as shown below: 

    <aura:application extends="force:slds"> 
    <c:ComponentName/> 
    </aura:application>   

    3. Attributes – Attributes have two important parameters i.e. Name and Type.

    4. Value Providers – The value provider enables us to access the value of a component attribute in component markup and Javascript controller. 

    Example:-  {!v.AccountData} 

    5. Action Providers The action provider enables us to handle actions, events, handlers for the component.

    Example:- <lightning:button label=”Save” onclick=”{!c.onSave}” /> 

    dont miss out iconCheck out another amazing blog by Harsh here: Using Batch Apex in Salesforce | The How-to Guide

    Events in Salesforce Lightning Component 

    The Lightning Framework’s event-driven architecture enables the communication between various events. When a user interacts with the user interface, JavaScript controller actions that are triggered by that interaction fire lightning events. Events can handle the communication between Components. 

    There are two types of custom events in Lightning: 

    • Components Events.
    • Application Events. 

     Lightning Component

       

     

     

     

  • How to Add Your Visualforce Page in your Application as a Tab | Salesforce Guide

    How to Add Your Visualforce Page in your Application as a Tab | Salesforce Guide

    Introduction

    Sometimes our requirement is to access our VF page as a tab in our application. So we gonna learn here how to use our VF page as a tab in your application. For this, I will create a sample Vf page example and  I will add it in our tab.

    How to Create Visualforce Page

    Step 1: Go to your ‘Developer Console’ and click on File → New → Visualforce Page.

    Step 2: Now write your VF page name and write your code inside it.

    Step 3: Now write Controller for your Vf Page and assign it in your Vf Page as above. Vf Page Controller is nothing but the Apex Class in Salesforce. And we assign this apex class to our vf page as controller. 

    Step 4: Hence our Vf Page is ready now.

    dont miss out iconDon’t forget to check out: Creating Multi Screen Wizard Using Apex and Visualforce Salesforce

    How to Add VF Page to our App as a Tab?

    Step 1: Go to the ‘Quick Find’ Box and search ‘Tab’ there. And click on ‘Tabs’.

    Step 2: Go to the ‘Visualforce Tab’ section and click on the ‘New’ button.

    Step 3: Now fill in details as follow:

    • Visualforce Page – Select your Vf Page here from the drop-down list.  Here I selected – Training Page [Training Page].
    • Tab Label – Write down a name for that Vf page according to your requirement. Here I write ‘Training Vf Page’.    
    • Tab Name – It automatically catches ‘Tab Label’ with an underscore.
    • Tab Style – Select tab style for your Vf Page.
    • Description – Write a description according to your VF page.

    Step 4: Click on the ‘Next’ button.

    Step 5: Now again click the ‘Next’ button on this page also. Here you can give access to this tab to various profiles also. But keep it as it is.

    Step 6: Now add your tab to all apps by clicking on ‘Include Tab’ or you can add this tab to a specific custom app according to your requirement. But I am not gonna add this tab to any of my apps for now. So I deselect the ‘Include Tab’ checkbox.

    Step 7: Now click on save and hence your Vf Page tab is created.

    Step 8: Now I am gonna add this tab to a particular app. So I search ‘App Manager’ on the Quick find box and click on it.

    dont miss out iconCheck out another amazing blog by Rajat here: Page Layouts in Salesforce – Here’s All You Need to Know

    Step 9: You can see the whole list of Standard and Custom apps of your org. Now select any one app and click on edit from the down arrow at the end of the app name. Here I select the ‘BOOK MY HOME’ custom app and click on the ‘Edit’ button.

    Step 10: Now click on ‘Navigation Items’ and search ‘Training’ on the search bar and then select ‘Training Vf Page’.

    Step 11: Now click on ‘>’ this arrow to add this tab in ‘Select Items’  i.e. in the navigation bar of that app.

    Step 12: Now add this tab in ‘Selected Items’ and click on ‘Save’.

    Step 13: Now go to your app and click on that ‘Training Vf Page’ tab. And your VF page code runs properly and see your Vf Page output.

    Step 14: Hence, our Vf Page is added in the app as a tab.

    I hope this information will be helpful for you.

    Thank you.

     

  • Visualforce Basics | Salesforce Learning Guide

    Visualforce Basics | Salesforce Learning Guide

    Visualforce is a powerful tool and a stimulating framework allowing developers to explain the interface component and to create sophisticated custom interfaces which will be hosted natively on the lightning platform The Visualforce framework consists of two elements: a tag-based markup and a set of server-side controllers making it easier for developers to perform database operations

    That is, components are defined using the markup language on the page and bind it to the controller (Standard or custom) to perform logical operations on the components.

    The server hosts the visual force, so whenever any Visualforce code is written it will be generated and will be run on the servers.

    Controllers and Extensions

    • Salesforce has provided the basic building functionality to be followed and used with appropriate logic for a Standard controller that works for a standard page as set by Salesforce. 

    Syntax: <apex:page standardController=”Contact”>

    For example, if we are going to use the standard Obj Opportunity, then we need to use a standard controller, clicking on the Save button on that Visualforce page will result in the same behaviour as clicking Save on a standard Opportunity edit page. A Standard list controller: Visualforce pages as the name suggests that can display the records in a list manner or act on a list of records. Examples of already present Salesforce pages that work with sets of records include list pages, related lists, and mass action pages.

    dont miss out iconDon’t forget to check out: Salesforce Lightning Component Inside Lightning Web Component Using Visualforce Page

    Example code:

    <apex:page standardController="Contact" recordSetVar="contacts">
        <apex:pageBlock title="Contacts List">
            <!-- Contacts List example of Standard List Controller -->
            <apex:pageBlockTable value="{! contacts }" var="ct">
                <apex:column value="{! ct.FirstName }"/>
                <apex:column value="{! ct.LastName }"/>
                <apex:column value="{! ct.Email }"/>
                <apex:column value="{! ct.Account.Name }"/>
            </apex:pageBlockTable>
        </apex:pageBlock>
    </apex:page>

     

    contact list

    • A Custom controller can be defined as a class written in Apex that provides the functionality of all of the page’s logic and behaviour without leveraging a typical standard controller. Access for the custom controller is embedded in the VF page as <apex:page controller=”ContactsListWithController“>  Custom controller, you’ll define new navigation elements or behaviours, but you want to also reimplement any functionality that was already provided during a standard controller.

    dont miss out iconCheck out another amazing blog by Narendra here: Understanding Accounts & Contacts for Sales Process | Salesforce Guide

    Syntax

    <apex:page controller="ContactsListWithController">
        <apex:form>
            <apex:pageBlock title="Contacts List" id="contacts_list">
    <!--Example of custom controller-->
                <!-- Contacts List goes here -->
            </apex:pageBlock>
        </apex:form>
    </apex:page>
    Custom Controller Apex Class
    public class ContactsListWithController {
        // Controller code goes here
    }

     

  • Visualforce Pages in Salesforce | The Developer Guide

    Visualforce Pages in Salesforce | The Developer Guide

    Visualforce Page In Salesforce

    Visualforce Page is just like HTML, i.e, It is a tag-based markup language. It allows developers to build sophisticated, user-custom interfaces. It has some user interface components such as a section of a page, a related list, or a field.

    It consists of two primary elements :

    • Visualforce markup
    • Visualforce controller

    Where can we use this Visualforce Page?

    • Override Standard buttons, Tab overview pages
    • Define Custom Tabs
    • Create a dashboard component and other more things we can do with this Visualforce Page.

    Simple Examples of Visualforce Page:

    <apex:page>
    <h1>Welcome Visualforce Page</h1>
    </apex:page>

    dont miss out iconDon’t forget to check out: Get Selected Records from ListView in Visualforce Page | GETRECORDIDS JavaScript | StandardSetController Salesforce

    What is a Controller?

    A Controller is an apex class that is used to implement all the logic of a Visualforce page without holding/supporting the standard functionality.

    In Visualforce, we have two types of controller:

    • Standard Controller
    • Custom Controller

    Standard Controller:

    A standard controller is a class that inherits all the standard properties of objects and the functionality of standard buttons. It also provides common operations such as CRUD (Create/ Read/ Update/ Delete) on any Standard or Custom object. E.g.

    <apex:page standardController=”Account”>
    </apex:page>

    Example of Standard Controller:

    <apex:page standardController="Account">
      <apex:form>
        <apex:pageBlock title="My Content" mode="edit">
          <apex:pageBlockButtons>
            <apex:commandButton action="{!save}" value="Save"/>
          </apex:pageBlockButtons>
          <apex:pageBlockSection title="My Content Section" columns="2">
            <apex:inputField value="{!account.name}"/>
            <apex:inputField value="{!account.site}"/>
            <apex:inputField value="{!account.type}"/>
            <apex:inputField value="{!account.accountNumber}"/>
          </apex:pageBlockSection>
        </apex:pageBlock>
      </apex:form>
    </apex:page>

    Custom Controller:

    A custom controller is an Apex class that applies all the logic for a page without holding a standard controller. E.g,

    <apex:page Controller=”myController”>
    </apex:page>

    Building Standard List Controller

    It is just similar to a standard controller that can display a set of records.

    Example of Standard List Controller:

    <apex:page standardController="Account" recordSetVar="accounts" tabstyle="account" sidebar="false">
      <apex:pageBlock>
        <apex:pageBlockTable value="{!accounts}" var="acc">
          <apex:column value="{!acc.name}"/>
        </apex:pageBlockTable>
      </apex:pageBlock>
    </apex:page>

    dont miss out iconCheck out an amazing Salesforce Video Tutorial here: Creating Multi Screen Wizard Using Apex and Visualforce Salesforce

    Building Custom List Controller

     It is just similar to a standard list controller that displays a set of records.

    <apex:page controller="ContactsListWithController">
        <apex:form>
            <apex:pageBlock title="Contacts List" id="contacts_list">
    <apex:pageBlockTable value="{! contacts }" var="ct">
         <apex:column value="{! ct.FirstName }"/>
         <apex:column value="{! ct.LastName }"/>
         <apex:column value="{! ct.Title }"/>
         <apex:column value="{! ct.Email }"/>
    </apex:pageBlockTable>
            </apex:pageBlock>
        </apex:form>
    </apex:page>
    private String sortOrder = 'LastName';
    public List<Contact> getContacts() {
        List<Contact> results = Database.query(
            'SELECT Id, FirstName, LastName, Title, Email ' +
            'FROM Contact ' +
            'ORDER BY ' + sortOrder + ' ASC ' +
            'LIMIT 10'
        );
        return results;
    }

     

  • How to Get Current Record Id in Lightning Web Component | Salesforce Developer Guide

    How to Get Current Record Id in Lightning Web Component | Salesforce Developer Guide

    Getting record in Lightning Aura Component is quite easy, we use force:hasRecordId and get the result in controller by using, 

    getRecordId:function(component,event, helper){
        var currentRecordId =  component.get(“v.recordId”);
        console.log(‘currentRecordId ‘+currentRecordId );
    }

    It is all good in Lightning Aura Components, but if you are starting a new Lightning Web Component, how can you get the recordId?

    Create a new Lightning Web Component, and name it as recordIdInLWC. When the component is created, go to its .js file.

    import { LightningElement, api } from 'lwc';
    export default class RecordIdInLWC extends LightningElement {
    }
    //Inside export part introduced a variable for recordId by using @api decorator. It will be a public access modifier.
    import { LightningElement, api } from 'lwc';
    export default class RecordIdInLWC extends LightningElement {
        //Create a Record ID variable
        @api recordId; 
    }
    

    dont miss out iconDon’t forget to check out: Salesforce Lightning Component Inside Lightning Web Component Using Visualforce Page

    Now, go to the components:

    HTML file

    <template>
        <div >
            <lightning-record-view-form record-id={recordId} object-api-name="Contact">
                <div >
                    <div >
                        <lightning-output-field field-name="Name"></lightning-output-field>                    
                    </div>
                    <div >
                        <lightning-output-field field-name="Phone"></lightning-output-field>
                        <lightning-output-field field-name="Email"></lightning-output-field>
                    </div>
                </div>
            </lightning-record-view-form>
        </div>
    </template>
    

    .js File

    import { LightningElement,api } from 'lwc'; 
    export default class RecordIdInLWC extends LightningElement {
        @api recordId;
    }
    

    XML File

    <?xml version="1.0" encoding="UTF-8"?>
    <LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
        <apiVersion>50.0</apiVersion>
        <isExposed>true</isExposed>
        <targets>
            <target>lightning__RecordPage</target>
        </targets>
    </LightningComponentBundle>
    

    dont miss out iconCheck out another amazing blog by Krati here: What are Quote Line Items in Salesforce

    Add this component to Contact Detail Page

    • Go to the Contact tab.
    • Open any contact record.
    • Click Setup (Gear Icon) and select Edit Page.
    • Under Custom Components, find your recordIdExampleLWC component and drag it on the right-hand side top.

    Click Save and activate.