0

I'm trying to create a custom list view in Lightning Web Component, I managed to create a data view but now I would also like to customize the filters ... so I want to reproduce the filter button with three conditions: equals, not equals and contains. Below I place the code of my page with its class. Thanks in advance for your time

-----template html-------

<template>
   <lightning-card title="Persone" icon-name="standard:contact" > <br/>
      <!-- Spinner -->
      <div if:true={showLoadingSpinner}>
          <lightning-spinner alternative-text="Loading" size="large"></lightning-spinner>
      </div>

      <!-- Detail view modal -->
      <template if:true={bShowModal}>
          <section role="dialog" tabindex="-1"
                  aria-labelledby="modal-heading-01"
                  aria-modal="true"
                  aria-describedby="modal-content-id-1"
                  class="slds-modal slds-fade-in-open">
          <div class="slds-modal__container">
              <!-- modal header -->
              <header class="slds-modal__header">
                  <button class="slds-button slds-button_icon slds-modal__close slds-button_icon-inverse" title="Close" onclick={closeModal}>
                      <lightning-icon icon-name="utility:close" alternative-text="close" variant="inverse" size="small" ></lightning-icon>
                  </button>
                  
                  <h2 id="modal-heading-01" class="slds-text-heading_medium slds-hyphenate" if:false={isEditForm}>Record Detail</h2>
                  <h2 id="modal-heading-02" class="slds-text-heading_medium slds-hyphenate" if:true={isEditForm}>Update Record Values</h2>
              </header>
              <!-- modal body -->
              <div class="slds-modal__content slds-p-around_medium" id="modal-content-id-1" if:false={isEditForm}>
                  <dl class="slds-list_horizontal slds-wrap">
                      <dt class="slds-item_label slds-truncate" title="First Name">First Name:</dt>
                      <dd class="slds-item_detail slds-truncate">{record.FirstName}</dd>
                      <dt class="slds-item_label slds-truncate" title="LastName">Last Name:</dt>
                      <dd class="slds-item_detail slds-truncate">{record.LastName}</dd>
                      <dt class="slds-item_label slds-truncate" title="Phone">Phone :</dt>
                      <dd class="slds-item_detail slds-truncate"><lightning-formatted-phone value={record.Phone} ></lightning-formatted-phone></dd>
                      <dt class="slds-item_label slds-truncate" title="Email">Email :</dt>
                      <dd class="slds-item_detail slds-truncate"><lightning-formatted-email value={record.Email} ></lightning-formatted-email></dd>
                  </dl>
              </div>
              
              <!-- showing record edit form -->
              <div if:true={isEditForm} class="slds-theme_default">
                  <lightning-record-edit-form layout-type="Full" record-id={currentRecordId} object-api-name="Test_Names__Persone__c" onsubmit={handleSubmit} onsuccess={handleSuccess}>
                      <lightning-messages></lightning-messages>
                      <lightning-output-field field-name="Id"></lightning-output-field>
                      <lightning-input-field field-name="Test_Names__Name__c"></lightning-input-field>
                      <lightning-input-field field-name="Test_Names__Last_Name__c"></lightning-input-field>
                      <lightning-input-field field-name="Test_Names__Phone__c"></lightning-input-field>
                      
                      <div style="text-align:center;">
                          <lightning-button class="slds-m-top_small"
                                            variant="brand"
                                            type="submit"
                                            name="update"
                                            label="Update Record"></lightning-button>
                      </div>
                  </lightning-record-edit-form><br/>
                  <div></div>
              </div>

              <!-- modal footer start-->
              <footer class="slds-modal__footer" if:false={isEditForm}>
                  <lightning-button variant="brand"
                                    label="Close"
                                    title="Close"
                                    onclick={closeModal}></lightning-button>
              </footer>
          </div>
          </section>
          <div class="slds-backdrop slds-backdrop_open"></div>
      </template>
  </lightning-card>   
<!--Gestione dei bottoni-->
<div class="container">
   <lightning-card>
      <lightning-layout multiple-rows="true">
         <lightning-layout-item size="12" padding="around-medium">
            <div class="slds-align_absolute-center">
               <lightning-datatable
                  key-field="id"
                  data={currentPageData}
                  columns={columns}
                  onrowaction={handleRowActions}
                  hide-checkbox-column="true"
                  >
               </lightning-datatable>
            </div>
         </lightning-layout-item>

         <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 ={onPrev}> prev
                        </button>
                     </li>
                  </template>
                  <template for:each={pagesList} for:item= "pageNumber">
                     <li class="slds-button-group-item" key={pageNumber}>
                        <button data-id={pageNumber} class="slds-button slds-button_neutral"
                           onclick={onPageClick}>{pageNumber}</button>
                     </li>
                  </template>
                  <template if:true={hasNext}>
                     <li class="slds-button-group-item" >
                        <button class="slds-button slds-button_neutral" onclick={onNext}
                           >next</button>
                     </li>
                  </template>
               </ul>
            </div>
         </lightning-layout-item>

      </lightning-layout>
   </lightning-card>
</div>
<!--Gestione Bottone-->
<aside>
   <div class="slds-m-top_medium slds-m-bottom_x-large">
       <h2 class="slds-text-heading_small slds-m-bottom_medium">
           Filtro
       </h2>
       <div class="slds-p-around_medium lgc-bg">
           <lightning-button-menu alternative-text="Show menu">
               <lightning-menu-item value="Equals" label="Equals"></lightning-menu-item>
               <lightning-menu-item value="NotEquals" label="NotEquals"></lightning-menu-item>
               <lightning-menu-item value="Contains" label="Contains"></lightning-menu-item>
           </lightning-button-menu>
       </div>
   </div>
</aside>
</template>

------------------controller js-----------------------------------------------

import {LightningElement, track, wire,api} from 'lwc';
// Richiamo la mia classe apex 
import getAllPers from '@salesforce/apex/All_Controller.getInfo';//Dove eseguo la query SOQL
import delSelectedCons from '@salesforce/apex/All_Controller.deleteContacts';//Dove mi gestisco l'eliminaizione di un campo SOQL
import {ShowToastEvent} from 'lightning/platformShowToastEvent';
import {refreshApex} from '@salesforce/apex';//Ogni volta che vi è una modifica faccio richiamo a questo metodo per refreshare la mia table
import{getRecord}from'lightning/uiRecordApi';
const actions = [ //Creazione della mia table dei bottoni
    { label: 'Record Details', name: 'record_details'}, 
    { label: 'Edit', name: 'edit'}, 
    { label: 'Delete', name: 'delete'}
];
const columns = [ //Creazione della mia table con richiamo al field object 
    {label: 'Id', fieldName: 'Id'},
    {label: 'Name', fieldName: 'Test_Names__Name__c'},
    {label: 'Last Name', fieldName: 'Test_Names__Last_Name__c'},
    {label: 'Phone', fieldName: 'Test_Names__Phone__c'},
    {
        type: 'action',
        typeAttributes: {
            rowActions: actions,
            menuAlignment: 'right'
        }
    }
];

  
export default class DeleteRowsInDatatableLWC extends LightningElement { 
    
   
    @track data;//Con il metodo Track accedo alle proprietà degli oggetti
    @track columns = columns;
    @track record = [];
    @track bShowModal = false;
    @track currentRecordId;
    @track isEditForm = false;
    @track showLoadingSpinner = false;
    @wire(getRecord,{recordId:'$recordId'})filter;
    selectedRecords = [];
    refreshTable;
    error;
    data = [];
    @track page = 1;
    perpage = 5;
    @track pages = [];
    set_size = 5;
    // retrieving the data using wire service
    @wire(getAllPers)//Con Wire accedo alla classe che manipola l'oggetto stesso quindi Persone__C
    persone(result) {
        this.refreshTable = result;
        if (result.data) {
            this.data = result.data;
            this.error = undefined;

        } else if (result.error) {
            this.error = result.error;
            this.data = undefined;
        }
    }
    //Gestione filtro
    /*
    @wire(filter)
    filter(result){



    }
*/
    handleRowActions(event) {
        let actionName = event.detail.action.name;

        window.console.log('actionName ====> ' + actionName);

        let row = event.detail.row;

        window.console.log('row ====> ' + row);
        // eslint-disable-next-line default-case
        switch (actionName) {
            case 'record_details':
                this.viewCurrentRecord(row);
                break;
            case 'edit':
                this.editCurrentRecord(row);
                break;
            case 'delete':
                this.deleteCons(row);
                break;
        }
    }

    // Vista bottoni su condizione(true o false)
    viewCurrentRecord(currentRow) {
        this.bShowModal = true;
        this.isEditForm = false;//Sarà solo visibile quando vi sarà presente un record
        this.record = currentRow;
    }

    // closing modal box
    closeModal() {
        this.bShowModal = false;
    }


    editCurrentRecord(currentRow) {
        // open modal box
        this.bShowModal = true;
        this.isEditForm = true;

        // assign record id to the record edit form
        this.currentRecordId = currentRow.Id;
    }

    // handleing record edit form submit
    handleSubmit(event) {
        // prevending default type sumbit of record edit form
        event.preventDefault();

        // querying the record edit form and submiting fields to form
        this.template.querySelector('lightning-record-edit-form').submit(event.detail.fields);

        // closing modal

        // Visualizzazione dell'operazione completata con Successo
        this.dispatchEvent(new ShowToastEvent({
            title: 'Tutto Ok!!',
            message: event.detail.fields.Id + ' '+ event.detail.fields.Test_Names__Last_Name__c +' Contatto Aggiornato Correttamente!!.',
            variant: 'tutto ok!'
        }),);

    }

    // Richiamo la classe del refresh se la condizione di aggiornmento della riga è andata a buon fine.
    handleSuccess() {
        return refreshApex(this.refreshTable);
    }

    deleteCons(currentRow) {
        let currentRecord = [];
        currentRecord.push(currentRow.Id);
        this.showLoadingSpinner = true;

        // Richiamo la classe apex per cancellare il record
        delSelectedCons({lstConIds: currentRecord})
        .then(result => {
            window.console.log('result ====> ' + result);
            this.showLoadingSpinner = false;

            // showing success message
            this.dispatchEvent(new ShowToastEvent({
                title: 'Tutto OK!!',
                message: currentRow.fields.Test_Names__Name__c+' '+currentRow.fields.Name__c + ' '+ currentRow.fields.Test_Names__Last_Name__c +''+currentRow.fields.Test_Names__Email__c+' '+currentRow.fields.Test_Names__Phone__c +' Contatto Eliminato.',
                variant: 'tutto ok!!'
            }),);

            // Aggiorno la mia table
             return refreshApex(this.refreshTable);

        })//Gestisco un eventuale errore
        .catch(error => {
            this.dispatchEvent(
                new ShowToastEvent({
                    title: 'Error deleting record',
                    message: error.body.message,
                    variant: 'error'
                })
            );
        });
    }
    //Gestione Paginazione dei bottoni next and prev
    renderedCallback() {
        this.renderButtons();
    }
    renderButtons = () => {
        this.template.querySelectorAll('button').forEach((but) => {
            but.style.backgroundColor = this.page === parseInt(but.dataset.id, 10) ? 'dodgerblue' : 'white';
            but.style.color = this.page === parseInt(but.dataset.id, 10) ? 'white' : 'black';
        });//Definisco lo style dei miei due bottoni 
    }
    //Successivamente eseguo le mie condizioni sui bottoni 
    get pagesList() {
        let mid = Math.floor(this.set_size / 2) + 1;//Incremento il contatore dei bottoni 
        if (this.page > mid) {
            return this.pages.slice(this.page - mid, this.page + mid - 1);
        }
        return this.pages.slice(0, this.set_size);
    }
    async connectedCallback() {
        this.data = await getAllPers();//Definisco la chiamata alla mia classe 
        this.setPages(this.data);
    }
    pageData = () => {
        let page = this.page;
        let perpage = this.perpage;
        let startIndex = (page * perpage) - perpage;
        let endIndex = (page * perpage);
        return this.data.slice(startIndex, endIndex);
    }
    setPages = (data) => {
        let numberOfPages = Math.ceil(data.length / this.perpage);
        for (let index = 1; index <= numberOfPages; index++) {
            this.pages.push(index);
        }
    }
    get hasPrev() {
        return this.page > 1;
    }
    get hasNext() {
        return this.page < this.pages.length
    }
    onNext = () => {
        ++this.page;
    }
    onPrev = () => {
        --this.page;
    }
    onPageClick = (e) => {
        this.page = parseInt(e.target.dataset.id, 10);
    }
    get currentPageData() {
        return this.pageData();
    }

}

-------------------------------apex class---------------------------------------

public inherited sharing class All_Controller {
    
    @AuraEnabled(Cacheable = true)
    public static List<Test_Names__Persone__c> getInfo(){
        return [SELECT Id,Name__c,Last_Name__c,Phone__c,Email__c FROM Test_Names__Persone__c  ORDER BY Name__c limit 10];
    }
    
    @AuraEnabled
    public static void deleteContacts(list<Id> lstConIds){
        try {
            list<Test_Names__Persone__c> lstConsToDelete = new list<Test_Names__Persone__c>();
            System.debug('lstConIds ====> '+lstConIds);
            for(Id idCon : lstConIds) {
                lstConsToDelete.add(new Test_Names__Persone__c(Id = idCon));
            }
            if(!lstConsToDelete.isEmpty()) {
                delete lstConsToDelete;
            }
        }
        catch(Exception ex) {
            throw new AuraHandledException(ex.getMessage());
        }
    }
 

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.