Showing posts with label Lighting Experience. Show all posts
Showing posts with label Lighting Experience. Show all posts

Thursday, January 30, 2020

What is Full Form Of LWC?

LWC stands for Lightning Web Components .This will be used for building the components in lightning experience (like aura ).
  • These will uses html,modern java script and css.
  • It uses core web components standard.
  • Because it’s built on code that runs natively in browsers, Lightning Web Components is lightweight and delivers exceptional performance.
  • The existing aura and lwc components can co exist in lightning experience.
For more information please refer salesforce documentation.

Please comment or write us if you have any queries/requirements.

Please like,follow,bookmark,subscribe this site to receive daily updates.





Hope this helps you..Enjoy..!


Friday, January 24, 2020

How To Configure Console Components In Lightning Console Applications

Unfortunately Salesforce doesn't support console components in lightning experience.

If your existing component is linked to a visual force page and then you want to use this component as a console component in lightning experience the workaround is below.

1. Goto Service Setup

2. Open the App Manager Under User Interface Section

3. Select the application where you want to add console component and Click on Edit

4. Select Utility Items Under App Settings



5. Click on Add Utility Items and Select Visual Force Page option

6. Please give console component name and it's related visual force page(your vf page is not shown)

7. Your component is ready and it's available in the bottom left.


Please comment or write us if you have any queries/requirements.

Please follow,bookmark,subscribe this site to receive daily updates.

Facebook - https://www.facebook.com/ILoveCodingYou/?ref=bookmarks

Hope this helps you..Enjoy..!

Tuesday, December 31, 2019

typeAttributes in lightning-datatable or lightning:datatable

Basically typeAttributes are the one of the major building blocks of <lightning-datatable>(in LWC) or <lightning:datatable> (in Aura).This will help us to format the data types /output display and attaching some of actions to your data displayed in table at each cell level ,row level or at the columns level.

The typeAttributes are attached to each columns data type when your specifying the columns for your data table in your java script file.

Each typeAttributes is having pre-defined set of attributes/properties basis on the data type of your column (your defining at the time of columns for table).

Usually each column definition will have below properties.

{ 
  label: 'Issue Type',  //Column Header Shown in Table
  fieldName: 'Issue_type__c', //Api name of filed 
  type:"text",   // tells text,date,url,email etc..
  initialWidth: 90 //column width
}

After attaching the typeAttributes the sample code looks like below.The sample code will create a column with name Case Number and Looks like a button ,on click of it you can fire rowAction automatically.


{
        label: 'Case Number',
        type: 'button',
        initialWidth: 90,
        typeAttributes: {
            iconName: 'action:preview',
            title: 'Preview',
            variant: 'border-filled',
            alternativeText: 'View',
            disabled: false,
            label: { fieldName: 'CaseNumber' }, // to assign the value dynamically
            name: { fieldName: 'Case_Age__c' }, // to assign the value dynamically
        }
    },

//other colums

At any time if you want to set any of the typeAttribute object attribute dynamically please use below syntax


  attributeName: { fieldName: 'api name of column/any other variable' }
          

As I have mentioned on the top each typeAttributes will have some set of properties based on the data type of your column.

If you want to know what are the available attributes for each datatype please refer below.




Sample Column Code With typeAttributes:


const datatableColums =[
 //Column 1 of type Url
    {
        label: 'Customer Name', fieldName: 'nameUrl', type: 'url',
        typeAttributes: {
            label: { fieldName: 'Name' },
            target: '_top'
        }
    },
 
 //Column 2 of type button 
 {
        label: 'PNR',
        type: 'button',
        initialWidth: 90,
        typeAttributes: {
            iconName: 'action:preview',
            title: 'Preview',
            variant: 'border-filled',
            alternativeText: 'View',
            disabled: false,
            label: { fieldName: 'Pnr__c' },
            name: { fieldName: 'Pnr__c' },

        }
    },
 
 //Column 3 of type date 
 {
        label: "Closed Date",
        fieldName: "ClosedDate",
        type: "date",
        typeAttributes:{
            weekday: "long",
            year: "numeric",
            month: "long",
            day: "2-digit"
        }
    }
]

Please watch this space more useful stuff.

Please follow,bookmark,subscribe this site to receive daily updates.

Facebook - https://www.facebook.com/ILoveCodingYou/?ref=bookmarks


Hope this helps you..Enjoy..!






How To Build A Global Search URL In Lightning Experience Using JavaScript

If your in lightning experience on click of any actionable item you want to take the user to the Global Search and perform the search action using the dynamic search string.To get the url of the global search in lightning using java script please refer the below code.


var searchStr = 'Sree'; //Search String
var stringToEncode = '{"componentDef":"forceSearch:search","attributes":{"term":"'+searchStr+ '","scopeMap":{"type":"TOP_RESULTS"},"context":{"disableSpellCorrection":false,"SEARCH_ACTIVITY":{"term":"'+ searchStr + '"}}}}';
var encodedStr = btoa(stringToEncode); //Base64 encoding
var redirectUrl='/one/one.app?source=aloha#'+encodedStr;

The format of url must be

     String redUrl = '/one/one.app?source=aloha#'+base64EncodedSearchString;

If you want to the same thing using apex please refer this post

Hope this helps you..Enjoy..!

How To Build A Global Search URL In Lightning Experience Using Apex

If your in lightning experience on click of any actionable item you want to take the user to the Global Search and perform the search action using the dynamic search string.To get the url of the global search in lightning using apex please refer the below code.


String searchStr = 'Sree'; //Search String
String stringToEncode = '{"componentDef":"forceSearch:search","attributes":{"term":"'+searchStr+ '","scopeMap":{"type":"TOP_RESULTS"},"context":{"disableSpellCorrection":false,"SEARCH_ACTIVITY":{"term":"'+ searchStr + '"}}}}';
String encodedStr = EncodingUtil.base64Encode(Blob.valueOf(stringToEncode)); //Base64 encoding
String redirectUrl='/one/one.app?source=aloha#'+encodedStr;

The format of url must be

     String redUrl = '/one/one.app?source=aloha#'+base64EncodedSearchString;

If you want to the same thing using java script please refer this post


Hope this helps you..Enjoy..!




Saturday, December 28, 2019

Invalid Reference lightning-navigation Of Type Module in file .js Issue in LWC

Usually you will receive this error when your trying to import the navigation package of Salesforce for navigation in LWC.

Error Code:

import { LightningElement,api,track,wire } from 'lwc';
import { NavigationMixin } from 'lightning-navigation';

export default class YourClassName extends NavigationMixin(LightningElement)
{
  // your code
}

If you try to save the class with above code you will receive same error.So,to fix this issue please replace lightning-navigation with lightning/navigation while importing.

Solution:


import { LightningElement,api,track,wire } from 'lwc';
import { NavigationMixin } from 'lightning/navigation';

export default class YourClassName extends NavigationMixin(LightningElement)
{
  // your code
}

Hope this helps you..Enjoy..!

Monday, December 9, 2019

How To Check Whether User In Lightning Experience Or Classic Experience In LWC

Please use the below code in your LWC components under the java script controller.

ExperienceCheck.js
import {api,wire, track} from 'lwc';
export default class ExperienceCheck
{
 checkTheExperience(event)
 {
  if(document.referrer.indexOf(".lightning.force.com") > 0)
  {
   console.log('user in lightning experience');
  }
  
  else
  {
   console.log('user in classic experience');
  }
 }
}


Hope this helps you..Enjoy..!

Thursday, December 5, 2019

System.LimitException: Too many DML statements: 1

Exception:

If you use below code it will throw an error System.LimitException: Too many DML statements: 1 if you have any dml statement in your aura-method.






public with sharing class GetAllAccountsCntrl {
   @AuraEnabled(cacheable=true)
    public static List<Account> processAllAccounts() 
 {
        List<Account> lstAcc = new List<Account>();
  for(Account acc:[SELECT Id, Name,AccountSource,Website, Createddate FROM Account Limit 10])
  {
      acc.Name = 'LWC Testing...';
   lstAcc.add(acc);
  }
  Database.update(lstAcc,false);
  return lstAcc;
    }

}

Workaround:

Please remove (cacheable=true) from your method declared above,then this will work without any error



public with sharing class GetAllAccountsCntrl {
   @AuraEnabled
    public static List<Account> processAllAccounts() 
 {
        List<Account> lstAcc = new List<Account>();
  for(Account acc:[SELECT Id, Name,AccountSource,Website, Createddate FROM Account Limit 10])
  {
      acc.Name = 'LWC Testing...';
   lstAcc.add(acc);
  }
  Database.update(lstAcc,false);
  return lstAcc;
    }

}


Hope this helps you..Enjoy..!

How To Throw An Exception From Apex (Server Side) To JavaScript(Client Side) Controller in LWC

In lightning if you want to throw something as error from Apex class to client side Js controller ,we can use the salesforce standard class AuraHandledException.

Please look at the below code snippet where I'm trying to call an api to get the weather information,basis on the api response you can throw an exception(received in valid status,received process status but didn't got the expected response etc..) wherever you want throw an exception to the client side controller.

If your using try and catch in your code and if you raise an exception in try it will automatically goes to catch block and from there it will return to client side controller.


global class WeatherReportCntrl
{

@AuraEnabled(cacheable=true)
public static string fetchWeatherReport()
{
   Http http = new Http();
   HttpResponse res = new HttpResponse();
   HttpRequest req = new HttpRequest();
   req.setEndpoint('endpoint');
   req.setMethod('GET');
   try
    {
 res = http.send(req);                      
 string responseValue =res.getBody();
 if(res.getStatus()=='OK' && res.getStatusCode()==200 && String.isNotBlank(responseValue)
 {
    //while processing some error came then
    System.debug('responseValue--->'+responseValue);
    if(someerror)
     throw new AuraHandledException('Error while Processing data');  

   return 'data processed successfully';
 }
 else
       {
 // Received some invalid status code
  throw new AuraHandledException('Received some invalid status');
 
 }
    }
   Catch(Exception e)
   {
       AuraHandledException ex = new AuraHandledException(String.valueOf(e));
       ex.setMessage('Exception caught in catch block');
       throw ex;
   }
 } 
}


Hope this helps you..Enjoy..!

Wednesday, December 4, 2019

Hyperlinks in Lightning-DataTable To Open The Record Detail Page In Classic Console

In my previous post we have seen how to open record detail page directly from the lightning data table .If the same thing you wants to do it in Classic Console where your visual force is loading the LWC component then that will not work.

Please do the below changes to work the same in Classic console as well.The major change involves at Url param and target param in columns section.

Change the target attribute to '_top' and append the console#%2F in the redirection url

AccountListTable.js

import { LightningElement ,wire,track} from 'lwc';
import getAllOpps from '@salesforce/apex/GetAllAccountsCntrl.getAllAccounts';

export default class AccountListTable extends LightningElement {
    @track columns = [
        {
            label: 'Account Name',
            fieldName: 'nameUrl',
            type: 'url',
            typeAttributes: {label: { fieldName: 'Name'}, 
            target: '_top'},
            sortable: true
        },
        {
            label: 'Account Source',
            fieldName: 'AccountSource',
            type: 'text',
       
        },
  {
            label: 'Website',
            fieldName: 'Website',
            type: 'text',
        },
        {
            label: 'Close date',
            fieldName: 'closeDate',
            type: 'date',
        }

    ];

    @track error;
    @track listAccsData = [];


    @wire(getAllAccounts)
 wiredAllAccounts({ error, data }) {
        if (data) {
         
            this.listAccsData = data.map(record => Object.assign(
                { "nameUrl": '/console#%2F'+record.Id},
                record
            ));
        
        }
        else if (error) {
            this.error = error;
            this.listAccsData = null;
          
        }
 }
}


Hope this helps you..Enjoy..!

Issue With Lightning-Button Click Action (Outside the button) In LWC

Issue:

If your using <lightning-button> in your component and this button is invoking the action even if you clicked outside of the button(it means the horizontally anywhere on the screen).

Route Cause:

This is because by default if your not setting any width to the button it will considers the entire width as the scope of the button.So,if you click anywhere on the screen horizontally to this,it will invokes the action automatically.

If you look at the below image the blue line has occupied entire width of the screen ,it means the scope of the button is spread like blue line.So,if you click anywhere it's get invoked automatically.



Sample button code:


 <template if:true={showIsCheck} class="slds-is-relative">
     <lightning-button label="Check ?" title="Check" 
          variant="success" onclick={checkIsCan} 
          class="slds-align_absolute-center slds-m-top_medium ">
     </lightning-button>
    
        <div if:true={isLoading}>
            <lightning-spinner alternative-text="Loading..." variant="brand" size="large" class="slds-is-absolute"></lightning-spinner>
        </div>
 </template>

Workaround:

Please set the width of the button so that the scope of the button will automatically bounds within the button.If you look at the below code snippets and image you can clearly undertsraynd that as soon as I sets the width the blue line is becoming small(Scope of the button).


 <template if:true={showIsCheck} class="slds-is-relative">
        <lightning-button label="Check ?" title="Check" 
            variant="success" onclick={checkIsCan} 
          class="slds-align_absolute-center slds-m-top_medium slds-size_medium"></lightning-button>
    
        <div if:true={isLoading}>
            <lightning-spinner alternative-text="Loading..." variant="brand" size="large" class="slds-is-absolute"></lightning-spinner>
        </div>
 </template>


a)when size as small

b)when size as medium


Thanks for visiting..hope this helps you!

Tuesday, December 3, 2019

Hyperlinks in Lightning-DataTable To Open The Record Detail Page In Classic(Non-Console) Or Lightning(Non-Console)

If your using <lightning-datatable> in html file to show the list of records and you want to provide an hyper link to open the record from the same table.

This can be done easily easing the  typeAttributes of lightning-datatable. Please use the below code snippet to display list of accounts with an option to open the account with hyperlink.This below code works only in Lightning(Console or Non-Console) and in Classic Non-Console applications.

Note: If you want the same thing in classic console as well please refer my previous post

GetAllAccountsCntrl.cls


public with sharing class GetAllAccountsCntrl {
   @AuraEnabled(cacheable=true)
    public static List<Account> getAllAccounts() {
        return [SELECT Id, Name,AccountSource,Website, Createddate FROM Account Limit 10];
    }

}

AccountListTable.js

import { LightningElement ,wire,track} from 'lwc';
import getAllOpps from '@salesforce/apex/GetAllAccountsCntrl.getAllAccounts';

export default class AccountListTable extends LightningElement {
    @track columns = [
        {
            label: 'Account Name',
            fieldName: 'nameUrl',
            type: 'url',
            typeAttributes: {label: { fieldName: 'Name'}, 
            target: '_blank'},
            sortable: true
        },
        {
            label: 'Account Source',
            fieldName: 'AccountSource',
            type: 'text',
       
        },
  {
            label: 'Website',
            fieldName: 'Website',
            type: 'text',
        },
        {
            label: 'Close date',
            fieldName: 'closeDate',
            type: 'date',
        }

    ];

    @track error;
    @track listAccsData = [];


    @wire(getAllAccounts)
 wiredAllAccounts({ error, data }) {
        if (data) {
         
            this.listAccsData = data.map(record => Object.assign(
                { "nameUrl": '/'+record.Id},
                record
            ));
        
        }
        else if (error) {
            this.error = error;
            this.listAccsData = null;
          
        }
 }
}

AccountListTable.html

<template>
    <lightning-card  title="Account Details">
        <lightning-datatable data={listAccsData} columns={columns} key-field="Id"></lightning-datatable>        
    </lightning-card> 
</template>


Output






Note: If you want the same thing in classic console please refer my previous post

Hope this helps you..Enjoy..!

Thursday, November 28, 2019

How To Access Parent Object Or Relationship Object Fields In LWC DataTable

Lets consider a case where we have 2 objects as listed below.
  • Activities__c  // Child Object
  • Transaction__c    //Parent Object
Now if you want to display all activities related to a particular transaction and as well as you want to show some field values related to transaction on each activity record (Ex: PNR and Status).

Unfortunately similar to VF pages you can't directly access them in LWC templates .So,we have to do some changes on data set (list of recors) before we display it in html template.

Solution:

We have to set/update the related field column value for each record before pushing/adding it into the list.

this.allActivitiesData = data.map(
   record => Object.assign(
 { "Transaction__r.Status__c": record.Transaction__r.Status__c, "Transaction__r.PNR__c": record.Transaction__r.PNR__c},
  record
  )
);

Complete Solution With Sample Code:


ActivitiesFlowCntrl.cls

global class ActivitiesFlowCntrl
{
    
    public ActivitiesFlowCntrl()
    {
      System.debug('Inside constructor..');
    }

    @AuraEnabled(cacheable=true)
    public static List<Activities__c> fetchActivities(String recdId)
    {
        List<Activities__c> lstAct = new List<Activities__c>()
        lstAct = [SELECT id,Name,Act_Name__c,Act_Type__c,Amount__c,Start_Time__c,
                  End_Time__c,Act_UniqueId__c,Transaction__r.Status__c,
                  Transaction__r.PNR__c FROM Activities__c 
                  WHERE Transaction__c=:recdId];
       return lstAct;
    }
}

ActivitiesFlow.js

import { LightningElement, api, track, wire } from "lwc";
import fetchActivities from "@salesforce/apex/ActivitiesFlowCntrl.fetchActivities";

const columns = [
    { label: 'Id', fieldName: 'Name' },
    { label: 'Name', fieldName: 'Act_Name__c' },
    { label: 'Type', fieldName: 'Act_Type__c' },
    { label: 'Status', fieldName: 'Transaction__r.Status__c' },
    { label: 'PNR', fieldName: 'Transaction__r.PNR__c' },
    { label: 'Amount', fieldName: 'Amount__c', type: 'currency' },
    { label: 'StartTime', fieldName: 'Start_Time__c', type: 'date' },
    { label: 'End Time', fieldName: 'End_Time__c', type: 'date' },
    { label: 'UniqueId', fieldName: 'Act_UniqueId__c' }

];

export default class ActivitiesFlow extends LightningElement 
{
  
  @track allActivitiesData;
  
  @wire(fetchActivities, { recdId: '$sfrecordId' })
    wiredActivities({ error, data }) {
       if (data) 
       {
          this.allActivitiesData =  data.map(
      record => Object.assign(
  { "Transaction__r.Status__c": record.Transaction__r.Status__c, "Transaction__r.PNR__c": record.Transaction__r.PNR__c},
  record
       )
            );
         
        }
 else if (error) {
            this.error = error;
            this.allActivitiesData = undefined;
           
        }
 }
}

ActivitiesFlow.html

<template>
    <template if:true={allActivitiesData}>
        <lightning-datatable data={allActivitiesData} columns={columns} key-field="id" hide-checkbox-column="true"></lightning-datatable>
    </template>
</template>


Hope this helped you..Enjoy..!