-
ChatterFeed
-
0Best Answers
-
1Likes Received
-
0Likes Given
-
2Questions
-
4Replies
Show data of a csv file in tabular form in LWC
Requirement: Whenever I upload a csv file, the data in the csv file should show in a tabular form(like above image.) in LWC.
Problem: Whenever I try to show the data in a <table>. The value is not showing in the <thead> &<tbody> (i.e. html). If I print the values of columnHeader and rows in the console, it gets displayed.
As I am not able to find where is the problem?
(If there is any doubt in understanding, please mention here.)
Below is the code.
<!-- html file --> <template> <lightning-card> <h3> <lightning-icon icon-name="utility:database" size="small"></lightning-icon> CSV Dataloader <button class="slds-button slds-button_destructive" style="margin-right:0; margin-left:auto; display:block;"> Clean Data </button> </h3> <lightning-input type="file" name="file" label="Attachment" accept=".csv" onchange={handleUploadFinished}> </lightning-input> <template if:true={showTable}> <table> <thead> <tr> <template for:each={csvString} for:item="head"> <th key={head.column_name}> {head.column_name} </th> </template> </tr> </thead> <tbody> <template for:each={lines} for:item="row"> <tr key={row}> <!--<template for:each={row} for:item="rowData">--> <td key={row}>{row}</td> <!--</template>--> </tr> </template> </tbody> </table> </template> </lightning-card> </template> ================================= // Javascript File import { LightningElement, track, wire } from 'lwc'; import getCSVObject from '@salesforce/apex/CSVCreator.getCSVObject'; export default class CustomCSVDataloaderInLWC extends LightningElement { @track colHeader = []; @track showTable = false; @track csvString; @track st; @track csvFile; @track lines; handleUploadFinished(event) { const uploadedFiles = event.detail.files; const file = uploadedFiles[0]; console.log("file : " + file); if (file) { this.showTable = true; //show the table console.log("this.showTable : " + this.showTable); let reader = new FileReader(); reader.readAsText(file, "UTF-8"); reader.onload = function (evt) { const csv = evt.target.result; console.log('csv : ' + csv); this.csvFile = csv; getCSVObject({ csv_str: csv }) .then(response => { console.log("response : " + JSON.stringify(response)); this.csvString =JSON.stringify([...response.headers]); console.log('this.csvString : '+this.csvString); this.lines = [...response.lines]; console.log('this.lines : '+JSON.stringify(this.lines)); let temp = response.headers; let col_head; this.colHeader = []; temp.forEach(element => { col_head = element.column_name;//JSON.stringify(element.column_name); console.log("col_head : " + col_head); this.colHeader = [...this.colHeader,col_head]; }); console.log("this.colHeader : " + this.colHeader); }).catch(error => { console.log("error2 ==> " + error); console.log("error ==> " + error.body.message); }); }; } } }Below is the console.log output of chrome in browser.
- Rajesh Kumar Maharana
- June 01, 2020
- Like
- 1
Create task object records based on contact names in the multi-select picklist
Activity Objective==> Wherever you see Activity Objective in the VFP, I have added the codes for the multi-picklist.
ISSUE: whenever I select the contact names (either 1 or more than 1) from the multi-picklist and click on save. It will save the record, but in the name field in the Task object will be blank. If I have selected 1 0r more than 1 contact names, it will create single record in the Task object and the name field will be blank.
REQUIREMENT: Now I want that, how many contact names I have selected from the multi-picklist. That many records will be created in the Task Object.
Already in the controller, record creation code is written. It is checking the contact name isChecked=true, then it will create the record.
In my code, it is taking isChecked=false. So it is not able to creat
<apex:page standardController="Task" id="thePageId" extensions="NewTaskCtrl" tabStyle="Task" action="{!loadNewTask}"> <apex:outPutPanel id="myMSG"> <apex:pageMessages id="msg" /> </apex:outPutPanel> <apex:slds /> <apex:form id="newTaskPage"> <!-- CDN links for the multiple picklist --> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" /> <link href="https://www.jqueryscript.net/css/jquerysctipttop.css?v3" rel="stylesheet" type="text/css" /> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"/> <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/@dashboardcode/bsmultiselect@0.5.40/dist/js/BsMultiSelect.min.js"></script> <!-- / Activity Objective - New picklist code--> <apex:actionFunction action="{!filterFields}" name="filterFields" reRender="myMSG,taskInfo" > <apex:param value="" name="tType" /> </apex:actionFunction> <apex:sectionHeader title="Task" subtitle="New Task"/> <apex:inputHidden value="{!inputValue}" id="theHiddenInput"/> <div class="slds-card"> <div class="slds-card__header slds-grid slds-border_bottom slds-p-bottom_small" style="background-color: #fafaf9;"> <div class="slds-media slds-media_center slds-has-flexi-truncate"> <div class="slds-media__body"> <h2 class="slds-card__header-title slds-text-heading_small"> Task Edit </h2> </div> <div class="slds-no-flex"> <apex:commandButton action="{!performSave}" title="Save" value="Save" styleClass="slds-button slds-button_brand"/> <apex:commandButton action="{!cancel}" title="Cancel" value="Cancel" styleClass="slds-button slds-button_neutral"/> </div> </div> </div> <div class="slds-card__body slds-p-horizontal_small"> <div class="slds-m-bottom_small slds-p-around_xx-small" style="background-color: #fafaf9;"><strong>Related To</strong></div> <div class="slds-form slds-form_horizontal"> <div> <div style="max-width: 600px;"> <apex:outputPanel styleClass="relatedToSection"> <div class="slds-form-element"> <apex:outputLabel value="Account" styleClass="slds-form-element__label"/> <div class="slds-form-element__control slds-m-top_xxx-small"> <apex:outputField value="{!taskObjectParent.WhatId}" title="This will contain Related Account" label="Account" /> </div> </div> <apex:pageBlock id="OfficeContactList"> <!-- rendered="{!IF((taskObjectParent.Id = null),true,false)}" --> <apex:outputPanel style="display:none" styleclass="taskContactMultiList"> <div class="slds-form-element"> <apex:outputLabel value="Select Contact to create task" styleClass="slds-form-element__label" id="con12"/> <div class="slds-form-element__control" style="padding-right: 82px;"> <!-- Activity Objective --> <!-- Show the multiple picklist values and binding--> <div class="container"> <select name="contactNames" id="example" class="form-control" multiple="multiple" onChange="countSelectedCheckbox()"> <apex:repeat value="{!avaiableContactlList}" var="con" id="conTable"> <option value="{!con.isChecked}" id="opt">{!con.Name}</option> <!---value is changed --> </apex:repeat> </select> </div> <!-- / Activity Objective --> Total Number of Selected record :<span style="font-weight:bold" id="selContactSize">0</span> </div> </div> </apex:outputPanel> </apex:pageBlock> <div class="slds-form-element"> <apex:outputLabel value="Topics Discussed" styleClass="slds-form-element__label"/> <apex:outputPanel id="refreshing"> <div class="slds-form-element__control" style="padding-right: 82px;"> <div class="slds-scrollable_y slds-m-top_x-small slds-m-bottom_small slds-p-around_x-small" style="max-height: 90px; border: 1px solid #dddbda; border-radius: .25rem;"> <table> <apex:repeat value="{!avaiableTopicList}" var="topic"> <tr> <td width="20" class="slds-p-bottom_x-small"> <span class="slds-checkbox slds-checkbox_standalone"> <apex:inputCheckbox value="{!topic.isChecked}" onclick="selectAllCheckboxes('topicCheckBoxId')" id="topicCheckBoxId"/> <span class="slds-checkbox_faux"></span> </span> </td> <td class="slds-p-bottom_x-small"> <label> {!topic.Name} </label> </td> </tr> </apex:repeat> </table> </div> Total Number of Selected record :<span style="font-weight:bold" id="selTopicSize">{!totalAvaiableTopic}</span> </div> </apex:outputPanel> </div> </div> </div> </div> </div> <div class="slds-card__footer slds-text-align_right"> <apex:commandButton action="{!performSave}" title="Save" value="Save" styleClass="slds-button slds-button_brand"/> <apex:commandButton action="{!cancel}" title="Cancel" value="Cancel" styleClass="slds-button slds-button_neutral"/> </div> </div> <script> function setFocusOnLoad() {} function toggleComponent(taskType,componentToToggle,taskId){ console.log('taskId : '+taskId); //filterFields(); if(taskId == 'NULL' || taskId == ''){ var contactComponent = document.getElementsByClassName(componentToToggle)[0]; var selectedValue = taskType.value; console.log(componentToToggle); if(selectedValue == 'Physician-to-Physician Visit' || selectedValue == 'Sports Medicine' ){ contactComponent.style.display ='block'; }else{ contactComponent.style.display ='none'; } }else{ var contactComponent = document.getElementsByClassName(componentToToggle)[0]; var selectedValue = taskType.value; console.log(componentToToggle); var oldTaskType = String(document.getElementById('thePageId:newTaskPage:theHiddenInput').value); if((oldTaskType != 'Physician-to-Physician Visit' && selectedValue == 'Physician-to-Physician Visit') || (oldTaskType != 'Sports Medicine' && selectedValue == 'Sports Medicine')){ contactComponent.style.display ='block'; }else{ contactComponent.style.display ='none'; } } //alert(taskType.value); filterFields(taskType.value); } function selectAllCheckboxes(receivedInputID){ var inputCheckBox = document.getElementsByTagName("input"); var totalCount = 0; for(var i=0; i<inputCheckBox.length; i++){ if(inputCheckBox[i].id.indexOf(receivedInputID)!=-1){ if(inputCheckBox[i].checked == true){ //alert("inputCheckBox[i].checked==>>"+inputCheckBox[i].checked); totalCount = totalCount + 1; } } } //console.log('====>' + totalCount); if(receivedInputID=='contactCheckBoxId'){ document.getElementById('selContactSize').innerHTML = totalCount; }else if(receivedInputID=='goalCheckBoxId'){ document.getElementById('setGoalsLength').innerHTML = totalCount; }else if(receivedInputID=='topicCheckBoxId'){ document.getElementById('selTopicSize').innerHTML = totalCount; } } // Js file to show the multiple picklist. $("select[multiple='multiple']").bsMultiSelect(); // code to calculate the count of selected picklist values **function countSelectedCheckbox(){ var totalCount = $("select#example>option:selected").length; document.getElementById('selContactSize').innerHTML = totalCount; } </script> </apex:form> </apex:page>
e the record. Due to limitation, not able to upload whole code.
- Rajesh Kumar Maharana
- April 13, 2020
- Like
- 0
Show data of a csv file in tabular form in LWC
Requirement: Whenever I upload a csv file, the data in the csv file should show in a tabular form(like above image.) in LWC.
Problem: Whenever I try to show the data in a <table>. The value is not showing in the <thead> &<tbody> (i.e. html). If I print the values of columnHeader and rows in the console, it gets displayed.
As I am not able to find where is the problem?
(If there is any doubt in understanding, please mention here.)
Below is the code.
<!-- html file --> <template> <lightning-card> <h3> <lightning-icon icon-name="utility:database" size="small"></lightning-icon> CSV Dataloader <button class="slds-button slds-button_destructive" style="margin-right:0; margin-left:auto; display:block;"> Clean Data </button> </h3> <lightning-input type="file" name="file" label="Attachment" accept=".csv" onchange={handleUploadFinished}> </lightning-input> <template if:true={showTable}> <table> <thead> <tr> <template for:each={csvString} for:item="head"> <th key={head.column_name}> {head.column_name} </th> </template> </tr> </thead> <tbody> <template for:each={lines} for:item="row"> <tr key={row}> <!--<template for:each={row} for:item="rowData">--> <td key={row}>{row}</td> <!--</template>--> </tr> </template> </tbody> </table> </template> </lightning-card> </template> ================================= // Javascript File import { LightningElement, track, wire } from 'lwc'; import getCSVObject from '@salesforce/apex/CSVCreator.getCSVObject'; export default class CustomCSVDataloaderInLWC extends LightningElement { @track colHeader = []; @track showTable = false; @track csvString; @track st; @track csvFile; @track lines; handleUploadFinished(event) { const uploadedFiles = event.detail.files; const file = uploadedFiles[0]; console.log("file : " + file); if (file) { this.showTable = true; //show the table console.log("this.showTable : " + this.showTable); let reader = new FileReader(); reader.readAsText(file, "UTF-8"); reader.onload = function (evt) { const csv = evt.target.result; console.log('csv : ' + csv); this.csvFile = csv; getCSVObject({ csv_str: csv }) .then(response => { console.log("response : " + JSON.stringify(response)); this.csvString =JSON.stringify([...response.headers]); console.log('this.csvString : '+this.csvString); this.lines = [...response.lines]; console.log('this.lines : '+JSON.stringify(this.lines)); let temp = response.headers; let col_head; this.colHeader = []; temp.forEach(element => { col_head = element.column_name;//JSON.stringify(element.column_name); console.log("col_head : " + col_head); this.colHeader = [...this.colHeader,col_head]; }); console.log("this.colHeader : " + this.colHeader); }).catch(error => { console.log("error2 ==> " + error); console.log("error ==> " + error.body.message); }); }; } } }Below is the console.log output of chrome in browser.
- Rajesh Kumar Maharana
- June 01, 2020
- Like
- 1
Show data of a csv file in tabular form in LWC
Requirement: Whenever I upload a csv file, the data in the csv file should show in a tabular form(like above image.) in LWC.
Problem: Whenever I try to show the data in a <table>. The value is not showing in the <thead> &<tbody> (i.e. html). If I print the values of columnHeader and rows in the console, it gets displayed.
As I am not able to find where is the problem?
(If there is any doubt in understanding, please mention here.)
Below is the code.
<!-- html file --> <template> <lightning-card> <h3> <lightning-icon icon-name="utility:database" size="small"></lightning-icon> CSV Dataloader <button class="slds-button slds-button_destructive" style="margin-right:0; margin-left:auto; display:block;"> Clean Data </button> </h3> <lightning-input type="file" name="file" label="Attachment" accept=".csv" onchange={handleUploadFinished}> </lightning-input> <template if:true={showTable}> <table> <thead> <tr> <template for:each={csvString} for:item="head"> <th key={head.column_name}> {head.column_name} </th> </template> </tr> </thead> <tbody> <template for:each={lines} for:item="row"> <tr key={row}> <!--<template for:each={row} for:item="rowData">--> <td key={row}>{row}</td> <!--</template>--> </tr> </template> </tbody> </table> </template> </lightning-card> </template> ================================= // Javascript File import { LightningElement, track, wire } from 'lwc'; import getCSVObject from '@salesforce/apex/CSVCreator.getCSVObject'; export default class CustomCSVDataloaderInLWC extends LightningElement { @track colHeader = []; @track showTable = false; @track csvString; @track st; @track csvFile; @track lines; handleUploadFinished(event) { const uploadedFiles = event.detail.files; const file = uploadedFiles[0]; console.log("file : " + file); if (file) { this.showTable = true; //show the table console.log("this.showTable : " + this.showTable); let reader = new FileReader(); reader.readAsText(file, "UTF-8"); reader.onload = function (evt) { const csv = evt.target.result; console.log('csv : ' + csv); this.csvFile = csv; getCSVObject({ csv_str: csv }) .then(response => { console.log("response : " + JSON.stringify(response)); this.csvString =JSON.stringify([...response.headers]); console.log('this.csvString : '+this.csvString); this.lines = [...response.lines]; console.log('this.lines : '+JSON.stringify(this.lines)); let temp = response.headers; let col_head; this.colHeader = []; temp.forEach(element => { col_head = element.column_name;//JSON.stringify(element.column_name); console.log("col_head : " + col_head); this.colHeader = [...this.colHeader,col_head]; }); console.log("this.colHeader : " + this.colHeader); }).catch(error => { console.log("error2 ==> " + error); console.log("error ==> " + error.body.message); }); }; } } }Below is the console.log output of chrome in browser.
- Rajesh Kumar Maharana
- June 01, 2020
- Like
- 1
Create task object records based on contact names in the multi-select picklist
Activity Objective==> Wherever you see Activity Objective in the VFP, I have added the codes for the multi-picklist.
ISSUE: whenever I select the contact names (either 1 or more than 1) from the multi-picklist and click on save. It will save the record, but in the name field in the Task object will be blank. If I have selected 1 0r more than 1 contact names, it will create single record in the Task object and the name field will be blank.
REQUIREMENT: Now I want that, how many contact names I have selected from the multi-picklist. That many records will be created in the Task Object.
Already in the controller, record creation code is written. It is checking the contact name isChecked=true, then it will create the record.
In my code, it is taking isChecked=false. So it is not able to creat
<apex:page standardController="Task" id="thePageId" extensions="NewTaskCtrl" tabStyle="Task" action="{!loadNewTask}"> <apex:outPutPanel id="myMSG"> <apex:pageMessages id="msg" /> </apex:outPutPanel> <apex:slds /> <apex:form id="newTaskPage"> <!-- CDN links for the multiple picklist --> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" /> <link href="https://www.jqueryscript.net/css/jquerysctipttop.css?v3" rel="stylesheet" type="text/css" /> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"/> <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/@dashboardcode/bsmultiselect@0.5.40/dist/js/BsMultiSelect.min.js"></script> <!-- / Activity Objective - New picklist code--> <apex:actionFunction action="{!filterFields}" name="filterFields" reRender="myMSG,taskInfo" > <apex:param value="" name="tType" /> </apex:actionFunction> <apex:sectionHeader title="Task" subtitle="New Task"/> <apex:inputHidden value="{!inputValue}" id="theHiddenInput"/> <div class="slds-card"> <div class="slds-card__header slds-grid slds-border_bottom slds-p-bottom_small" style="background-color: #fafaf9;"> <div class="slds-media slds-media_center slds-has-flexi-truncate"> <div class="slds-media__body"> <h2 class="slds-card__header-title slds-text-heading_small"> Task Edit </h2> </div> <div class="slds-no-flex"> <apex:commandButton action="{!performSave}" title="Save" value="Save" styleClass="slds-button slds-button_brand"/> <apex:commandButton action="{!cancel}" title="Cancel" value="Cancel" styleClass="slds-button slds-button_neutral"/> </div> </div> </div> <div class="slds-card__body slds-p-horizontal_small"> <div class="slds-m-bottom_small slds-p-around_xx-small" style="background-color: #fafaf9;"><strong>Related To</strong></div> <div class="slds-form slds-form_horizontal"> <div> <div style="max-width: 600px;"> <apex:outputPanel styleClass="relatedToSection"> <div class="slds-form-element"> <apex:outputLabel value="Account" styleClass="slds-form-element__label"/> <div class="slds-form-element__control slds-m-top_xxx-small"> <apex:outputField value="{!taskObjectParent.WhatId}" title="This will contain Related Account" label="Account" /> </div> </div> <apex:pageBlock id="OfficeContactList"> <!-- rendered="{!IF((taskObjectParent.Id = null),true,false)}" --> <apex:outputPanel style="display:none" styleclass="taskContactMultiList"> <div class="slds-form-element"> <apex:outputLabel value="Select Contact to create task" styleClass="slds-form-element__label" id="con12"/> <div class="slds-form-element__control" style="padding-right: 82px;"> <!-- Activity Objective --> <!-- Show the multiple picklist values and binding--> <div class="container"> <select name="contactNames" id="example" class="form-control" multiple="multiple" onChange="countSelectedCheckbox()"> <apex:repeat value="{!avaiableContactlList}" var="con" id="conTable"> <option value="{!con.isChecked}" id="opt">{!con.Name}</option> <!---value is changed --> </apex:repeat> </select> </div> <!-- / Activity Objective --> Total Number of Selected record :<span style="font-weight:bold" id="selContactSize">0</span> </div> </div> </apex:outputPanel> </apex:pageBlock> <div class="slds-form-element"> <apex:outputLabel value="Topics Discussed" styleClass="slds-form-element__label"/> <apex:outputPanel id="refreshing"> <div class="slds-form-element__control" style="padding-right: 82px;"> <div class="slds-scrollable_y slds-m-top_x-small slds-m-bottom_small slds-p-around_x-small" style="max-height: 90px; border: 1px solid #dddbda; border-radius: .25rem;"> <table> <apex:repeat value="{!avaiableTopicList}" var="topic"> <tr> <td width="20" class="slds-p-bottom_x-small"> <span class="slds-checkbox slds-checkbox_standalone"> <apex:inputCheckbox value="{!topic.isChecked}" onclick="selectAllCheckboxes('topicCheckBoxId')" id="topicCheckBoxId"/> <span class="slds-checkbox_faux"></span> </span> </td> <td class="slds-p-bottom_x-small"> <label> {!topic.Name} </label> </td> </tr> </apex:repeat> </table> </div> Total Number of Selected record :<span style="font-weight:bold" id="selTopicSize">{!totalAvaiableTopic}</span> </div> </apex:outputPanel> </div> </div> </div> </div> </div> <div class="slds-card__footer slds-text-align_right"> <apex:commandButton action="{!performSave}" title="Save" value="Save" styleClass="slds-button slds-button_brand"/> <apex:commandButton action="{!cancel}" title="Cancel" value="Cancel" styleClass="slds-button slds-button_neutral"/> </div> </div> <script> function setFocusOnLoad() {} function toggleComponent(taskType,componentToToggle,taskId){ console.log('taskId : '+taskId); //filterFields(); if(taskId == 'NULL' || taskId == ''){ var contactComponent = document.getElementsByClassName(componentToToggle)[0]; var selectedValue = taskType.value; console.log(componentToToggle); if(selectedValue == 'Physician-to-Physician Visit' || selectedValue == 'Sports Medicine' ){ contactComponent.style.display ='block'; }else{ contactComponent.style.display ='none'; } }else{ var contactComponent = document.getElementsByClassName(componentToToggle)[0]; var selectedValue = taskType.value; console.log(componentToToggle); var oldTaskType = String(document.getElementById('thePageId:newTaskPage:theHiddenInput').value); if((oldTaskType != 'Physician-to-Physician Visit' && selectedValue == 'Physician-to-Physician Visit') || (oldTaskType != 'Sports Medicine' && selectedValue == 'Sports Medicine')){ contactComponent.style.display ='block'; }else{ contactComponent.style.display ='none'; } } //alert(taskType.value); filterFields(taskType.value); } function selectAllCheckboxes(receivedInputID){ var inputCheckBox = document.getElementsByTagName("input"); var totalCount = 0; for(var i=0; i<inputCheckBox.length; i++){ if(inputCheckBox[i].id.indexOf(receivedInputID)!=-1){ if(inputCheckBox[i].checked == true){ //alert("inputCheckBox[i].checked==>>"+inputCheckBox[i].checked); totalCount = totalCount + 1; } } } //console.log('====>' + totalCount); if(receivedInputID=='contactCheckBoxId'){ document.getElementById('selContactSize').innerHTML = totalCount; }else if(receivedInputID=='goalCheckBoxId'){ document.getElementById('setGoalsLength').innerHTML = totalCount; }else if(receivedInputID=='topicCheckBoxId'){ document.getElementById('selTopicSize').innerHTML = totalCount; } } // Js file to show the multiple picklist. $("select[multiple='multiple']").bsMultiSelect(); // code to calculate the count of selected picklist values **function countSelectedCheckbox(){ var totalCount = $("select#example>option:selected").length; document.getElementById('selContactSize').innerHTML = totalCount; } </script> </apex:form> </apex:page>
e the record. Due to limitation, not able to upload whole code.
- Rajesh Kumar Maharana
- April 13, 2020
- Like
- 0
How to cover execute method in test class for Batch class.
Hi guys.
I have batch calss name:Del_leads
and a Schedule Class bulkdelleads.
When i am writing test method for batch class it is not covering the execute method i am calling this execute from schedule class.Can any body help to figure out the problem.
Batch Class:-
=====================
global class Del_leads implements Database.Batchable<sobject>
{
public String query;
public date d=System.today();
public integer i=7;
Public Date z=d-i;
Public String s;
public integer j;
Public string k='Name'+','+'Company'+','+'phone'+','+'Email';
global Database.QueryLocator start(Database.BatchableContext BC){
system.debug(query);
return Database.getQueryLocator(query);
}
global void execute(Database.BatchableContext BC,List<Lead> Lds){
for( j=0;j<lds.size();j++){
if(j==0){
s +=k+'\n'+ lds[j].Name+','+lds[j].Company+','+lds[j].phone+','+lds[j].Email;
} else{
s +=+'\n'+ lds[j].Name+','+lds[j].Company+','+lds[j].phone+','+lds[j].Email;
}
}
Blob b=Blob.valueOf(s);
Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
efa.setFileName('attachment.csv');
efa.setBody(b);
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setToAddresses(new String[] {'franktoanil@gmail.com'});
mail.setSenderDisplayName('Batch Processing');
mail.setSubject('Batch Process Completed');
mail.setPlainTextBody('Please find the attachment of deleted records');
mail.setFileAttachments(new Messaging.EmailFileAttachment[] {efa});
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
delete Lds;
}
global void finish(Database.BatchableContext BC){
System.debug(LoggingLevel.WARN,'Deleting Leads Finished');
}
=====================================================
/*-----------------Test Method-----------------Only 47 % test coverage*/
=====================================================
public static testMethod void Del_leads (){
List <Lead> lds = new List<Lead>();
for(integer i = 0; i<200; i++){
Lead l = new Lead(LastName='Anil',Company='ef');
lds.add(l);
}
insert lds;
test.startTest();
Del_leads dl = new Del_Leads();
dl.query='select id,Name,Company,Phone,Email from lead where createddate<=:z and date_opened__c=null ';
ID batchprocessid = Database.executeBatch(dl);
test.stoptest();
System.AssertEquals(
database.countquery('SELECT COUNT()'+' FROM Lead '),200);
}
}
============================
Schedule Class
============================
global class bulkdelleads Implements Schedulable{
public static String CRON_EXP = '0 0 0 3 9 ? 2022';
global void Execute(SchedulableContext SC){
Del_leads ld=new Del_leads();
ld.query='select id,Name,Company,Phone,Email from lead where createddate<=:z and date_opened__c=null ';
database.executebatch(ld);
}
==================================
/*----------Test Method------------------ 100% test Coverage-*/
==================================
static testmethod void bulkdelleads () {
Test.startTest();
Lead l = new Lead ();
l.LastName = 'Raghu ';
l.company='eg';
insert l;
// Schedule the test job
String jobId = System.schedule('bulkdelleads ',bulkdelleads.CRON_EXP,new bulkdelleads ());
// Get the information from the CronTrigger API object
CronTrigger ct = [SELECT Id, CronExpression, TimesTriggered,
NextFireTime
FROM CronTrigger WHERE id = :jobId];
// Verify the expressions are the same
System.assertEquals(bulkdelleads.CRON_EXP,ct.CronExpression);
// Verify the job has not run
System.assertEquals(0, ct.TimesTriggered);
// Verify the next time the job will run
System.assertEquals('2022-09-03 00:00:00',
String.valueOf(ct.NextFireTime));
Test.stopTest();
}
}
Thanks
Anil.B
- @anilbathula@
- September 10, 2012
- Like
- 0