Posts

Showing posts with the label Visualforce

Salesforce custom label in Apex, Visualforce, AURA, LWC

Salesforce custom labels can be used across different Salesforce technologies, including Apex, Visualforce, Aura components, and Lightning Web Components (LWC). Here's how you can use custom labels in each of these contexts: Apex : In Apex, you can access custom labels using the System.Label global variable. Custom labels are referenced by their developer name. String labelValue = System.Label.MyCustomLabel; Visualforce : In Visualforce pages, you can reference custom labels using the $Label global variable. <apex:outputText value="{!$Label.MyCustomLabel}" /> Aura Components: In Aura components, you can access custom labels using the $Label global value provider. <aura:component>     <aura:attribute name="labelValue" type="String" default="{!$Label.MyCustomLabel}" /> </aura:component> Lightning Web Components (LWC): In Lightning Web Components, you can import and reference custom labels using the @salesforce/label scop...

Retrieve Guest User IP Address with VF Page

Image
The two standard objects:  AuthSession ,  LoginGeo don’t store the login information of a Guest User. Using a VF Page  <apex:page showHeader="false" sidebar="false" controller="userIPAddressController"  action="{!getUserIPAddress}">  <script>     setTimeout(function(){         var message = '{!ip}';         parent.postMessage(message, window.top.location.origin);               }, 3000);  </script>  <apex:form >      {!ip}  </apex:form> </apex:page> Controller public class userIPAddressController{     public string ip {get;set;}     public pageReference getUserIPAddress() {                  // True-Client-IP has the value when the request is coming via the caching integration.         ip = ApexPages.currentPage().getHeaders()...

Retrieve IP Address of a Community User

Image
For a variety of purposes, including displaying items, sending texts, and other security-related tasks, tracing IP addresses is necessary. Logged in User IP Address Getting IP Address for logged in user is relatively simple as Salesforce stores this information in two standard objects:  AuthSession ,  LoginGeo . List<AuthSession> auth = [SELECT Id , IsCurrent, SessionType, CreatedDate, LoginGeoId, NumSecondsValid FROM AuthSession WHERE UsersId =: Userinfo.getUserID()]; if(auth.isEmpty() == false && auth[0].IsCurrent ){ system.debug('yes, it is current user session'); }else{ system.debug('No, it is not current user session'); } List<LoginGeo> lg = [SELECT Id,City, Country, PostalCode, Subdivision, Latitude, Longitude,LoginTime FROM LoginGeo WHERE Id =: auth[0].LoginGeoId]; Alternatively, you can use  Auth.SessionManagement  Class as well as below: Auth.SessionManagement.getCurrentSession().get('LoginGeoId'); getCurrentSession() re...

Conditionally render fields on Visualforce page based on picklist values

 An example of how to render a Visualforce page based on criteria. <apex:pageBlock id="xxxpb1"> <apex:pageBlockSection>                      <apex:actionRegion >                  <apex:inputField id="xxxif1" value="{!Object.picklistfieldapiname1}" required="true" >      <apex:actionSupport event="onchange" rerender="xxxpb1" />   </apex:inputField> </apex:actionRegion>                   </apex:pageBlockSection>                 <apex:pageBlockSection id="xxxpbs1" rendered="true">  <apex:inputField id="xxxif2" value="{!Object.Fieldtobedisplayed1}" rendered="{!IF(Object.picklistfieldapiname1 ='picklist value 1' || lead.Buyer_Type__c ='picklist value 2' ,true,false)}"/> </apex:pageBlockSection> <apex:pageBlockSec...

Dynamically Calling JavaScript Functions

Dynamically invoking JavaScript functions enhances code flexibility and efficiency. By dynamically calling JavaScript functions, we can create more flexible and efficient applications that adapt to various scenarios. Dynamic Functionality : Dynamically calling JavaScript functions allows your code to adapt to different scenarios and conditions at runtime. This flexibility lets you execute functions based on user interactions, system events, or data-driven logic. Code Reusability : By dynamically invoking JavaScript functions, you can reuse standard functions across multiple components or modules within your application. This promotes code modularity, reduces duplication, and leads to cleaner and more maintainable code. Conditional Logic: Dynamically invoking functions allows you to apply conditional logic to determine which functions to execute based on specific conditions or criteria. This enables you to build more intelligent and adaptive applications that respond dynamically to cha...

Managed vs Unmanaged in Salesforce

Image
Managed Packages in Salesforce are a way for developers to package and distribute their custom applications and components to other Salesforce organizations. These packages encapsulate custom objects, fields, Apex code, Visualforce pages, Lightning components, and other metadata components developed on the Salesforce platform. Unmanaged packages in Salesforce are collections of metadata components that are bundled together for distribution and deployment. Unlike managed packages, which provide IP protection and versioning capabilities, unmanaged packages are primarily used for sharing customizations within a single Salesforce organization or for simple deployments.  Here is a comparison between Managed and Unmanaged packages. Managed Packages: Packaging and Distribution: Managed packages are packaged and distributed by Salesforce developers or ISVs (Independent Software Vendors) through the Salesforce AppExchange or other distribution channels. Developers can package custom object...

Visualforce PDF Rendering Considerations and Limitations

It is essential to consider these limitations when designing Visualforce pages that will be rendered to PDF. Always verify the formatting and appearance of the PDF version of your page before putting it into production. The following are some limitations of the Visualforce PDF rendering service Limitations of the Visualforce PDF rendering service include the following. PDF is the only supported rendering service. The PDF rendering service renders PDF version 1.4 and CSS versions up to 2.1. Rendering a Visualforce page as a PDF file is intended for pages designed and optimized for print. A Visualforce page rendered as a PDF file displays either in the browser or is downloaded, depending on the browser’s settings. Specific behavior depends on the browser, version, and user settings, and is outside the control of Visualforce. The PDF rendering service renders the markup and data on your page, but it might not render formatting contained within the contents of rich text area fields added t...

Lightning Design System (SLDS) in Visualforce pages

Salesforce Lightning Design System provides a set of CSS classes and design guidelines that allow you to create user interfaces that are consistent with the Salesforce Lightning Experience.  You can use the Lightning Design System (SLDS) to build Visualforce pages that match the look and feel of the Salesforce mobile app. To use SLDS, it takes some tweaks in your code and a few things to remember. Visualforce Page with SLDS <apex:page applyHtmlTag="false" applyBodyTag="false">     <html lang="en">     <head>         <title>SLDS Example in Visualforce</title>         <apex:slds />     </head>     <body>         <div class="slds-scope">             <div class="slds-grid slds-grid_vertical">                 <div class="slds-col slds-size_1-of-2">  ...

Use Of addFields in ApexPages.StandardController

The add fields method helps developers specify fields for the standard controller to query in Visualforce pages. public AccountController(ApexPages.StandardController stdController){             this.controller = stdController;             List<String> fieldNamesList = new List<String>{Type,Industry};             stdController.addFields( fieldNamesList );             // stdController.addFields(new List<String>{'Name', 'TaxExemption__c', ' Industry '}); } Reference: https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/apex_ApexPages_StandardController_addFields.htm

Add a Lightning application within a Visualforce page in Salesforce

  <!-- create a lightning app with global access that extends lightning outApp-->   YourLightningComponent.app <aura:application access="GLOBAL" extends="ltng:outApp">        <aura: dependency resource="lightning: button"/>   </aura: application>   <apex:page >     <apex:includeLightning />          <div id="lightningContainer"></div>     <script>         $Lightning.use("c:YourApp", function() {             $Lightning.createComponent(                 "c:YourLightningComponent",                 {},                 "lightningContainer",                 function(cmp) {                   ...

Pagination in Visualforce using StandardSetController

Image
The StandardSetController is a controller class that enables you to create a Visualforce page to showcase a list of records. It has built-in capabilities to handle pagination, thus simplifying displaying extensive data sets on a Visualforce page. Here are some key features and functionalities of StandardSetController: Pagination : StandardSetController automatically handles pagination, allowing you to display a subset of records on each page. It provides methods for navigating between pages, such as first(), previous(), next(), and last(). Sorting and Filtering : StandardSetController allows you to specify sorting and filtering criteria for the records displayed on the Visualforce page. You can define sorting order and filter conditions using the setSortOrder() and setFilterId() methods. Record Navigation : You can easily navigate to the first, last, previous, or next page of records using methods provided by StandardSetController. This simplifies the implementation of navigation contr...

Ajax in Visualforce page

In Visualforce, you can use Ajax (Asynchronous JavaScript and XML) techniques to perform asynchronous requests to the server without refreshing the entire page. This allows you to update specific parts of the page dynamically, providing a smoother and more responsive user experience. Here's how you can use Ajax in Visualforce pages: Using <apex:actionFunction>: <apex:actionFunction> allows you to define a JavaScript function that invokes an Apex controller method without a full page refresh. It's typically used to perform server-side actions based on user interactions. Example <apex:page controller="MyController">     <apex:form>         <apex:commandButton value="Click Me" onclick="doAction(); return false;"/>         <apex:actionFunction name="doAction" action="{!myControllerMethod}" rerender="outputPanel"/>     </apex:form>     <apex:outputPanel id="outputPanel"...

Implement deletion of checked values in a Visualforce page

Here's a simplified example to illustrate the approach: Visualforce Page <apex:page controller="MyController">     <script>         function deleteSelectedRecords() {             var selectedIds = [];             // Loop through checkboxes and collect IDs of checked records             document.querySelectorAll('input[type="checkbox"]:checked').forEach(function(checkbox) {                 selectedIds.push(checkbox.value);             });             // Call server-side method to delete selected records             MyController.deleteRecords(selectedIds, function(result, event) {                 // Handle response from server                 if (event....

Importing a CSV file using Apex and Visualforce

Here is an example of importing a CSV file using Apex and Visualforce. Depending on your requirements, you may need to enhance this solution with additional error handling, validation, and business logic. Visualforce Page- <apex:page controller="demoImportDataFromCSV">     <apex:form >         <apex:pagemessages />         <apex:pageBlock >             <apex:pageBlockSection columns="2">                    <apex:inputFile value="{!csvFileBody}"  filename="{!csvAsString}"/>                   <apex:commandButton value="Import Product" action="{!importCSVFile}"/>             </apex:pageBlockSection>         </apex:pageBlock>         <apex:pageBlock >           ...

Visualforce View State

Image
In Visualforce, view state refers to the state of the page, including the state of its form data, component values, and controller state, that is transmitted to and from the server with each request. View state enables Visualforce pages to maintain stateful behavior similar to traditional web applications, where user inputs and interactions are preserved across multiple requests. Optimize the View State View State Tab Steps to reduce the View State Use filters and pagination to reduce data that requires state. Declare an instance variable with a transient keyword if the variable is only useful for the current request. A transient variable isn’t included in the view state. Refine your SOQL calls to return only data that's relevant to the Visualforce page. Reduce the number of components that your page depends on. Make data read-only. Use the <apex:outputText> component instead of the <apex:inputField> component. Use JavaScript remoting. Unlike the <apex:actionFunction...

Retrieve current record id in salesforce

To get the current record ID in Salesforce Visualforce, you can use the Id parameter in the URL or leverage standard controllers. Here are two common methods to accomplish this: Using the Id Parameter in the URL: In Visualforce, you can access the current record's ID using the Id parameter in the URL. This method is commonly used when creating custom pages or links. <apex:page standardController="Account">     <h1> Account Record ID: {!$CurrentPage.parameters.Id}</h1> </apex:page> In this example, {!$CurrentPage.parameters.Id} retrieves the ID from the URL. Using Standard Controllers : If you're using a standard controller in your Visualforce page, you can directly reference the record ID using the Id property of the standard controller. <apex:page standardController="Account">     <h1>Record ID: {! Account.Id}</h1> </apex:page> In this example, {! Account.Id} retrieves the ID of the current record from the st...

Display error messages with different severity levels in a Visualforce page

Image
To display error messages with different severity levels in a Visualforce page using ApexPages.addMessage, you can follow the same approach as before but with different severity levels. Here's how you can add messages with different severity levels and display them in a Visualforce page: Add Messages with Different Severities in Apex Controller: In your Apex controller, add error messages with different severity levels using ApexPages.addMessage. public class MyController {     public void someAction() {         try {             // Perform some action             if (someCondition) {                 // Add error message with severity                 ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'An error occurred: Some error message'));             } else if (another...