Showing posts with label visualforce page. Show all posts
Showing posts with label visualforce page. Show all posts

Tuesday, May 12, 2020

Navigate to Visualforce page from lightning web components(lwc)

To navigate to visualforce page we have to use the Navigation Service in Lightning web components.

Check below for more details about navigation service in Lightning web components

Sample Code

//Navigate to visualforce page
navigateToVFPage() {
    this[NavigationMixin.GenerateUrl]({
	    type: 'standard__webPage',
	    attributes: {
		    url: '/apex/SampleVFPage?id=' + recId
	    }
    }).then(vfURL => {
	window.open(vfURL);
    });
}

Friday, September 13, 2019

How to implement Progress Bar in Visualforce Page

This post explains how to implement Progress bar on the Visualforce page using SLDS class.

This is Demo only you can extend this functionality based on your requirement.

Demo

Visualforce page
<apex:page controller="ProgressBarController" >
    <apex:slds />
    <apex:form id="frm">
        <apex:actionPoller action="{!checkStatus}" enabled="{!bProcess}" interval="5" reRender="frm" />
        
        <div class="slds-grid slds-gutters" style="margin-left:1%;">
            <div class="slds-col slds-size_1-of-3">
                <h1 style=" font-weight: bold;">
                    Progress Bar Demo in Visualforce Page
                </h1>
                <div style="display: block; margin-top:5%;" class="slds-progress-bar slds-progress-bar_circular" aria-valuemin="0" aria-valuemax="100"
                     aria-valuenow="{!deProgressBarWidth}" role="progressbar">
                    <span class="slds-progress-bar__value slds-progress-bar__value_success" style="width: {!deProgressBarWidth}%;">
                        <span class="slds-assistive-text">Progress: {!deProgressBarWidth}%</span>
                    </span>
                    <div class="slds-text-align--center slds-text-title" style="color:forestgreen;">
                        {!strStatus}
                    </div>
                </div>
            </div>
        </div>
    </apex:form>
</apex:page>


Apex Class
public class ProgressBarController {
    
    public Decimal deProgressBarWidth {get;set;}
    public Integer iCount {get;set;}
    public String strStatus {get;set;}
    public Boolean bProcess {get;set;}
    
    public ProgressBarController() {
        deProgressBarWidth = 0;
        strStatus = 'In Progress...';
        bProcess = true;
        iCount = 0;
    }
    
    public PageReference checkStatus() 
        // Caluclating Percentage value
        deProgressBarWidth = (iCount != 0 ? (Decimal.valueOf(iCount) > 100 ? 100 : Decimal.valueOf(iCount))/100 * 100 : 0);
        if(iCount >= 100) {
            strStatus = 'Completed';
            bProcess = false;
        }
        else {
            strStatus = 'Processing => ' + iCount + '/100';
        }  
        
        iCount += 45;
        return null;
    }
}

Output

Thursday, June 27, 2019

Send data from Lightning Component to Visualforce page Using Custom Event

This post explains how to send the data from the Lightning component to the visualforce page by using Custom Event.

In this demo, I am displaying the Account data in both Lighting component and visualforce page.

Example

Create a Custom Event this event used to send the data to visualforce page

SendDataToVFPage.evt
<!-- this event used in SendDataToVFPageComponent -->
<aura:event type="APPLICATION">
    <aura:attribute name="currentRecId" type="String"/>
    <aura:attribute name="CurrentRecDetails" type="Object" />
</aura:event>
Create Lightning Component and register the custom event in Lighting Component

SendDataToVFPage.cmp
<aura:component>

    <aura:attribute name="strParentId" type="String"/>
    <aura:attribute name="recordFields" type="Object"/>

    <!--This event used to send the data from Lightning component to vf page-->
    <aura:registerEvent name="vfEvent" type="c:SendDataToVFPage"/>

    <aura:if isTrue="{!not(empty(v.strParentId))}">
        <force:recordData aura:id="currentRecord" layoutType="FULL" recordId="{!v.strParentId}" targetFields="{!v.recordFields}"/>
        <h3><b>Showing data from Lightning Component</b></h3><br/>
        <div>
            <lightning:card iconName="standard:account" title="{!v.recordFields.Name}">
                <div class="slds-p-horizontal--small">
                    <p class="slds-text-heading--medium"><lightning:formattedText title="Type" value="{!v.recordFields.Type}"/></p>
                    <p class="slds-truncate">
                        <lightning:formattedText title="Industry" value="{!v.recordFileds.Industry}"/></p>
                    <p class="slds-truncate"><lightning:formattedPhone title="Phone" value="{!v.recordFields.Phone}"/></p>
                </div>
            </lightning:card>
        </div><br/>
        <div style="text-align: center">
            <lightning:button variant="brand" label="Send Data VF Page" onclick="{!c.sendDataVFPage}" />
        </div>
    </aura:if>

</aura:component>
when you click the 'sendDataVFPage' button in the Component custom event will fire and it sets the data to the event parameters.
SendDataToVFPageController.js
({
    sendDataVFPage : function(component, event, helper) {
        console.log('current rec details ===> '+JSON.stringify(component.get('v.recordFields')));
        console.log('Parent Id  ===> '+component.get('v.strParentId'));
        if(component.get('v.strParentId')) {
            var myEvent = $A.get("e.c:SendDataToVFPage");
            myEvent.setParams({
                currentRecId: component.get('v.strParentId'),
                CurrentRecDetails: component.get('v.recordFields')
            });
            myEvent.fire();
        }
    }
})

Create Lightning out App to call the lighting component from the visualforce page.
add your component in lightning out App.

DemoLightingOutApp.app
<aura:application extends="ltng:outApp" access="GLOBAL">
    <aura:dependency resource="c:SendDataToVFPage"/>
</aura:application>
Create Visualforce page and include  <apex:includeLightning /> in page.

LightingOutPageDemo.page
<apex:page standardController="Account">
    <apex:pageMessages />
    <apex:includeLightning />
    <div id="vfDemo" />

    <apex:pageBlock title="Showing data from visualforce page">
        <apex:pageBlockSection>
            <apex:pageBlockSectionItem>
                <apex:outputLabel value="Account Name" />
                <apex:outputText styleClass="accName" />
            </apex:pageBlockSectionItem>
            <apex:pageBlockSectionItem>
                <apex:outputLabel value="Account Industry" />
                <apex:outputText styleClass="accIndustry" />
            </apex:pageBlockSectionItem>
            <apex:pageBlockSectionItem>
                <apex:outputLabel value="Account Phone" />
                <apex:outputText styleClass="accPhone" />
            </apex:pageBlockSectionItem>
        </apex:pageBlockSection>
    </apex:pageBlock> <br/><br/>

    <script>
        // Calling Lightning component from vf page
        $Lightning.use("c:DemoLightingOutApp", function () {
            $Lightning.createComponent("c:SendDataToVFPage", {
                strParentId: '{!Account.Id}', // passing parameters to Lightning Component
            },
                "vfDemo",
                function (component) {
                    console.log("Lightning component rendered successfully!!");
                    // Event Service hander to handele the lightning component cusom event
                    $A.eventService.addHandler({ "event": "c:SendDataToVFPage", "handler": retriveEventData });
                });
        });


        function retriveEventData(event) {
            var recordTypeId = event.getParam("currentRecId");
            var eventRecordData = event.getParam("CurrentRecDetails");

            // passing data to outputtext lables
            document.getElementsByClassName("accName")[0].innerHTML = eventRecordData.Name;
            document.getElementsByClassName("accIndustry")[0].innerHTML = eventRecordData.Industry;
            document.getElementsByClassName("accPhone")[0].innerHTML = eventRecordData.Phone;
        }

    </script>
</apex:page>
Create Detail page button on the account select button type as visualforce and add the button to the Page Layout.
That's it.
Clcik the button from account record the component will render from vf page.

Result

Monday, May 27, 2019

How to call Lightning Web components from Visualforce page

This post explains how to call Lightning web components from the visualforce page.

From Summer 19 onwards we can use Lightning web component in the visualforce page,
normally to call lightning components in the visualforce page we used  $A.createComponent and $Lightning.use.
we can use the same concept as well in lightning web components.

Note: To work this functionality, API version should be above or equal to v46


Demo:

lwcInVisualforceDemo.html
<template>
    <lightning-card title="Calling Lightning Web Components From Visualforce Page" icon-name="standard:account">
        <template if:true={accData}>
            <table class="slds-table slds-table_bordered slds-table_cell-buffer slds-table_col-bordered">
                <thead>
                    <tr class="slds-text-title_caps">
                        <th scope="col">
                            <div title="Key">Account Name</div>
                        </th>
                        <th scope="col">
                            <div title="Value">Industry</div>
                        </th>
                    </tr>
                </thead>
                <tbody>
                    <template for:each={accData} for:item="acc">
                        <tr key={acc.key}>
                            <th scope="col">
                                <div>{acc.Name}</div>
                            </th>
                            <th scope="col">
                                <div>{acc.Industry}</div>
                            </th>
                        </tr>
                    </template>
                </tbody>
            </table>
        </template>
    </lightning-card>
</template>

lwcInVisualforceDemo.js
import { LightningElement, track, wire } from 'lwc';
// importing apex class and method to retrive accounts
import retriveAccounts  from '@salesforce/apex/LWCExampleController.fetchAccounts';

export default class LwcInVisualforceDemo extends LightningElement {

    // to track object name from vf page
    @track objName = 'Account';
    @track accData;
    @track error;

    // getting accounts using wire service
    @wire(retriveAccounts, {strObjectName : '$objName'})
    accounts({data, error}) {
        if(data) {
            this.accData = data;
            this.error = undefined;
        }
        else if(error) {
            this.accData = undefined;
            this.error = error;
            window.console.log(error);
        }
    }
}

LWCExampleController.cls
public inherited sharing class LWCExampleController {
    @AuraEnabled(Cacheable = true)
    public static list<Account> fetchAccounts(String strObjectName) {
        if(String.isNotBlank(strObjectName)) {
            return Database.query('SELECT Id, Name, Industry From ' + strObjectName + ' limit 10');
        }
        else {
            return null;
        }
    }
}
Create lightning out dependency Lightning application, and Visualforce page to call lwc component.

CallingLWCFromPage.page
<apex:page>
    <apex:includeLightning />
    <div id="lwcDemo" />
    <script>
    $Lightning.use("c:lwcInVisualforceApp", function() {
        $Lightning.createComponent("c:lwcInVisualforceDemo", {
            //pass parameter values to lwc js controller
            objName : "Account" // optional parameter, I already declared value in lwc js controller.
        },
        "lwcDemo",
            function(component) {
             console.log("Lightning Web Component created Successfully!!");
              // extend the functionality as per your requirement
            }
       );
    });
    </script>
</apex:page>

lwcInVisualforceApp.app
<aura:application  access="GLOBAL" extends="ltng:outApp" >
 <aura:dependency resource="lwcInVisualforceDemo"/>
</aura:application>

Result:

Resource:
https://releasenotes.docs.salesforce.com/en-us/summer19/release-notes/rn_lwc_vf.htm?edition=&impact=