+ Start a Discussion
abu saleh khan 20abu saleh khan 20 
I am trying to pull picklist values in to my component using schema and its methods. I am getting all the values through server controller, but in my component labels are not populating but it is showing picklist structure.

Lightning Component:

<aura:component controller="PickListController" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
    <aura:attribute name="aname" type="Account" default="{'sObjectType':'Account'}"/>
    <aura:attribute name="picvalue" type="List"/>
   <aura:handler name="init" value="{!this}" action="{!c.doInit}" /> 
        <lightning:input label="Enter Your Name: " value="{!v.aname.Name}"/>
        <lightning:input label="Phone Number: " value="{!v.aname.Phone}"/>
       <lightning:select value="{!v.aname.Rating}" label="Rating">       
            <option value="choose">Choose one...</option> 
            <aura:iteration items="{!v.picvalue}" var="s">
                <option value="{!s.value}"/>             
            </aura:iteration> 
        </lightning:select> 
    <lightning:button label="Submit" onclick="{!c.go}"/>
</aura:component>

Js:

({
    doInit : function(component) {        
        var pickvar = component.get("c.getPickListValuesIntoList");
        pickvar.setCallback(this, function(response) {
            var state = response.getState();
            if(state === 'SUCCESS'){
                var list = response.getReturnValue();
                component.set("v.picvalue", list);
            }
            else if(state === 'ERROR'){
                //var list = response.getReturnValue();
                //component.set("v.picvalue", list);
                alert('ERROR OCCURED.');
            }
        })
        $A.enqueueAction(pickvar);
    },
    go : function(component){
        var cvar = component.get("v.aname");
        var action = component.get("c.insertValues");
        action.setParams({acc: cvar});
        action.setCallback(this, function(response) {
            var state = response.getState();
            if(state === 'SUCCESS'){
            var list1 = response.getReturnValue();
            //component.set("v.picklistValues", list);
            alert('Record Created Successfully '+list1);
            }
            else if(state === 'INCOMPLETE'){
                alert('Something is missing');   
            }
            else if(state === 'ERROR'){
                alert('Insertion Failed');   
            }
        })
        $A.enqueueAction(action);
    }
})

Server Controller:

public class PickListController {
    @AuraEnabled        
    public static List<String> getPickListValuesIntoList(){
        List<String> pickListValuesList = new List<String>();
        Schema.DescribeFieldResult fieldResult = Account.Rating.getDescribe();
        List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
        for( Schema.PicklistEntry pickListVal : ple){
            pickListValuesList.add(pickListVal.getLabel());
            System.debug('Values in Rating are: '+pickListValuesList);
        }     
        return pickListValuesList;
    }
    @AuraEnabled        
    public static Id insertValues(Account acc){
        insert acc;   
        return acc.id;
    }
}

User-added image
Best Answer chosen by abu saleh khan 20
Maharajan CMaharajan C
HI Abu,

Change your Lightning:select as below then it works:

<lightning:select value="{!v.aname.Rating}" label="Rating">       
    <option value="choose">Choose one...</option> 
        <aura:iteration items="{!v.picvalue}" var="s">
                <option value="{!s}">{!s}</option>
        </aura:iteration> 
</lightning:select> 

Can you please Let me know if it helps or not!!!

If it helps don't forget to mark this as a best answer!!!


Thanks,
Maharajan.C
.12.12 
I want only one value from the json but i'm getting all the values how can i stop iteration or is there any way to show only one row like keeping size please help to find the solution

Thank you in Advance,

<tbody>
                        <aura:iteration items="{!v.jsonValues}" var="item" indexVar="rowIndex">  
                            <tr data-data="{!rowIndex}">
                                <td role="gridcell" tabindex="-1" data-label="Record Type Name">                            
                                    <span class="slds-grid slds-grid_align-spread">
                                        <div class="slds-truncate">                                        
                                            <span class="slds-truncate">{!item.firstName}</span>
                                        </div>
                                    </span>                            
                                </td>
                            </tr>
                        </aura:iteration>
                    </tbody>

Original Output:-
      Ramesh
      Suresh
      Rakesh

Expected Output:-
    Ramesh
Best Answer chosen by .12
Maharajan CMaharajan C
Hi, 

Please try the below any one of the way:
 
<tbody>
	<aura:iteration items="{!v.jsonValues}" var="item" indexVar="rowIndex"> 
		<aura:if isTrue="{! rowIndex == 0 }">
			<tr data-data="{!rowIndex}">
				<td role="gridcell" tabindex="-1" data-label="Record Type Name">                            
					<span class="slds-grid slds-grid_align-spread">
						<div class="slds-truncate">                                        
							<span class="slds-truncate">{!item.firstName}</span>
						</div>
					</span>                            
				</td>
			</tr>
		</aura:if>
	</aura:iteration>
</tbody>

OR
 
<tbody>
    <aura:if isTrue="{!not(empty(v.jsonValues))}">
        <tr>
            <td role="gridcell" tabindex="-1" data-label="Record Type Name">                            
                <span class="slds-grid slds-grid_align-spread">
                    <div class="slds-truncate">                                        
                        <span class="slds-truncate">{!jsonValues[0].firstName}</span>
                    </div>
                </span>                            
            </td>
        </tr>
    </aura:if>
</tbody>

Thanks,
Maharajan.C
Steve ConnellySteve Connelly 
The AccountTeamMember widget (Lightning Component) displays the Role API Name instead of the Role Label.

How do i change the lightning component so it will display the role label instead of the role API name?

Here is the component code:
<aura:component implements="flexipage:availableForRecordHome,force:hasRecordId" access="global" controller="AccountTeamHelper">
    <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
    <aura:attribute name="TeamMembers" type="AccountTeamMember[]" /> 	  
    <lightning:card title="Account Team" iconName="custom:custom103">
        <div style="margin: 0px 5px">
            <p class="slds-p-horizontal_small">
                <aura:if isTrue="{!v.TeamMembers.length > 0}">
                <aura:iteration items="{!v.TeamMembers}" var="member">
                    <!-- <span style="display: inline-block; margin: 3px;"><lightning:avatar src="{!member.User.SmallPhotoUrl}" alternativeText="(Avatar)" fallbackIconName="standard:avatar" variant="circle" /></span> -->
                    <span><a href="{!'/one/one.app#/sObject/' + member.User.Id + '/view'}">{!member.User.FirstName}&nbsp;{!member.User.LastName}</a> - {!member.TeamMemberRole}</span><br/>
                </aura:iteration>
                <aura:set attribute="else">
                    No account team members have been assigned to this account.
                </aura:set>
                </aura:if>
        	</p>
        </div>
    </lightning:card>
</aura:component>

 
Best Answer chosen by Steve Connelly
Maharajan CMaharajan C
Can you please mark the best answer if your issue solved !!!
Jonathan Wolff 7Jonathan Wolff 7 
Hello, I build a List button that Includes a Visualforce Page. When I chose Accounts in List view and click account I only see the blank Page without the account fields. Please tell me how to change it.

<apex:page standardController="Account" renderAs="pdf" recordSetVar="accounts" >
 

<h1>Welcome to APP!</h1>
 
<p>Thank you, <b><apex:outputText value=" {!Account.Name}"/></b>, for 
   working with APP.</p>
 
<p>Your account details are:</p>
 
<table>
<tr><th>Account Name</th>
    <td><apex:outputText value="{!Account.Name}"/></td>
    </tr>
<tr><th>Account Rep</th>
    <td><apex:outputText value="{!Account.Owner.Name}"/></td>
    </tr>
<tr><th>Customer Since</th>
    <td><apex:outputText value="{0,date,long}">
        <apex:param value="{!Account.CreatedDate}"/>
        </apex:outputText></td>
    </tr>
</table>
    
</apex:page>

User-added image


Result:

User-added image
Best Answer chosen by Jonathan Wolff 7
Maharajan CMaharajan C
Hi Jonathan,

Please try the below code:
 
<apex:page standardController="Account" renderAs="pdf" recordSetVar="accounts" extensions="AccountListPDFController">
    
    
    <h1>Welcome to APP!</h1>
    
    <apex:repeat value="{!accounts}" var="Account">
        
        <p>Thank you, <b><apex:outputText value=" {!Account.Name}"/></b>, for 
            working with APP.</p>
        
        <p>Your account details are:</p>
        
        <table>
            <tr><th>Account Name</th>
                <td><apex:outputText value="{!Account.Name}"/></td>
            </tr>
            <tr><th>Account Rep</th>
                <td><apex:outputText value="{!Account.Owner.Name}"/></td>
            </tr>
            <tr><th>Customer Since</th>
                <td><apex:outputText value="{0,date,long}">
                    <apex:param value="{!Account.CreatedDate}"/>
                    </apex:outputText></td>
            </tr>
        </table>
    </apex:repeat>
</apex:page>

Apex Class:
 
public class AccountListPDFController {
    public List<Account> accounts{get;private set;}
    public AccountListPDFController(ApexPages.StandardSetController stdSetController){
        accounts = (List<Account>) stdSetController.getSelected();
    }
}

Thanks,
Maharajan.C
​​​​​​​​​​​​​​
Prasan De AlwisPrasan De Alwis 
Could you please help me to align right side(close to right side border) toggle button, button and help text. Currently it is showing close to center. Below is the UI of the LWC Component. 

User-added image

Please find the HTML full code. I have used list elements show button in horizontal line.

HTML Code
 
<template>
    <lightning-card   title="User Management" icon-name="standard:user" >
            <div class="slds-col slds-size_10-of-12 slds-p-top_medium">
                <lightning-layout multiple-rows="true" class="slds-m-left_xx-large">
                    <lightning-layout-item size = "12" margin= "around-small">
                           <span style="float: right;">
                        <div style="float: right;">
    
                            <ul class="slds-button-group-row slds-m-left_xx-large" >
                                <!-- <template if:true={hasPrev}>-->
    
                                <li class="slds-button-group-item" >
                                    <template if:true={showToggle}>
                                        <lightning-input type="toggle"
                                                         label="Enable Process"
                                                         onchange ={deactivateProcess}
                                                         checked= "{ToggleChecked}"
                                                         class="slds-m-right_xx-small slds-m-left_xx-large" >
                                        </lightning-input>
                                        </template>
    
                                </li>
                                <li class="slds-button-group-item" >
                                    <lightning-button class="slds-m-right_xxx-small slds-m-top_none slds-m-bottom_xxx-small" slot="actions" label="Submit" onclick={updateRecords}>
                                    </lightning-button>
                                    <lightning-helptext class="slds-m-top_none slds-m-bottom_xxx-small slds-m-right_xx-small " content="The users that will exclude from the de-activation."></lightning-helptext>
    
                                </li>
                                </ul>
    
                  </div>
                                </span>
                        </lightning-layout-item>
                    </lightning-layout>
    
            </div>
        <div class="slds-p-left_medium">
            <div class="slds-col slds-size_12-of-12 slds-p-top_medium">
                <div class="slds-p-around_medium lgc-bg">
                    <lightning-datatable
                            key-field="UserId"
                            columns={columns}
                            data={currentPageData}
                            selected-rows= {allSelectedRows}
                            onrowselection= {rowSelection}
                            sorted-by={sortBy}
                            sorted-direction={sortDirection}
                            onsort={handleSortdata}
                    >
                    </lightning-datatable>
                </div>
                <div class="slds-col slds-size_10-of-12 slds-p-top_medium">
                    <lightning-layout multiple-rows="true">
                        <lightning-layout-item size = "12" margin= "around-small">
                            <div class="slds-align_absolute-center">
                                <ul class="slds-button-group-row">
                                    <!-- <template if:true={hasPrev}>-->
                                    <li class="slds-button-group-item" >
                                            <button class="slds-button slds-button_neutral" onclick ={onFirst} disabled={disabledConditionFirst}> First
                                            </button>
                                    </li>
                                    <li class="slds-button-group-item" >
                                              <button class="slds-button slds-button_neutral" disabled={disabledConditionPrev} onclick ={onPrev}> Prev
                                              </button>
                                    </li>
                                    <li class="slds-button-group-item" >
                                          <button class="slds-button slds-button_neutral" disabled={disabledConditionNext} onclick={onNext} >Next</button>
                                    </li>
                                    <li class="slds-button-group-item" >
                                            <button class="slds-button slds-button_neutral"  onclick ={onLast} disabled={disabledConditionLast}> Last
                                            </button>
                                    </li>
                                    <!--</template>-->
                                </ul>
                            </div>
                            </br>
                            <div class="slds-align_absolute-center" >
                        <span
                                disabled={disabledCondition}>Total Records: {totalRecordCount} </span>
                            </div>
                            <div class="slds-align_absolute-center" >
                                <span disabled={disabledCondition}>Page ({page} of {numberOfPages}) </span>
                            </div>
                        </lightning-layout-item>
                    </lightning-layout>
                </div>
            </div>
        </div>
        <div if:true={showLoadingSpinner}>
            <lightning-spinner alternative-text="Loading" size="large"></lightning-spinner>
        </div>
    </lightning-card>


JS

import { LightningElement, track, wire, api} from 'lwc';
import getUserList from '@salesforce/apex/UserManagementController.getUserList';
import userRecordsUpdate from '@salesforce/apex/UserManagementController.userRecordsUpdate';
import { refreshApex} from '@salesforce/apex';
import { ShowToastEvent} from 'lightning/platformShowToastEvent';
import getProfile from '@salesforce/apex/UserManagementController.getProfile';
import updateUserManagementProcess from '@salesforce/apex/UserManagementController.updateUserManagementProcess';

export default class Usermanagement extends LightningElement {

  //Display Coulmns on Datatable
  @track columns = [

    {
      label: 'Name',
      fieldName: 'recordLink',
      type: 'url',
      typeAttributes: { label: { fieldName: "FullName" }, tooltip:"Name", target: "_blank" },
      sortable: true,
      cellAttributes: {
        alignment: 'left'
      },
      initialWidth: 200,
    },
    {
      label: 'Email',
      fieldName: 'Email',
      type: 'text',
      sortable: true,
      cellAttributes: {
        alignment: 'left'
      },
      initialWidth: 200,
    },
    {
      label: 'Profile',
      fieldName: 'ProfileName',
      type: 'text',
      sortable: true,
      cellAttributes: {
        alignment: 'left'
      },
      initialWidth: 170,
    },
    {
      label: 'Role',
      fieldName: 'RoleName',
      type: 'text',
      sortable: true,
      cellAttributes: {
        alignment: 'left'
      },
      initialWidth: 200,
    },
    {
      label: "Last Login Date",
      fieldName: "LastLoginDate",
      type: "date",
      typeAttributes: {
        year: "numeric",
        month: "2-digit",
        day: "2-digit",
        hour: "2-digit",
        minute: "2-digit",
        second: "2-digit"
      },
      sortable: true,
      cellAttributes: {
        alignment: 'left'
      },
      initialWidth: 200,
    },
    {
      label: 'isFrozen',
      fieldName: 'isFrozen',
      type: 'text',
      sortable: false,
      cellAttributes: {
        alignment: 'left'
      },
      initialWidth: 100,
    },
    {
      label: 'isDeactivate',
      fieldName: 'isDeactivate',
      type: 'text',
      sortable: false,
      cellAttributes: {
        alignment: 'left'
      },
      initialWidth: 125,
    }

  ];

  // Track Gloabal variables
  @track showLoadingSpinner = false;
  @track error;
  @track page = 1;
  @track perpage = 20;
  @track pages = [];
  @track disabledConditionNext = true;
  @track disabledConditionPrev = true;
  @track disabledConditionFirst = true;
  @track disabledConditionLast = true;
  @track preSelectedRows = [];
  @track totalRecordCount = 0;
  @track numberOfPages = 1;
  @track sortBy;
  @track sortDirection;
  @track ToggleChecked;

  //Gloabal variables
  data = [];
  @api allDeSelectedRows = [];
  pageSlice;
  numOfPreviousPages;
  showToggle = false;
  wiredActivities;
  @track profName;

  //  Initial Method Call
  connectedCallback() {
    console.log('Initial' );
    this.init();
  }

  //Enable Deactivate Process button for Admins based on profile
  @wire(getProfile)
  wiredActivities({ error, data }) {
    if (data){
      console.log('profName==> '+JSON.stringify(data));

      this.profName = data;
      if(this.profName == 'System Administrator'){
        this.showToggle = true;
      }else{
      this.showToggle = false;
}
      console.log(this.profName);
      this.error = undefined;
     } else if (error) {
      this.error = error;
      this.data = undefined;

  }
}

  // Initial Method Call - Populate data on UI
  async init() {
    try {
      this.disabledConditionNext = true;
      this.disabledConditionPrev = true;
      this.disabledConditionFirst = true;
      this.disabledConditionLast = true;
      this.showLoadingSpinner = true;
      await getUserList()
        .then((result, error) => {
          console.log('result =' + result);
          var userList = JSON.parse(result);
          if (userList) {
             var tempUserList = [];
             userList.userMngtWrapperList.forEach((record) => {
                 let tempUserRec = Object.assign({}, record);
                 tempUserRec.recordLink = '/' + tempUserRec.UserId;
                 tempUserList.push(tempUserRec);
             });
            this.data = tempUserList;
            this.preSelectedRows = userList.selectedUserIdSet;
            this.ToggleChecked = userList.enableUserMngmtProcess;
            this.allSelectedRows = [];
            //this.data = this.data;
            console.log('this.data new =' + this.data);
            console.log('allSelectedRows =' + this.allSelectedRows);
            console.log('preSelectedRows =' + this.preSelectedRows);
            this.totalRecordCount = this.data.length;
            this.error = undefined;
          } else if (error) {
            console.error(error);
            this.data = undefined;
          }
        });
      this.setPages(this.data);

      if (this.data.length == 0) {
        this.dispatchEvent(
          new ShowToastEvent({
            title: 'No records to Display',
            message: 'No users to de-activates',
            variant: 'info'
          })
        );
      }
      this.showLoadingSpinner = false;

    } catch (error) {
      this.error = error;
    } finally {
      this.showLoadingSpinner = false;
    }
  }

/**
 * Below Methods are to Manipulate Page Load,Navigation and page click
 * pagesList
 * currentPageData
 * pageData
 * setPages
 * onPageClick
 * onNext
 * onPrev
 * onFirst
 * onLast
 * changePage
 */

  // Get Page list
  get pagesList() {
    let mid = Math.floor(this.perpage / 2) + 1;
    if (this.page > mid) {
      return this.pages.slice(this.page - mid, this.page + mid - 1);
    }
    return this.pages.slice(0, this.perpage);
  }

  // Get Data to load to current Page
  get currentPageData() {
    return this.pageData();
  }

 // Get Current Page Data based on page Number
  pageData = () => {
    let numberOfPages = Math.ceil(this.data.length / this.perpage);
    this.numberOfPages = numberOfPages;
    let page = this.page;
    let perpage = this.perpage;
    let startIndex = (page * perpage) - perpage;
    let endIndex = (page * perpage);

    if (this.numberOfPages < 2)
    {
        this.disabledConditionNext = true;
        this.disabledConditionPrev = true;
        this.disabledConditionLast = true;
        this.disabledConditionFirst = true;
    }
    else if (this.page  == this.numberOfPages)
    {
         this.disabledConditionNext = true;
         this.disabledConditionPrev = false;
         this.disabledConditionLast = true;
         this.disabledConditionFirst = false;
    }
    else if (this.page  == 1)
    {
          this.disabledConditionNext = false;
          this.disabledConditionPrev = true;
          this.disabledConditionLast = false;
          this.disabledConditionFirst = true;
    }
    else // if (this.page  < this.numberOfPages)
    {
          this.disabledConditionNext = false;
          this.disabledConditionPrev = false;
          this.disabledConditionLast = false;
          this.disabledConditionFirst = false;
    }

    this.pageSlice = this.data.slice(startIndex, endIndex);
    return this.data.slice(startIndex, endIndex);
  }

  // Get Number of pages need to be visible based on the data amount
  setPages = (data) => {
    let numberOfPages = Math.ceil(data.length / this.perpage);
    this.numOfPreviousPages = numberOfPages;
  }

  // Page Click event
  onPageClick = (e) => {
    this.page = parseInt(e.target.dataset.id, 10);
    }
  }

  // First Page button Click
  onFirst = () => {
    this.changePage(1);
  }

 // Last Page button Click
  onLast = () => {
    this.changePage(this.numberOfPages > 0 ? this.numberOfPages : 1);
  }

  // Page Data Change based on page number
  changePage(pageNumber) {

    let pageData = this.pageData();
    // Preserve rows outside current page and add rows from current page
    this.allSelectedRows = this.allSelectedRows.filter((rowId) => !pageData.find((record) => record.userId === rowId)).concat(this.template.querySelector('lightning-datatable').selectedRows);
    //Distinct the dataset
    this.allSelectedRows = this.allSelectedRows.filter((v, i, a) => a.indexOf(v) == i);
    console.log('changePage-allSelectedRows = ' + this.allSelectedRows);
    this.page = pageNumber;
    pageData = this.pageData();

    console.log('changePage - this.preSelectedRows in current page =' + this.preSelectedRows);
 }

 // On Row Selection - when select/deselect Checkbox
 rowSelection(evt) {
    let deselectedRecs = [];
    this.allSelectedRows = this.allSelectedRows.filter((v, i, a) => a.indexOf(v) == i);
    const selectedRows = evt.detail.selectedRows;
    console.log('rowSelection - Selected Rows are ' + JSON.stringify(selectedRows));
    console.log("rowSelection - selectedRows.length" + selectedRows.length);
    //concat new selected ids to allSelectedRows list
    this.allSelectedRows  = selectedRows
              .map(x => x.UserId)
              .concat(this.allSelectedRows ).filter((v, i, a) => a.indexOf(v) == i);
    console.log("rowSelection - this.allSelectedRows concat new selected ids= " + this.allSelectedRows);
    //remove new selected ids from deselectedRecs list
    this.deselectedRecs = this.pageSlice
        .filter(x => !selectedRows.includes(x))
        .concat(selectedRows.filter(x => !this.pageSlice.includes(x)))
        .map(x => x.UserId).filter((v, i, a) => a.indexOf(v) === i);
    console.log('rowSelection - Deselected Recs are original ' + this.deselectedRecs);
    console.log('rowSelection - deselectedRecs.length ' + this.deselectedRecs.length);
    if (this.deselectedRecs.length > 0) {
        //remove deselected ids from allSelectedRows list
        this.allSelectedRows = this.allSelectedRows.filter(item => !this.deselectedRecs.includes(item)).filter((v, i, a) => a.indexOf(v) === i);
    }
    console.log('rowSelection - Final allSelectedRows= ' + this.allSelectedRows);
  }

  updateRecords(event) {
    console.log('this.allSelectedRows updateRecords'+ this.allSelectedRows);
      console.log('this.preSelectedRows updateRecords'+ this.preSelectedRows);
    this.allDeSelectedRows = this.preSelectedRows
                                  .filter(item => !this.allSelectedRows.some(obj => obj === item))
                                  .filter((v, i, a) => a.indexOf(v) === i);
    if (this.allDeSelectedRows.length > 0) {
      this.showLoadingSpinner = true;
      console.log('this.allDeSelectedRows updateRecords'+ this.allDeSelectedRows);

      userRecordsUpdate({
          deSelectedArrList: this.allDeSelectedRows
        })
        .then(result => {
          if (result) {
            console.log('result userRecordsUpdate ='+ result);
            this.showLoadingSpinner = false;
            this.dispatchEvent(
              new ShowToastEvent({
                title: 'Success',
                message: 'User List updated',
                variant: 'success'
              })
            );
           window.location.reload();
          } else {
             console.log('Update failed.');
             this.dispatchEvent(
                  new ShowToastEvent({
                     title: 'Error updating user records',
                     message: 'Update failed',
                     variant: 'error'
                     }));
          }
        })
        .catch(error => {
          this.showLoadingSpinner = false;
          console.log('Update failed due to - ' + error);
          this.dispatchEvent(
            new ShowToastEvent({
              title: 'Error updating user records',
              message: error,
              variant: 'error'
            }));
        });
    }
    else
    {
        this.dispatchEvent(
        new ShowToastEvent({
            title: 'No records to Update',
            message: 'No users to de-activates',
            variant: 'info'
            })
        );
    }
  }

  deactivateProcess(event) {
        this.showLoadingSpinner = true;
         let chk = event.target.checked;
         console.log("clicked : "+ event.target.checked);

         if (chk != null) {

             updateUserManagementProcess({
                   status: event.target.checked
                 })
                 .then(result => {
                   if (result) {
                     console.log('result updateUserManagementProcess ='+ result);
                     this.showLoadingSpinner = false;

                     if(chk == true)
                     {
                         this.dispatchEvent(
                           new ShowToastEvent({
                             title: 'Success',
                             message: 'User Deactivation is Active',
                             variant: 'success'
                           })
                     );
                     }
                     else
                     {
                          this.dispatchEvent(
                             new ShowToastEvent({
                               title: 'Success',
                               message: 'User Deactivation is Inactive',
                               variant: 'success'
                          })
                       );
                       }


                   } else {
                      console.log('Update failed.');
                      this.dispatchEvent(
                           new ShowToastEvent({
                              title: 'Error updating user management meta-data record',
                              message: 'Update failed',
                              variant: 'error'
                              }));
                   }
                 })
                 .catch(error => {
                   this.showLoadingSpinner = false;
                   console.log('Update failed due to - ' + error);
                   this.dispatchEvent(
                     new ShowToastEvent({
                       title: 'Error updating user management meta-data record',
                       message: error,
                       variant: 'error'
                     }));
                 });
   		}
   else
       {
           this.dispatchEvent(
           new ShowToastEvent({
               title: 'Update Failed',
               message: 'Error updating user management meta-data record',
               variant: 'info'
               })
           );
       }
     }



  // Sorting
   handleSortdata(event) {
          // field name
          this.sortBy = event.detail.fieldName;
          console.log('this.sortBy = '+this.sortBy);
          // sort direction
          this.sortDirection = event.detail.sortDirection;
          console.log('this.sortDirection = '+this.sortDirection);
          // calling sortdata function to sort the data based on direction and selected field
          this.sortData(event.detail.fieldName, event.detail.sortDirection);
      }

      sortData(fieldname, direction) {
          // serialize the data before calling sort function
          let parseData = JSON.parse(JSON.stringify(this.data));
           console.log('this.parseData = '+this.parseData);
           console.log('this.fieldname = '+fieldname);
          // Return the value stored in the field
          let keyValue = (a) => {
              return a[fieldname];
          };

          // cheking reverse direction
          let isReverse = direction === 'asc' ? 1: -1;

          // sorting data
          parseData.sort((x, y) => {
              x = keyValue(x) ? keyValue(x) : ''; // handling null values
              y = keyValue(y) ? keyValue(y) : '';

              // sorting values based on direction
              return isReverse * ((x > y) - (y > x));
          });

          // set the sorted data to data table data
          this.data = parseData;

      }
}

​​​​​​​
Best Answer chosen by Prasan De Alwis
CharuDuttCharuDutt
Hii Prasan De Alwis
Try Now I've Made Some Changes
<template>
  <lightning-card   title="User Management" icon-name="standard:user" >
            <div class=" dd slds-m-bottom-xx-large">
               <div class=" slds-float_right">
                                    <lightning-layout >
                                        <lightning-layout-item size="6" class="">
                                           
                                                <lightning-input type="toggle"
                                                         label="Enable Process"
                                                         onchange ={deactivateProcess}
                                                         checked= "{ToggleChecked}"
                                                        >
                                        </lightning-input>       
                                            
                                        </lightning-layout-item>
                                        <lightning-layout-item size="4" class="">
                                         
                                                <lightning-button  label="Submit" onclick={updateRecords}>
                                                </lightning-button>
                                           
                                        </lightning-layout-item>
                                      
                                        <lightning-layout-item  size="1" class="">
                                           
                                                <lightning-helptext content="The users that will exclude from the de-activation."></lightning-helptext>
                                           
                                        </lightning-layout-item>
                                    </lightning-layout>
                             
                                </div>
            </div>
        <div>
            <div class="slds-col slds-size_12-of-12 slds-p-top_medium">
                <div  class="slds-m-top_large lgc-bg">
                    <lightning-datatable
                            key-field="UserId"
                            columns={columns}
                            data={currentPageData}
                            selected-rows= {allSelectedRows}
                            onrowselection= {rowSelection}
                            sorted-by={sortBy}
                            sorted-direction={sortDirection}
                            onsort={handleSortdata}
                    >
                    </lightning-datatable>
                </div>
                <div class="slds-col slds-size_10-of-12 slds-p-top_medium">
                    <lightning-layout multiple-rows="true">
                        <lightning-layout-item size = "12" margin= "around-small">
                            <div class="slds-align_absolute-center">
                                <ul class="slds-button-group-row">
                                    <!-- <template if:true={hasPrev}>-->
                                    <li class="slds-button-group-item" >
                                            <button class="slds-button slds-button_neutral" onclick ={onFirst} disabled={disabledConditionFirst}> First
                                            </button>
                                    </li>
                                    <li class="slds-button-group-item" >
                                              <button class="slds-button slds-button_neutral" disabled={disabledConditionPrev} onclick ={onPrev}> Prev
                                              </button>
                                    </li>
                                    <li class="slds-button-group-item" >
                                          <button class="slds-button slds-button_neutral" disabled={disabledConditionNext} onclick={onNext} >Next</button>
                                    </li>
                                    <li class="slds-button-group-item" >
                                            <button class="slds-button slds-button_neutral"  onclick ={onLast} disabled={disabledConditionLast}> Last
                                            </button>
                                    </li>
                                    <!--</template>-->
                                </ul>
                            </div>
                            </br>
                            <div class="slds-align_absolute-center" >
                        <span
                                disabled={disabledCondition}>Total Records: {totalRecordCount} </span>
                            </div>
                            <div class="slds-align_absolute-center" >
                                <span disabled={disabledCondition}>Page ({page} of {numberOfPages}) </span>
                            </div>
                        </lightning-layout-item>
                    </lightning-layout>
                </div>
            </div>
        </div>
        <div if:true={showLoadingSpinner}>
            <lightning-spinner alternative-text="Loading" size="large"></lightning-spinner>
        </div>
    </lightning-card>

Css
.dd{
    margin-bottom: 20px;
}

Please Mark It As Best Answer If it Helps
Thank You!
Manisha ValavalaManisha Valavala 
Hi ,

I am not able to browse third party url in lightning component as it shows below error 

"The domain is not set in 'CSP trusted sites whitelist'

But I have added the third party url in CSP , please assist
Best Answer chosen by Manisha Valavala
SwethaSwetha (Salesforce Developers) 
HI Manisha,
Ensure that you have  added the URL to CSP Errors whitelist using a wildcard like this: https://*.forcecontentuser.com

Also there is a known issue with the lightning:map usage which is worth checking: https://trailblazer.salesforce.com/issues_view?id=a1p3A000001FSlqQAG

If this information helps, please mark the answer as best. Thank you
DiamundoDiamundo 
Hi there.

In my lightning app I have a few components:
  • one component has a ui:inputSelect and registers an event. the ui:inputSelect has a change attribute that fires a function, wherein the selected text (an ID) is put in an event and fired.
  • one component that handles the event, is an aura:iteration list of a component that, on handling the event, should retrieve a list of items where a master-child lookup is the sent ID of the master object. This then displays all those child objects.
  • the other component that handles the event, has three inputText fields, that are supposed to display the other fields of the master object
The problem: either the event seems to not be fired, or the handlers seem to not be activated.

I put console.debug's, alerts and component.set("v.testmessage", "fired") 's in the handlers but they never execute.
I then put one of the handlers as the init-handler and then it did execute the handler (with an undefined ID since the event hadn't yet been fired, which is reasonable).

I have triple-checked the event name, event type and handler action, everything matches. I have no compilation problems, I have no errors when I am using my app. 
I also have no response whatsoever from my event. Any ideas?

**Registering component**
<aura:component controller="PrefixMasterHeaderSelectorController">
    <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
    <aura:registerEvent name="updateMaster" type="c:PrefixMasterEvent" />
    <aura:attribute name="masters" type="PrefixMaster__c[]"/>
      
    <label class="slds-master-element__label" for="masterSelector">Select a master to work with:</label>
    <div class="slds-master-element__control">
        <div class="slds-select_container">
            
            <ui:inputSelect aura:id="masterID" class="slds-select" change="{!c.masterHasChanged}">
                <aura:iteration items="{!v.masters}" var="master">
                    <ui:inputSelectOption text="{!master.Id}" label="{!master.Name}" />
                    <!-- + ' (Last modified: ' + master.LastModifiedDate + ' by ' + master.LastModifiedBy.Name + ')'}"/> -->
                </aura:iteration>	
                <ui:inputSelectOption text="newMaster" label="Create a new master" />
            </ui:inputSelect>
            
        </div>
    </div>

    <c:PrefixMasterHeaderMaster />
</aura:component>

**Registering controller**
({
    doInit : function(component, event, helper) {
        // Create the action
        var action = component.get("c.getMasters");
    
        // Add callback behavior for when response is received
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (component.isValid() && state === "SUCCESS") {
                component.set("v.masters", response.getReturnValue());
            }
            else {
                console.log("Failed with state: " + state);
            }
        });
    
        // Send action off to be executed
        $A.enqueueAction(action);
    },
    
    masterHasChanged : function(component, event, helper) {
        var masterID = component.find("masterID").get("v.value");
        var masterEvent = component.getEvent("updateMaster");
        masterEvent.setParams({"master" : masterID})
        masterEvent.fire();
        
		console.debug('UPDATE MASTER = ' + masterID);
        alert('Hiya! masterEvent ' + masterEvent.getParam("master"));
    }
		
})

**List-child component**
<aura:component controller="PrefixListChildsController">
	<aura:handler name="updateForm" event="c:PrefixFormEvent" action="{!c.loadChilds}" />
    <aura:attribute name="childs" type="PrefixChild__c[]"/>
    
	<!--   	<aura:handler name="saveChild" event="c:PrefixChildEvent" action="{!c.handleAddItem}"/> -->
    <!--	to reload the masters after adding a new child -->
    
    <div>
        <header class="slds-p-top--small">
            <h3 class="slds-text-heading--small">Childs</h3>
        </header>
        
        <div id="list" class="row">
            <aura:iteration items="{!v.childs}" var="child">
                <aura:if isTrue="{!child.Order__c % 2 == 1}">
                        <div class="slds-p-around--small" style="background-color: lightblue; border-radius: 10px">
                            <c:PrefixChild child="{!child}"/>
                        </div>
                    <aura:set attribute="else" >
                        <div class="slds-p-around--small" style="background-color: none; border-radius: 10px">
                            <c:PrefixChild child="{!child}"/>
                        </div>
                    </aura:set>
                </aura:if>
            </aura:iteration>
            {!v.testEventmessage}
            <c:PrefixNewChild />
        </div>
    </div>

</aura:component>

**List-child controller.js**
({
	loadChilds : function(component, event, helper) {
 	    var action = component.get("c.getChilds");
		var masterID = event.getParam("master");    
    	action.setParams({ "masterID" : masterID });
        
        console.debug('master id = ' + masterID);
        alert('load childs ' + masterID);
        component.set("v.testEventmessage", masterID);

        // Add callback behavior for when response is received
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (component.isValid() && state === "SUCCESS") {
                component.set("v.childs", response.getReturnValue());
            }
            else {
                console.log("Failed with state: " + state);
            }
        });
        
        // Send action off to be executed
        $A.enqueueAction(action);
    }
})


 
Best Answer chosen by Diamundo
DiamundoDiamundo
Solved it...

After I found out that the firing component was able to handle the (component) event, but a component somewhere else (not a parent or child component, but, say, an uncle-component) was not, I changed the type of the event to application. Still didn't work, so I looked up the documentation and saw that an application-type event is registered slightly different.

**APPLICATION-TYPE EVENT:**
<aura:event type="APPLICATION" >
    <aura:attribute name="item" type="sObject__c" />
</aura:event>
**REGISTERING COMPONENT**
<aura:registerEvent name="PrefixMasterEvent" type="c:PrefixMasterEvent" />

**FIRING CONTROLLER**
var applicationEvent = $A.get("e.c:PrefixMasterEvent");
    applicationEvent.setParams({"item" : itemID})
    applicationEvent.fire();
(Note: instead of component.getEvent("eventName") you now use $A.get("e.c:EventName") !
I'm not sure what the 'e' stands for, but I'm pretty sure the 'c' part is the namespace, and be careful to put the name of the event FILE as 'EventName' in the $A.get() parameter.)

**HANDLING COMPONENT**
<aura:handler event="c:PrefixApplicationEvent" action="{!c.doAnotherFunction}" />
(Note: the main difference is: with an application event there is no need (or use) for an event 'name', and I'm not sure why it has to be specified at the registerEvent tag other than it's a required attribute of the tag.)

**HANDLING CONTROLLER**
({
    doAnotherFunction(component, event, helper) {
        var item = event.getParam("item");
        alert('The item is: ' + item);
    }
})




 
ShiviSShiviS 
Requirement: When a Billing Address is modified, get the new Postal Code. Then check which Contacts on the Account are outside that Postal Code. If 1 or more Contacts are outside of the Postal Code, mark Out_of_Zip as TRUE.

I wrote this trigger on account object:

 trigger Q2 on Account (after update) {
    List<id> aid=new list<id>();
    List<Contact> c=new List<Contact>();
    
    List<id> aidd=new list<id>();
    List<account> az=new list<account>();
    List<account> acfinal=new List<account>();
    
    for(Account a1:trigger.new){
        aid.add(a1.id);
    }
    c=[select id,MailingPostalCode,Accountid from contact where accountid in :aid];
    for(Account aa:Trigger.new){
        for(contact con:c){
            if(con.Accountid==aa.id && con.MailingPostalCode!=aa.BillingPostalCode){
                aidd.add(aa.id);
            }
        }
    }
    az=[select id, Out_of_Zip__c from account where id in :aid];
    for(account al:az){
        al.Out_of_Zip__c=true;
        acfinal.add(al);
    }
    update acfinal;
}

When I am changin the postal code on the account object, It's giving the below error:

Q2: execution of AfterUpdate caused by: System.DmlException: Update failed. First exception on row 0 with id 0012v00003EsSb5AAF; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, Q2: maximum trigger depth exceeded Account trigger event AfterUpdate Account trigger event AfterUpdate Account trigger event AfterUpdate Account trigger event AfterUpdate Account trigger event AfterUpdate Account trigger event AfterUpdate Account trigger event AfterUpdate Account trigger event AfterUpdate Account trigger event AfterUpdate Account trigger event AfterUpdate Account trigger event AfterUpdate Account trigger event AfterUpdate Account trigger event AfterUpdate Account trigger event AfterUpdate Account trigger event AfterUpdate Account trigger event AfterUpdate: [] Trigger.Q2: line 27, column 1

Kindly let me know why is this happening? I am a beginner to coding.
Best Answer chosen by ShiviS
Suraj Tripathi 47Suraj Tripathi 47

Hi Shivis,

Please try this code.

if(trigger.isBefore && trigger.isUpdate){
        List<id> aid=new list<id>();
        List<Contact> c=new List<Contact>();
        
        List<id> aidd=new list<id>();
        List<account> az=new list<account>();
        List<account> acfinal=new List<account>();
        
        for(Account a1:trigger.new){
            aid.add(a1.id);
        }
        c=[select id,MailingPostalCode,Accountid from contact where accountid in :aid];
        for(Account aa:Trigger.new){
            for(contact con:c){
                if(con.Accountid==aa.id && con.MailingPostalCode!=aa.BillingPostalCode){
                   aa.Out_of_Zip__c =true;
                }
            }
        }
    }

Please let me know it is working or not??
Please mark it as Best Answer

Thank you

Poorna DeveloperPoorna Developer 
Hi,

I have Apex code  output JSON data,

User-added image

I wish to display this json data in my LWC. 
Html:
<template>
    <lightning-card title="Report Data" icon-name="lightning-icon" >
        <div class="slds-m-around_medium">
            <template if:true={lapp}>
                <ul>
               <template for:each={lapp} for:item="app">
                   <li key={app.Id}> {app.Name} </li>
               </template>
            </ul>
           </template>
           <template if:true={error}>
               {error}
           </template>  
        </div>
 </lightning-card>
</template>

Js:
import { LightningElement, wire, track} from 'lwc';
import getURL from '@salesforce/apex/CreateReport.reportgen';
export default class RedirecctedURL extends LightningElement {
       @track lapp;
       @track data;
       @track error;
       wiredActivities;
     @wire(getURL,{
     }
     )
     wiredCases(value){
     this.wiredActivities = value;
     const { data, error } = value;
     
     if(data){
       this.lapp = JSON.stringify(data);
       console.log(JSON.stringify(data));
     
     }else if(error){
       console.log(error);
       this.error = error;
     }
     }
}

Any help??
 
Best Answer chosen by Poorna Developer
CharuDuttCharuDutt
Hii Poorna,
Please See My Answer Above I've Made Some changes
yours=====>     this.lapp = JSON.stringify(data);
Changed======>  this.lapp = JSON.parse(JSON.stringify(data));
This Will Help In Showing Data Also Check if Console is Printing or not on Google Console

Please Mark it As Best Answer If it Helps
Thank You!
Hector MariscalHector Mariscal 
An <a> tag in the html file of the lwc is only adding the desired url to the current url of the community page that the lwc is in.
Best Answer chosen by Hector Mariscal
Raj VakatiRaj Vakati
A lightning-formatted-url component displays a text URL as a hyperlink with an href attribute. The valuecan be a relative or absolute URL. Absolute URLs use protocols such as http://, https://, and ftp://, followed by the domain name and path.

https://developer.salesforce.com/docs/component-library/bundle/lightning-formatted-url/example
<template>
    <p><lightning-formatted-url value="my/path" ></lightning-formatted-url></p>
    <p><lightning-formatted-url value="https://my/path" tooltip="Go to https://my/path" label="My Cool Website" target="_blank" ></lightning-formatted-url></p>
    <p><lightning-formatted-url value="ftp://my/path" tooltip="Go to ftp://my/path" ></lightning-formatted-url></p>
    <p><lightning-formatted-url value="http://my/path" ></lightning-formatted-url></p>
    <p><lightning-formatted-url value="/my/path" ></lightning-formatted-url></p>
    <p><lightning-formatted-url value=".my/path" ></lightning-formatted-url></p>
</template>