GET AUTHORISATION CODE AND REFRESH TOKEN

Different ways for Getting Refresh Token:

1.Manually enter Client Id and Client secret in Input field.
Every Time user has to Manually Generate RefreshToken

2.Using Custom Label or Custom settings.
when the client Id/secret is placed in custom label, client Id/secret is not editable while Installing as managed package .
when the client Id/secret is placed in Custom settings, client Id/secret is editable while Installing as managed package.

Example:

The use case is to generate Refresh token manually inorder to track who is asking for Refresh Token and when the data comes in to salesforce,so inorder track all this information refresh token is generated manually.

In This Example I have used Input field to manually enter Client Id and Client Secret to get the Refresh Token.

ClientIdConsumer Key from Connected Apps.

ClientSecret- Consumer Secret from Connected Apps.

VISUALFORCE PAGE WITH SLDS:

<apex:page controller="RefreshTokenClass" >
<apex:slds />
<apex:form >
<div class="slds-form slds-form_stacked">
<div class="slds-form-element slds-size_2-of-4">
<label class="slds-form-element__label" for="input-id-01"><b>Client Id</b></label>
<div class="slds-form-element__control">
<apex:inputText id="clienti" styleClass="slds-input" value="{!clientid}"/>
</div>
</div>
<div class="slds-form-element slds-size_2-of-4">
<label class="slds-form-element__label" for="input-id-01"><b>Client Secret</b></label>
<div class="slds-form-element__control">
<apex:inputText id="clientsecr" styleclass="slds-input" value="{!clientsecret}" />
</div>
</div>
</div>
<br/>
<apex:commandButton action="{!auth_step_1}" value="Step1:Get Authorization Code"/>&nbsp;
<apex:commandButton action="{!auth_step_2}" value="Step2:Get RefreshToken"/>
<br/>
<div style="display:{!IF($CurrentPage.parameters.code != Null && str = Null ,'block','none')}">
<label><b>Authorization Code:</b></label>
<div class="slds-page-header slds-p-top_medium">
<b>{!$CurrentPage.parameters.code}</b>
</div>
</div>
<div style="display:{!IF(str = Null, 'none','block')}">
<label><b>Refresh Token:</b></label>
<div class="slds-page-header slds-p-top_medium" style="display:{!IF(str = Null,'none','block')}">
<b>{!str}</b>
</div>
</div>
</apex:form>
</apex:page>

 

APEX CLASS:

public class RefreshTokenClass {
private auth_response rt;
public string str {get; set;}
public string clientid {get; set;}
public string clientsecret {get; set;}
public pagereference auth_Step_1(){
String auth_url = 'https://login.salesforce.com/services/oauth2/authorize';
String params =
'?response_type=code' +
'&client_id=' + encodingUtil.urlencode(clientid,'UTF-8') +
'&redirect_uri=https://c.na53.visual.force.com/apex/RefreshToken';
pageReference pr = New PageReference(auth_url + params);
return pr.setRedirect(false);
}
public pagereference auth_Step_2(){
HttpRequest req = new HttpRequest();
Http http = new Http();
String auth_url = 'https://login.salesforce.com/services/oauth2/token';
String params =
'?code=' + apexPages.currentPage().getParameters().get('code') +
'&grant_type=authorization_code' +
'&client_id=' + encodingUtil.urlencode(clientid,'UTF-8') +
'&client_secret='+ clientsecret +
'&redirect_uri=https://c.na53.visual.force.com/apex/RefreshToken';
system.debug('auth_Step_2>>>>>>'+params);
req.setMethod('POST');
req.setEndpoint(auth_url + params);
HTTPResponse resp = http.send(req);
rt = (auth_response)json.deserialize(resp.getBody(),auth_response.class);
system.debug('rt>>>>'+ rt );
str = rt.refresh_token;
return null ;
}
private class auth_response{
public string refresh_token;
public string access_token;
}
}

Lets Learn Together!!!

Lightning Record Edit Form in Lightning web component

How lightning record edit form can help your business and developer…

Scenario:

Get Account details by clicking new button and the page which have been opened should have some limited amount of fields how business needed and it should have Cancel, save and save & New button.

1.Save:
Record has to be saved without apex controller and need to redirect respected record page if the record got saved or if there is error it should show error message and withstand in same page.

2.Save & New:
Assume if you click Save & New button, it should save the record and it should show success Notification & reset page with empty field values.

3.Cancel:
if you click new button from Related list, then it should redirect to previous record page or if you click new button from List view, then it should redirect to List View.

Lets do this 🙂

HTML:

<template>
<lightning-card>
<lightning-record-edit-form object-api-name='Account' onsuccess={handleSuccess}
onerror={handleError} >
<header class="slds-modal__header">
<div class="slds-text-heading_medium slds-modal__title slds-hyphenate">New Account Details</div>
</header>
<div class="slds-page-header">
<div class="slds-page-header__row">
Account Detail
</div>
</div>
<div class="slds-grid slds-gutters">
<div class="slds-col slds-size_1-of-12">
<span></span>
</div>
<div class="slds-col slds-size_5-of-12">
<span>
<lightning-input-field field-name="Name"></lightning-input-field>
<lightning-input-field field-name="Customer_Name__c"></lightning-input-field>
<lightning-input-field field-name="Opportunity__c"></lightning-input-field>
<lightning-input-field field-name="TaxCode3__c"></lightning-input-field>
</span>
</div>
<div class="slds-col slds-size_5-of-12">
<span>
<lightning-input-field field-name="CopyAccountValues__c"></lightning-input-field>
<lightning-input-field field-name="TaxCode1__c"></lightning-input-field>
<lightning-input-field field-name="TaxCode2__c"></lightning-input-field>
</span>
</div>
<div class="slds-col slds-size_1-of-12">
<span></span>
</div>
</div>
<div class="slds-m-top_large slds-grid slds-grid_align-center slds-align–absolute-center">
<lightning-button variant="brand" label="Cancel" type="cancel" onclick={handleCancel}></lightning-button>
&nbsp;&nbsp;
<lightning-button type="submit" variant="brand" label="Save"></lightning-button>
&nbsp;&nbsp;
<lightning-button type="submit" variant="brand" label="Save & New" onclick={saveAndNewClick}></lightning-button>
</div>
<br/><br/>
</lightning-record-edit-form>
</lightning-card>
</template>

Js:

import { LightningElement } from 'lwc';
import { NavigationMixin } from 'lightning/navigation';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
export default class LightningRecordEditForm extends NavigationMixin (LightningElement) {
redirect = true;
resetpage = false;
handleSuccess(event) {
const even = new ShowToastEvent({
title: 'Success!',
message: 'Record created!',
variant: 'success'
});
this.dispatchEvent(even);
if(this.redirect == true){
console.log('handleSuccess'+this.redirect);
let creditnoteId = event.detail.id;
this[NavigationMixin.Navigate]({
type: 'standard__recordPage',
attributes: {
recordId:creditnoteId,
objectApiName:'Account',
actionName:'view'
}
})
}
if(this.resetpage== true){
this.handleReset();
}
}
handleError(event){
const evt = new ShowToastEvent({
title: 'Error!',
message: event.detail.detail,
variant: 'error',
mode:'dismissable'
});
this.dispatchEvent(evt);
}
saveAndNewClick() {
this.redirect = false;
this.template.querySelector('lightning-record-edit-form').submit(this.fields);
this.resetpage = true;
}
handleReset() {
const inputFields = this.template.querySelectorAll(
'lightning-input-field'
);
if (inputFields) {
inputFields.forEach(field => {
field.reset();
});
}
}
handleCancel(event){
var url = window.location.href;
var value = url.substr(0,url.lastIndexOf('/') + 1);
window.history.back();
return false;
}
}

In the above HTML code, there are two parameters onsuccess and onerror which work as similar as standard controller in visualforce page for saving record and throwing error details before saving record.

When we click Save&New standard save functionality should work, but it shouldn’t redirect to any page, instead it should withstand in same page and clear the field values. so we have a parameter (this.redirect = false;) to stop the redirection to record page or list page.

There is one more parameter to handle the reset, only when we click save & New (this.resetpage = true;)

Let’s Learn Together!!!

Cancel in Lightning web component

When you develop Lightning web components, while clicking cancel it has to take you back to the previous page,but in lightning there is no direct way to go back to previous page.

Scenario:
Assume there is a New Button which is available in parent object Record page and the same button is available in Related list,In both scenarios it has to navigate different pages.but as of now in salesforce there is no parameter to hold the previous page data, so we are now directly hard coding in js file to navigate to record page or List page like below,

handleCancel(event){
this[NavigationMixin.Navigate]({
type: “standard__objectPage”,
attributes: {
objectApiName: ‘c2g__codaCreditNote__c’,
actionName: ‘list’
},
state: {
filterName: ‘Recent’
}})
}

But above code will not work in all scenarios, because the button is in various locations and previous page differs, so below code is alternative way to overcome to navigate to previous page

Button:
<lightning-button variant=”brand” label=”Cancel” type=”cancel” onclick={handleCancel}/>

js:
handleCancel(event){
var url = window.location.href;
var value = url.substr(0,url.lastIndexOf(‘/’) + 1);
window.history.back();
return false;
}

This code will work for all scenarios for Cancel button.

Learning Never Ends!!!

URL Hack Pre-populate field with default values in Lightning Experience

From Spring’20, When you click on button, you can navigate to a Record’s Create Page with Default Field Values. After clicking Save or Quick save be patient for few seconds and refresh the page using Ctrl + F5.

/lightning/o/EnterObjectAPIName__c/new?
defaultFieldValues=
EnterFieldAPIName__c={!Account.Id}
&retURL=%2Fa1W%2Fo

For navigating pass return url parameters as Record Id, like this
retURL=/{!EnterObjectAPIName__c.Id}

or like this,
retURL=%2FOBJId%2Fo

Example of a Contact ID (003D0000001aH2A)

Object ID Prefix
003

Place the Object Id prefix in return URL.

Filter reports via url parameters in lightning experience

ISSUE:
I had an issue after refreshing sandbox my reports were not working correctly.I was able to get all values in URL but it was not passing to report Filter values…

Classic URL: https://naveendhanaraj.my.salesforce.com/00OG00000079T1hMBY?pv0=004751&pv1=2345

LIGHTNING URL: https://naveendhanaraj.lightning.force.com/lightning/r/Report/00OG00000079T1hMBY/view?fv0=004751&fv1=2345

After Refreshing your sandbox make sure filter in report doesn’t have Is Locked Equal to True.

Get List of Visualforce Pages from Salesforce Org Using Developer Console

List of visualforce page created by users:
1.Go To Query Editor in Developer Console.
2.Run the below Query.

SELECT Name, MasterLabel,namespaceprefix, ApiVersion, CreatedDate FROM ApexPage WHERE namespaceprefix = NULL

3. Above Query Gives you list of all visualforce page created by users in organization.

Get List of visualforce page created by users and installed packages run the below query:

SELECT Name, MasterLabel,namespaceprefix, ApiVersion, CreatedDate FROM ApexPage where namespaceprefix != NULL

Spring’19 Treasure’s

1.Welcome Lightning Playground & Start Playing in your Lightning Component Library.

2.Welcome New Lightning Flow Builder,Finally Live.

3.Choose your Default List View by clicking Pin.

4.Lightning Email Templates,

5.Customize the Help Menu.

Help icon at the top of every page opens a menu full of resources relevant to that page—help topics.

 6.Create Big Objects in Lightning UI.

7.Change your Template By Clicking Edit Page under gear icon at top right hand side of the page.

8.Five New Standard Components To the list:
        i.Cisco Webex Teams Conversations.
        ii.  Cisco Webex Teams Spaces.
        iii.Einstein Next Best Action.
        iv.industries_manufacturing:agreementTerms.
        v.Surveys.

NOTE:

Some features in Spring ’19 may be Released in scheduled time,nor it might not be available.These above features content are from my knowledge which I found these informations via Lightning Experience Roadmap and from Ideas.So wait until you get the official confirmation from salesforce Release notes whether these features may be Released or not.So watch out Trailblazer community Release Readiness Group for more Details about
Spring ’19 features..

Hope This Helps!!!