Posts

Showing posts with the label Visualforce Pages

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...

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...

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) {                   ...

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"...

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...

Working with Large Sets of Data

Visualforce custom controllers and controller extensions are subject to Apex governor limits. For more information about governor limits, see Execution Governors and 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. 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. Note - You can only iterate over large sets of data if you specify read-only ...

Rendering PDF Files Using Visualforce Page

Rendering PDF files using a Visualforce page in Salesforce is a common requirement, especially when you need to generate printable documents such as reports, invoices, or statements. Salesforce provides a way to generate PDF files directly from Visualforce pages using the renderAs attribute.    Visualforce <apex:page controller="PDFRenderingController" renderAs="pdf">   <apex:form >     <apex:pageBlock >         <apex:pageBlockTable value="{!accList}" var="acc" border="2">            <apex:column value="{!acc.Name}"/>            <apex:column value="{!acc.AnnualRevenue}"/>            <apex:column value="{!acc.Type}"/>            <apex:column value="{!acc.AccountNumber}"/>            <apex:column value="{!acc.Rating}"/>       ...

Wrapper Class in Apex Salesforce

A wrapper class in Salesforce Apex is a custom class that allows you to combine different types of data into a single object. It's particularly useful when you need to work with complex data structures or display multiple pieces of information in a Visualforce page.  Wrapper classes are commonly used in scenarios like: Visualforce Pages : You can use wrapper classes to display data from multiple related objects in a single table or form on a Visualforce page. Apex Controllers : Wrapper classes can be used to pass complex data structures between Apex controllers and Visualforce pages. Lightning Components : In Lightning development, wrapper classes are often used to format data for display in Lightning components or to simplify the structure of data passed between components. Integration : When working with external systems or APIs, wrapper classes can help structure data in a way that's easier to work with in Apex code. Here's an example of how you can use a wrapper class w...

Mass Updating Records with a Custom Controller Using Visualforce Page

Here's an example illustrating these steps: Controller public with sharing class MassUpdateController {     public List<MyObject__c> records { get; set; }     public Set<Id> selectedIds { get; set; }     public MassUpdateController() {         // Fetch records to display         records = [SELECT Id, Name, Active__c FROM Agent__c LIMIT 10];         selectedIds = new Set<Id>();     }     // Method to handle the mass update operation     public PageReference performMassUpdate() {         List< Agent__c > recordsToUpdate = new List< Agent__c >();         // Fetch selected records to update         for (Agent__c record : records) {             if (selectedIds.contains(record.Id)) {                 // ...

Integrating Visualforce and Google Charts

Integrating Visualforce with Google Charts allows you to create dynamic and visually appealing charts within your Salesforce environment. Visualforce is Salesforce's markup language for building custom user interfaces, and Google Charts is a powerful visualization library provided by Google. Here's a basic guide on how to integrate Visualforce with Google Charts: <!-- MyChartPage.page --> <apex:page controller="ChartController">     <apex:includeScript value="https://www.gstatic.com/charts/loader.js"/>     <script>         google.charts.load('current', {'packages':['corechart']});         google.charts.setOnLoadCallback(drawChart);         function drawChart() {             var data = google.visualization.arrayToDataTable({!chartData});             var options = {                 title:...

Dynamic Menu Using JDock

Image
Show Sleek and Dynamic Menu on the Visualforce Page. jqdock is a jQuery plugin inspired by Mac .jqdock is a jQuery plugin inspired by Mac Dock Menu. jqDock   Visualforce Page <apex:page sidebar="false" showHeader="false" controller="JqueryController">  <head>    <style> bPageHeader{       display:none;   }   .heading{       background-color:#ccc;       text-align:center;   }   .data table,td,th {       border:1px solid #000;   }   </style>  <apex:includeScript value="{!$Resource.jquery}"/>  <apex:includeScript value="{!$Resource.jqDock}"/>   <style type='text/css'>  /*position and hide the menu initially - leave room for menu items to expand...*/ #page {padding-top:150px; padding-bottom:20px; width:100%;} #menu {position:absolute; top:0; left:0; width:100%; display:none;} /*dock styling...*/ /*...centre the dock...*/ ...