Saturday, 17 October 2020

LWC Multiple Records Select

public with sharing class OpportunityController {

  public static list<wrapperClass> listWrapper;

  @AuraEnabled(cacheable=true)  

  public static List<opportunity> fetchRecordList(){  

    return [SELECT Id, Name, StageName,Amount,owner.name From Opportunity LIMIT 5];  

  }  

  @AuraEnabled  

  public static void updateRecords(object[] recordList){  

    system.debug('...data...'+recordList);

    list<id> lstId = new list<id>();

    list<opportunity> lstopp = new list<opportunity>();

    if(!recordList.isEmpty() && recordList.size() > 0){        

        for(object objRecord : recordList){

          String jsonstring = Json.serialize(objRecord); 

          wrapperClass n = (wrapperClass)JSON.deserialize(jsonstring, wrapperClass.class);

          ID vID = String.valueof((n.BidNumber).Right(18));

          lstId.add(vID);

        }

        if(!lstId.isEmpty()){

          for(ID vID : lstId){

            opportunity objOpp = new opportunity();

            objOpp.id = vID;

            lstopp.add(objOpp);

          }

        }

    }

    delete lstopp;  

  }  

  class wrapperClass {

    string BidNumber;

  }

}


=====================================================================================================================

import { LightningElement,track,wire } from 'lwc';

import {refreshApex} from '@salesforce/apex';  

import getAllRecords from '@salesforce/apex/OpportunityController.fetchRecordList';  

import updateRecords from '@salesforce/apex/OpportunityController.updateRecords';  

/*const COLS=[  

  {label:'Name',fieldName:'Name', type:'text'},  

  {label:'Stage',fieldName:'StageName', type:'text'},  

  {label:'Amount',fieldName:'Amount', type:'ownerName'}  

];*/

const columns =[{

  label: 'Bid Number',

  fieldName: 'BidNumber',

  type: 'url',

  typeAttributes: {

      label: {

          fieldName: 'BidNumberLabel'

      },

      target: '_blank'

  },

  sortable:true

},{

  label: 'Total Bid Amount',

  fieldName: 'TotalBidAmount',

  type: 'Currency',

  sortable:true

}, {

  label: 'Owner Name',

  fieldName: 'OwnerName',

  type: 'text',

  sortable:true

}];  

export default class DataTableInLwcCheckbox extends LightningElement {

  @track data = [];

  @track recordList = [];

  @track columns = columns;

  wiredAccountsResult;

  //@track recordCount =0;

  @track sortBy;

  @track sortDirection;  

  @wire(getAllRecords)

  opp({error, data}) {

    this.wiredAccountsResult = data;

      if(data) {

          let currentData = [];

          let url = 'https://'+location.host+'/';

          data.forEach((row) => {

              let rowData = {};

              rowData.TotalBidAmount = row.Amount;

              rowData.BidNumber = url+row.Id; 

              rowData.BidNumberLabel = row.Name;              

              if (row.Owner) {

                  rowData.OwnerName = row.Owner.Name;

              }              

              currentData.push(rowData);

              

          });


          this.data = currentData; 

          this.recordList = currentData;

          //this.recordCount = currentData.length;

      }

      else if(error) {

        //  window.console.log(error);

      }

  }

  @wire(getAllRecords) refreshData;  

  handleSortdata(event) {

      this.sortBy = event.detail.fieldName;

      this.sortDirection = event.detail.sortDirection;

      this.sortData(event.detail.fieldName, event.detail.sortDirection);

  }


  sortData(fieldname, direction) {

      let parseData = JSON.parse(JSON.stringify(this.data));

      let keyValue = (a) => {

          return a[fieldname];

      };


      let isReverse = direction === 'asc' ? 1: -1;


      parseData.sort((x, y) => {

          x = keyValue(x) ? keyValue(x) : ''; // handling null values

          y = keyValue(y) ? keyValue(y) : '';

          return isReverse * ((x > y) - (y > x));

      });


      this.data = parseData;


  }

   deleteRecord(){ 

    console.log("getSelectedRows => ", this.template.querySelector('lightning-datatable').getSelectedRows()); 

     var selectedRecords =  this.template.querySelector("lightning-datatable").getSelectedRows();  

     console.log('...this.wiredAccountsResult...',this.wiredAccountsResult);

     updateRecords({recordList: selectedRecords})  

     .then(result=>{

       eval("$A.get('e.force:refreshView').fire();");  

       return refreshApex(this.refreshData);  

     })  

     .catch(error=>{  

       alert('Cloud not update'+JSON.stringify(error));  

     })  

   }  

}

=========================================================================

<template>

  <lightning-card title="Opportunity">  

      <lightning-button variant="brand" 

                        slot="actions" 

                        label="Approve" 

                        onclick={deleteRecord}

                        >

      </lightning-button>  

      <div class="slds-box">  

        <lightning-datatable columns={columns} 

                            data={data} 

                            key-field="id"

                            sorted-by={sortBy}

                            sorted-direction={sortDirection}

                            onsort={handleSortdata}></lightning-datatable>

      </div>  

    </lightning-card>  

</template>

=========================================================================

<?xml version="1.0" encoding="UTF-8"?>

<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">

    <apiVersion>49.0</apiVersion>

    <isExposed>true</isExposed>

    <targets>

        <target>lightning__HomePage</target>

        <target>lightning__RecordPage</target>

    </targets>

</LightningComponentBundle>

=========================================================================

Thursday, 15 October 2020

SFDC LWC data table With Check Box

 public with sharing class OpportunityController {

   @AuraEnabled(cacheable=true)  

   public static List<opportunity> fetchRecordList(){  

     return [SELECT Id, Name, StageName,Amount From Opportunity LIMIT 5];  

   }  

   @AuraEnabled  

   public static void updateRecords(List<opportunity> recordList){  

     delete recordList;  

   }  

}

=====================================================================================================

import { LightningElement,track,wire } from 'lwc';

import {refreshApex} from '@salesforce/apex';  

import getAllRecords from '@salesforce/apex/OpportunityController.fetchRecordList';  

import updateRecords from '@salesforce/apex/OpportunityController.updateRecords';  

const COLS=[  

  {label:'Name',fieldName:'Name', type:'text'},  

  {label:'Stage',fieldName:'StageName', type:'text'},  

  {label:'Amount',fieldName:'Amount', type:'currency'}  

];  

export default class DataTableInLwcCheckbox extends LightningElement {

   cols=COLS;  

   @wire(getAllRecords) recordList;  

   deleteRecord(){  

     var selectedRecords =  

      this.template.querySelector("lightning-datatable").getSelectedRows();  

     updateRecords({recordList: selectedRecords})  

     .then(result=>{  

       return refreshApex(this.recordList);  

     })  

     .catch(error=>{  

       alert('Cloud not delete'+JSON.stringify(error));  

     })  

   }  

}

=====================================================================================================

<template>

    <lightning-card title="Opportunity">  

        <lightning-button variant="brand" slot="actions" label="Approve" onclick={deleteRecord}></lightning-button>  

        <div class="slds-box">  

          <lightning-datatable  

          data={recordList.data} columns={cols} key-field="Id">  

          </lightning-datatable>  

        </div>  

      </lightning-card>  

</template>


=====================================================================================================


Wednesday, 14 October 2020

LWC Data table

 import {LightningElementtrackwirefrom 'lwc';

import retriveOpportunities from '@salesforce/apex/LWCExampleController.retriveOpportunities';

// Datatable Columns
const columns = [
   /* { label: 'Company Website', fieldName: 'website', type: 'url',
    typeAttributes: { tooltip: { fieldName: 'website' } } }
    {
        label: 'Duplicate Website', 
        fieldName: 'duplicateWebsite', 
        type: 'url' , 
        typeAttributes:{
            label: { 
                fieldName: 'websiteLabel'                 
            } ,
            target : '_blank'           
        }

    }*/
    {
        label: 'Related To',
        fieldName: 'AccId',
        type: 'url',
        typeAttributes: {
            label: {
                fieldName: 'AccName'
            },
            target: '_blank'
        },
        sortable:true
    },{
        label: 'Opportunity Name',
        fieldName: 'Name',
        type: 'text',
    }, {
        label: 'Account Name',
        fieldName: 'AccountName',
        type: 'text',
        sortable:true
    }, {
        label: 'Account Owner',
        fieldName: 'AccountOwner',
        type: 'text',
        sortable:true
    }, {
        label: 'Opportunity Owner',
        fieldName: 'OpportunityOwner',
        type: 'text',
        sortable:true
    }, {
        label: 'CreatedDate',
        fieldName: 'CreatedDate',
        type: 'date',
        sortable:true
    }, {
        label: 'test acc',
        fieldName: 'testacc',
        type: 'text',
        sortable:true
    }
];


export default class ParentFieldsInLWC extends LightningElement {
    @track data = [];
    @track columns = columns;
    @track recordCount =0;
    @track sortBy;
    @track sortDirection;

    @wire(retriveOpportunities)
    opp({errordata}) {
        if(data) {

            let currentData = [];
            let url = 'https://'+location.host+'/';
            data.forEach((row=> {

                
                let rowData = {};

                rowData.Name = row.Name;
                rowData.CreatedDate = row.CreatedDate;
                
                if (row.Account) {
                    rowData.AccName = row.Account.Name//Here define your value which you want to display
                    rowData.AccId = url+row.Id;
                    rowData.AccountName = row.Account.Name;
                    rowData.AccountOwner = row.Account.Owner.Name;
                }

                if (row.Owner) {
                    rowData.OpportunityOwner = row.Owner.Name;
                }
                if (row.test_acc__c) {
                    rowData.testacc = row.test_acc__r.Name;
                }
                currentData.push(rowData);
            });

            this.data = currentData
            this.recordCount = currentData.length;
        }
        else if(error) {
        }
    }
    handleSortdata(event) {
        // field name
        this.sortBy = event.detail.fieldName;

        // sort direction
        this.sortDirection = event.detail.sortDirection;

        // calling sortdata function to sort the data based on direction and selected field
        this.sortData(event.detail.fieldNameevent.detail.sortDirection);
    }

    sortData(fieldnamedirection) {
        // serialize the data before calling sort function
        let parseData = JSON.parse(JSON.stringify(this.data));

        // 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((xy=> {
            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;

    }
}



<template>
    <lightning-card title="">
       <H4>Showing Reference Fields Data in Lightning Datatable {recordCount}</H4> 
        <lightning-datatable columns={columns} 
                            data={data} 
                            key-field="id"
                            hide-checkbox-column="true"
                            show-row-number-column="true"
                            sorted-by={sortBy}
                                     sorted-direction={sortDirection}
                                     onsort={handleSortdata}></lightning-datatable>
    </lightning-card>
</template>


public with sharing class LWCExampleController {
    @AuraEnabled(cacheable=true)
    public static list<OpportunityretriveOpportunities() {
        return [SELECT Id
                       Name,
                       test_acc__r.Name,
                       AccountID,
                       Account.Name
                       Account.owner.name
                       Owner.Name
                       CreatedDate 
                FROM Opportunity LIMIT 10];
    }
}