• CharuDutt
  • ALL STAR
  • 8472 Points
  • Member since 2020
  • ACS


  • Chatter
    Feed
  • 273
    Best Answers
  • 0
    Likes Received
  • 7
    Likes Given
  • 2
    Questions
  • 1095
    Replies
global class BatchOnContact implements Database.Batchable<sObject>, Database.Stateful{
    
    global Database.QueryLocator start(Database.BatchableContext bc){     
        
        return Database.getQueryLocator('select Id, name, StageName from opportunity where StageName=\'Closed Won\'');
        
    }
    global void execute(Database.BatchableContext bc, List<opportunity> Opplist){
        List<OpportunityLineItem> OList = new List<OpportunityLineItem>();
        List<Product2> prolist= [SELECT Id from Product2 Limit 10];
              For(opportunity opp:  Opplist){
            for(Integer i=0; i<10; i++){
               OpportunityLineItem op= new OpportunityLineItem(opportunityId=opp.id, Product2Id=prolist.get(i).id,Quantity =1, TotalPrice=1000);
                OList.add(op);                                                               
            }  opp.Pricebook2Id='0066F00000yUeDpQAK';            
        }update opplist;
        insert OList;      
    }
 global void finish(Database.BatchableContext bc){ }
}

I have a situation where I have two objects Opportunity and a custom Object Contract__c. In both the object I have a field called reference_name__c. Now the situation is that I have to query the objects and return the reference_name__c values. If Opportunity has reference_name__c value and Contract__c don't have reference_name__c value return value. If Opportunity has no reference_name__c value and Contract__c has reference_name__c value then return the value. How could I write the query? The query was written by me just satisfies the 1st condition. Please help me with the query.


Select Id, reference_name__c,(Select ID, reference_name__c from Contract__r where reference_name__c !=null Limit 10) from opportunity where AccountId != null AND reference_name__c != null AND Owner.AccountId =loggedInUser.Contact.AccountId limit 10

How to achieve this with helper. 
component:
<aura:component controller="AccountSearch" implements="flexipage:availableForRecordHome,force:hasRecordId" access="global" >
    <!--button-->
    <aura:attribute name="searchkeyword" type="string" description="used to store user search"/>
    <aura:attribute name="TotalnoofRecords" type="integer" default="0" description="used to display the  no of records"/>
    <aura:attribute name="searchResult" type="List" description="used to store and display result"/>
    <aura:attribute name="message" type="boolean" description="used to  display message"/>
    <aura:attribute name="AccList" type="Account[]" />
    <aura:attribute name="columns" type="List"/>
    <!--aura:handler name="init" value="{!this}" action="{!c.fetchAccount}" /-->
    <lightning:button variant="brand" label="search" iconName="utility:search" onclick="{!c.Search}"/>
    <lightning:input value ="{!v.searchkeyword}"
                keyField="True"
                placeholder="search accounts.."
                label="AccountName"/>
      
    </aura:component>
controller:
({
     Search:function(component,event,helper) {
         helper.Searchhelper(component,event,helper);
     }
     })
Helper:
({
    SearchHelper : function(component,event) {
        
       component.set('v.columns', [
          {label:'AccountName', fieldName:'Name', type: 'text'},
          {label:'Type', fieldName:'Type', type: 'text'},
          {label:'Industry', fieldName:'Industry', type: 'text'},
          {label:'Phone', fieldName:'Phone', type: 'Phone'},
          {label:'Fax', fieldName:'Fax', type: 'text'}]);

           
        //Step1: Get the Apex method that should be invoked
        
         var action = component.get("c.fetchAccount");
         
       
         //step2: set the parameters
         action.setParams({ 
           'searchword':component.get("v.searchkeyword")
           
         });
        //Step4: handle the response from apex class method/Server side method
        action.setCallback(this, function(response){
            var storeResponse = response.getReturnValue();
            if (storeResponse.length==0){
                component.set("v.message",true);
            }
            else{
                component.set("v.message",false);
            }

           component.set("v.TotalnoofRecords",storeResponse.length);
            component.set("v.searchResult",storeResponse);
           
        });
        //Step3: Enqueue action/ApexMethod to be executed 
        $A.enqueueAction(action);
     

       
    }
})

Apex:
public class AccountSearch {
@AuraEnabled
    public static List<Account> fetchAccount(string searchword){
        string Searchkey = '%'+searchword+'%';
        List<Account> AccList = [select id,Name,Type,Industry,Phone,Fax from Account where Name=:Searchkey LIMIT 500];
        return AccList;
}
  
}
Test Class 

@isTest
    public static void testmethod3(){
        contact con = new contact();
        con.LastName = 'Test contact';
        con.Email = 'sample@sample.com';
        insert con;
        List<Case> caseList = new List<Case>();
        for(Integer i=1; i<=200 ; i++){
            Case cs = new Case();
            cs.Status = 'New';
            cs.Origin = 'Phone';
            cs.ContactId =con.Id;
            caseList.add(cs);
        }
        
          Test.startTest();
          insert caseList;
          Test.stopTest();
    
}

 
Hi everyone,
Please help me in writting test class for the below apex code:

public class xyz {

        public abc objabc{get;set;}
        public Boolean sendEmail {get; set;}
        public Task objtask{get;set;}
        public boolean isChecked{get;set;}
    public xyz() {
        
        
        String objabcId = ApexPages.currentPage().getParameters().get('id');
                
            objabc = new abc();
        
             if(objabcId !=null && objabcId !=''){
                 
                 objabc = [Select id,OwnerId,name from abc 
                            where id=:ApexPages.currentPage().getParameters().get('id')];
             }
              
            if(objabc.id!=null){
                sendEmail = true;
                objtask= new task();
                objtask.whatid=objabc.id;
                objtask.RecordTypeId = [select Id,Name from RecordType where name='abcd' and SOBjectType='Task' limit 1].Id;
                objtask.status = 'Completed';
                objtask.type = 'Assigned';
                objtask.OwnerID = UserInfo.getUserId();
                objtask.Subject='Assignment';
            }
    }
      
        public pagereference save() {
            try {
                if(objtask.subject!=null){
                    insert objtask;
                    update objabc;
                    if(sendEmail){                       
                        Database.DMLOptions dlo = new Database.DMLOptions();
                        dlo.EmailHeader.triggerUserEmail = true;
                        database.update(objabc,dlo);                        
                    }
                }else{
                    Apexpages.addMessage(new Apexpages.message(ApexPages.Severity.Error,'Subject cannot be Null !!!'));
                    return null;
                }
                string abcobjurl = objabc.id;
                abcobjurl = abcobjurl.substring(0,3);
                PageReference orderPage = new PageReference('/' + abcobjurl);
                return orderPage;
            } catch (Exception e) {
                system.debug('---inside Exception---'+e.getMessage());
                system.debug('---inside Exception Line---'+e.getLineNumber());
                Apexpages.addMessage(new Apexpages.message(ApexPages.Severity.Error,e.getMessage()));
                return null;
            }
        }
        
}


Thanks in advance!
Hi Developers,

How can I restrict a string field to not allow  0-9^#*@!_()$%&+>< ( ) | 

Phone should allows only numbers and hyphen 

Thanks in Advance.
Hello, I have a component on account object. I want to render part of the component dependend on if the checkbox 'Urlaub__c' on the ownerUser is true. The problem I have is, that with the way I did it the section Is not showing up even tough the checkbox is true. Could you tell me what to change so that it works?
 
<aura:if isTrue="{!v.OwnerUser.Urlaub__c}">
            <lightning:layoutItem padding="around-small">                
                <br></br> 
                
                <div class="header-column" width="100%">
                    <div style="font-size: 15px;"><b>{!v.OwnerUser.Vertreter__c.Name}</b></div>
                    <div style="font-size: 10px;">Team {!v.OwnerUser.Team_2020__c}</div>
                    <div>
                        <a href="{!'tel:' + v.OwnerUser.Vertreter__c.MobilePhone}"><lightning:icon iconName="action:call" size="xx-small" alternativeText="Telefon" title="Telefon"   /></a>&nbsp;
                        <a href="{!'mailto:' + v.OwnerUser.Vertretung__c.Email}"><lightning:icon iconName="action:email" size="xx-small" alternativeText="E-Mail" title="E-Mail" /></a>&nbsp;
                        <a href="{!v.OwnerUser.Vertreter__c.Link_BookingTime__c}" target="_blank"><lightning:icon iconName="action:new_event" size="xx-small" alternativeText="BookingTime" title="BookingTime" /></a> 
                    </div>
                    
                </div>
                   
            </lightning:layoutItem>
              </aura:if>

 

Hello ,
I have one requirement where in I am capturing three fields value on a text field with a comma separated values . Three values are Id of a record, phone no and email of the record. Now i need to update three different fields on an other object with the text field(where I am storing Id, phone and email ). If that text filed contains an id then update the look up field , if the text field contains phone then update the phone field and same goes for email field. 

Could anyone please help me how to use split functionality here to update the three differnet fields from one text field which contains all the values in Apex.
Thank you in advance

I have created a batch apex but unable to write test class for the same.


global class exportobjectascsvbatch implements Database.Batchable <SObject>{
global Database.QueryLocator start (Database.BatchableContext bc)
{
    String SobjectApiName = 'Opportunity';
Map<String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
Map<String, Schema.SObjectField> fieldMap = schemaMap.get(SobjectApiName).getDescribe().fields.getMap();
String query = 'Select ';
for(String fieldName : fieldMap.keyset() )
    {
        query += fieldname+',';   
        }

query = query.removeEnd(',');
query += ' from Opportunity where lastmodifieddate = yesterday';
    system.debug(query);
    return Database.getQueryLocator(query);
}
   global void execute(Database.BatchableContext bc, List<Opportunity> OppList)
   {
       try{     
String SobjectApiName = 'Opportunity';
Map<String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
Map<String, Schema.SObjectField> fieldMap = schemaMap.get(SobjectApiName).getDescribe().fields.getMap();
String generatedCSVFile = '';
for(String fieldName : fieldMap.keyset() )
    {
        generatedCSVFile += fieldName +',';     
        }
generatedCSVFile = generatedCSVFile.removeEnd(',');
generatedCSVFile = generatedCSVFile + '\n'; 
for(Opportunity company: OppList){
  for(String fieldName : fieldMap.keyset() )
    {
        generatedCSVFile += company.get(fieldName)+ ',';     
        }
    generatedCSVFile = generatedCSVFile.removeEnd(',');
    generatedCSVFile = generatedCSVFile + '\n'; 
}

       //send email with generated csv file
Messaging.EmailFileAttachment csvAttachment = new Messaging.EmailFileAttachment();
Blob csvBlob = blob.valueOf(generatedCSVFile);
String csvName = 'Opportunitybackup.csv';
csvAttachment.setFileName(csvName);
csvAttachment.setBody(csvBlob);
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
String[] toAddresses = new String[]{'thanigai.k.balaji@apisero.com'};
String subject = 'Opportunity backup';
email.setSubject(subject);
email.setToAddresses(toAddresses);
email.setPlainTextBody('Opportunity backup');
email.setFileAttachments(new Messaging.EmailFileAttachment[]{csvAttachment});
Messaging.SendEmailResult[] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[]{email});
       }
       catch(exception e)
       {
            system.debug('Exception Caught:'+e.getmessage());
       }
       }
       
    global void finish(Database.BatchableContext bc)
    {
    }  
}
 
hii,

how to resolve Method does not exist or incorrect signature ?

my code:
public class VerifyAccountcls {
 @AuraEnabled
    public static void  verify(List<String> recordid){
        List<Account> acclist = new List<Account>();
        for(Account acc:[select Id, Name, Phone, Website,
                    BillingStreet, BillingCity,
                         BillingState, BillingPostalCode, Verified__c from Account where Id in :recordid]){
                             acc.Verified__c = true;
                             acclist.add(acc);
                         }
        if(acclist.size()>0){
            update acclist;
        }
        
    }
@AuraEnabled
    public static void  unverify(List<String> recordid){
        List<Account> acclist = new List<Account>();
        for(Account acc:[select Id, Name, Phone, Website,
                    BillingStreet, BillingCity,
                         BillingState, BillingPostalCode, Verified__c from Account where Id in :recordid]){
                             acc.Verified__c = false;
                             acclist.add(acc);
                         }
        if(acclist.size()>0){
            update acclist;
        }
        
    }

}

thanks in advance,
Zeel
({
openModel: function(component, event, helper) {
// Set isModalOpen attribute to true
component.set("v.isModalOpen", true);
},

closeModel: function(component, event, helper) {
// Set isModalOpen attribute to false
component.set("v.isModalOpen", false);
},
handleSelect: function (cmp, event, helper) {
// This will contain the string of the "value" attribute of the selected
// lightning:menuItem
var selectedMenuItemValue = event.getParam("value");
alert("Menu item selected with value: " + selectedMenuItemValue);
}

})
Hi!
I have a contacts table and I need to delete a row using a modal window with two buttons: Cancel and Delete. The first button works, but the second doesn't. Here is mistake:
User-added image

Please tell me what is wrong. Here is my code:

Parent:


HTML
<template>
    <lightning-card title="Contact Table">
        <lightning-layout multiple-rows="true" vertical-align="end">
            <lightning-layout-item size="4" padding="around-small">
                                <!-- lightning input -->
                <lightning-input class="text" type="text" label="Search by name" value={key} onchange={updateKey}></lightning-input>
            </lightning-layout-item>
            <lightning-layout-item size="2" padding="around-small">
                                <!-- lightning button -->
                <lightning-button label="filter" onclick={handleSearch} variant="brand"></lightning-button>  
            </lightning-layout-item>
            <lightning-layout-item size="12" padding="around-small">
                                 <!--lightning table -->
                <lightning-datatable key-field="id" data={contacts} columns={columns}
                    onrowaction={handleRowAction} row-number-offset={rowOffset}>
                </lightning-datatable>
            </lightning-layout-item>
        </lightning-layout>  
    </lightning-card>
        <c-modal-delete
        title='Delete Contact'
            message='“Are you sure?”'
            confirm-label='Delete'
            cancel-label='Cancel'
            visible={isDialogVisible}
            original-message={originalMessage}
            name="confirmModal"
            ondeletecontact={handleClick}
            record-id={recordId}
            selected-row={selectedRow}
        ></c-modal-delete>
</template>

JS
import {LightningElement, api, track, wire} from 'lwc';
import getContacts from '@salesforce/apex/ContactTableWithDeleteButton.getContacts';
import searchContacts from '@salesforce/apex/ContactTableWithDeleteButton.searchContacts';
import {deleteRecord} from 'lightning/uiRecordApi';
import {ShowToastEvent} from 'lightning/platformShowToastEvent';
import {NavigationMixin} from 'lightning/navigation';
import {refreshApex} from "@salesforce/apex";
const columns = [
    { label: 'Contact FirstName', fieldName: 'FirstName', type: 'text' },
    { label: 'Contact LastName', fieldName: 'LastName', type: 'text' },
    { label: 'Phone', fieldName: 'Phone', type: 'text' },
    { label: 'Email', fieldName: 'Email', type: 'Email' },
    { label: "Account Name", fieldName: "recordLink", type: "url",
        typeAttributes: {label: {fieldName: "AccountName"}, tooltip: "Name", target: "_blank", linkify: true} },
    { label: 'Created Date', fieldName: 'CreatedDate', type: 'date',
        typeAttributes: {day: 'numeric', month: 'numeric', year: 'numeric', hour: '2-digit', minute: '2-digit', hour12: true} },
    { type: 'button-icon', label: 'Delete', initialWidth: 75,
        typeAttributes: {iconName: 'action:delete', title: 'Delete', name: 'delete_contact', variant: 'border-filled', alternativeText: 'Delete'} }
];
export default class contactTable extends LightningElement {
   
    data;
    columns = columns;
    contacts;
    searchValue = '';
    error;
    refreshData;
    @api recordId;
    @api objectApiName;
    @api AccountId;
    @api ContactId;
    @track data = {};
    @track record = {};
    @track currentRecordId;
    @track rowOffset = 0;
    @track columns = columns;
    @track isDialogVisible = false;
    @track originalMessage;
    @track displayMessage = 'Click on the \'Open Confirmation\' button to test the dialog.'
    _wiredResult;
    error;
    @wire(getContacts)
    wiredContacts(value) {
        this.refreshData = value;
        const {error, data} = value;
        if (data) {
            let contactData = JSON.parse(JSON.stringify(data));      
            contactData.forEach(record => {
                if (record.AccountId) {
                    record.recordLink = "/" + record.AccountId;  
                    record.AccountName = record.Account.Name;
                }
            });
            this.contacts = contactData;
        } else if (error) {
            this.error = error;
        }
    }
    handleRowAction(event) {
        console.log('handleRowAction ', event);        
        if (event.detail.action.name === 'delete_contact') {
            this.selectedRow = event.detail.row;
            this.isDialogVisible = true;
        }
    }
    handleClick(event) {
        console.log("handleClick");
        this.originalMessage = event.currentTarget.dataset.id;
        if (event.target.name === 'confirmModal') {
            if (event.detail.status === 'confirm') {
                let selectedRow = event.detail.selectedRow;
                this.deleteContacts(selectedRow);
                this.isDialogVisible = false;
            } else if (event.detail.status === 'cancel') {
                this.isDialogVisible = false;
            }
            this.isDialogVisible = false;
        }
    }
   
    deleteContacts(event) {
            console.log('deleteContacts = ', event);
   
            const action = event.detail.action;
            console.log('action = ', JSON.stringify(action));
   
            const row = event.detail.row;
            console.log('row = ', JSON.stringify(row));
            if (action.name === 'delete_contact') {
                console.log('Done = ', row.Id);
                deleteRecord(row.Id)
                .then(() => {
                    const rows = this.data;
                    return refreshApex(this.refreshData);
                })
            }
        }
    updateKey(event){
        this.searchValue = event.target.value;
    }
    handleSearch(){
        searchContacts({searchKey: this.searchValue})
        .then(result => {
            let contactData = JSON.parse(JSON.stringify(result));        
            contactData.forEach(record => {
                if (record.AccountId) {
                    record.recordLink = "/" + record.AccountId;  
                    record.AccountName = record.Account.Name;
                }
            });
            this.contacts = contactData;
        })  
        .catch(error => {
            console.log('Error:', error);
        });
    }
}

Child

HTML
<template>
    <lightning-card if:true={visible}>
        <div class="slds-container_small">
            <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">
                    <header class="slds-modal__header">
                        <button class="slds-button slds-button_icon slds-modal__close slds-button_icon-inverse" name="cancel" onclick={handleRowAction}>                              
                            <lightning-icon icon-name="utility:close"
                                            alternative-text="close"
                                            variant="inverse"
                                            size="small">
                            </lightning-icon>
                            <span class="slds-assistive-text">Close</span>
                        </button>
                        <h2 data-id="title" class="slds-text-heading_medium slds-hyphenate">{title}</h2>
                    </header>
                    <div class="slds-modal__content slds-p-around_medium" id="modal-content-id-1">
                        <p data-id="message">{message}</p>
                    </div>
                    <footer class="slds-modal__footer">
                        <lightning-button variant="neutral"
                                          name="cancel"
                                          label={cancelLabel}
                                          title={cancelLabel}
                                          onclick={handleRowAction}>
                        </lightning-button>
                        <lightning-button class="slds-m-left_x-small"
                                          variant="brand"
                                          name="confirm"
                                          label={confirmLabel}
                                          title={confirmLabel}
                                          onclick={handleRowAction}>
                        </lightning-button>
                    </footer>
                </div>
            </section>
            <div class="slds-backdrop slds-backdrop_open"></div>
        </div>
    </lightning-card>
</template>

JS
import {LightningElement, api, track} from 'lwc';
export default class ConfirmationDialogDelete extends LightningElement {
    @api visible = false; //used to hide/show dialog
    @api title = ''; //modal title
    @api name; //reference name of the component
    @api message = ''; //modal message
    @api confirmLabel = ''; //confirm button label
    @api cancelLabel = ''; //cancel button label
    @api originalMessage; //any event/message/detail to be published back to the parent component
    @api recordId;
    @api deleteContacts;
    @track isDialogVisible = false;
    @track contactId;
    //handles button clicks
    @api selectedRow;
    handleRowAction(event) {
        //creates object which will be published to the parent component
        let finalEvent = {
            originalMessage: this.originalMessage,
            status: event.target.name,
            selectedRow: this.selectedRow
        };
        //dispatch a 'click' event so the parent component can handle it
        this.dispatchEvent(new CustomEvent('deletecontact', {detail: finalEvent}));
    }
}

Apex
public with sharing class ContactTableWithDeleteButton {
    @AuraEnabled(cacheable=true)
    public static List<Contact> getContacts() {
        return [
            SELECT Id, FirstName, LastName, Phone, Email, Account.Name, AccountId, CreatedDate
            FROM Contact
        ];
    }
    @AuraEnabled(cacheable=true)
    public static List<Contact> searchContacts(String searchKey) {
        String searchKeyword = '%' + searchKey + '%';
        List<Contact> contacts = [
            SELECT Id, FirstName, LastName, Phone, Email, Account.Name, AccountId, CreatedDate
            FROM Contact
            WHERE Name LIKE :searchKeyword
        ];
        return contacts;
    }
}

I habe an object named Teacher(Parent) Object and having a filed name as “Number of Active Students”(Number) and a having another Field on Student(Child) Object named as Active(Checkbox).

so how can i create

   Trigger to find the number of Active Students in “Number of Active Students” Fields when any Student record is created, deleted or undeleted.


please help ......
and please suggest any good youtube channel for learning salesforce development

Hi All - I just want to call the apex method which has two paramaeters in when on click button. I have created the Button using LWC and trying to call the apex method , below is my code. can someone correct me if my approach is correct. New to LWC trying to implement this want best way and suggestions.

Apex Method :
@AuraEnabled(cacheable=true)
    public static void recountAssets(Id b2bAccountId, Id b2bOrderId){
        String sDISCOCouponCode;
        List<Id> lstB2BOrderIds = new List<Id>();
        List<String> lstPkgDefCodes = new List<String>();
        List<OrderItem> lstB2BOrderItems = new List<OrderItem>(); //List of all B2B Order Items that requires reconciliation
        //List<Order> lstB2BOrders = new List<Order>();//List of all B2B Orders that requires reconciliation
        
        
        if(b2bAccountId != null){
            Account objB2BAccount = [SELECT ID, DISCOCouponCode__c FROM Account WHERE ID =: b2bAccountId AND RecordType.DeveloperName = 'ACC_B2BCustomer' LIMIT 1];
            if(objB2BAccount != null){
                sDISCOCouponCode = objB2BAccount.DISCOCouponCode__c;
                if(!String.isEmpty(sDISCOCouponCode)){
                    if(b2bOrderId != null){
                        // for(Order o:b2bOrders){
                        //     lstB2BOrderIds.add(o.Id);
                        //     system.debug('lstB2BOrderIds' +lstB2BOrderIds);
                        // }
                        
                        lstB2BOrderItems = [SELECT  Id, OrderId, Package_Definition_Code__c, DISCOCouponCode__c, NoOfActiveSubscriptionsExclBuffer__c, Quantity, Order.NumberOfDigitalSubscriptionSold__c
                            FROM OrderItem WHERE TECH_OrderCategory__c ='Corporate' AND (OrderId =: b2bOrderId OR Order.Original_Subscription__r.Id =: b2bOrderId) AND DISCOCouponCode__c =: sDISCOCouponCode AND Order.Status = 'ACTIVE' AND Order.StartDate__c <= TODAY AND Order.End_Date__c >= TODAY AND Order.B2BProduct__c != 'Anonymous' ORDER BY Order.StartDate__c ASC];
                        system.debug('lstB2BOrderItems' +lstB2BOrderItems);
                    }
                    else{
                        lstB2BOrderItems = [SELECT  Id, OrderId, Package_Definition_Code__c, DISCOCouponCode__c, NoOfActiveSubscriptionsExclBuffer__c, Quantity, Order.NumberOfDigitalSubscriptionSold__c
                            FROM OrderItem WHERE TECH_OrderCategory__c ='Corporate' AND DISCOCouponCode__c =: sDISCOCouponCode AND Order.Status = 'ACTIVE' AND Order.StartDate__c <= TODAY AND Order.End_Date__c >= TODAY AND Order.B2BProduct__c != 'Anonymous' ORDER BY Order.StartDate__c ASC];
                    }

                    // lstB2BOrderIds.clear(); //Repurposing the variable for further use
                    // system.debug('lstB2BOrderIds' +lstB2BOrderIds);
                    if(lstB2BOrderItems.size()>0){
                        
                        for(OrderItem oi:lstB2BOrderItems){
                            lstPkgDefCodes.add(oi.Package_Definition_Code__c); //Prepare the list of package definition codes
                            lstB2BOrderIds.add(oi.OrderId); //Prepare the list of ids of all the B2B orders that will go through active sub count reconciliation
                            oi.NoOfActiveSubscriptionsExclBuffer__c = 0; //Reset the current asset count
                            system.debug(' oi.NoOfActiveSubscriptionsExclBuffer__c ' + oi.NoOfActiveSubscriptionsExclBuffer__c);
                        }
                    }

                    if(lstPkgDefCodes.size()>0){
                        Map<String, Decimal> mapActiveAssetCount = new Map<String, Decimal>(); //Count of all the active assets that requires recounting, grouped by Package Definition Code
                        List<Asset> lstActiveAssets = [SELECT Package_Definition_Code__c, Id FROM Asset
                            WHERE Package_Definition_Code__c IN: lstPkgDefCodes AND Order_Product__r.DISCOCouponCode__c =: sDISCOCouponCode AND Status = 'ACTIVE'];
                        for (Asset a : lstActiveAssets)  {
                            if(mapActiveAssetCount.containsKey(a.Package_Definition_Code__c)){
                                //System.debug('a.Package_Definition_Code__c : ' + a.Package_Definition_Code__c );
                                Decimal nAssetCount = (Decimal) mapActiveAssetCount.get(a.Package_Definition_Code__c);
                                nAssetCount++;
                                system.debug('nAssetCount' +nAssetCount);
                                mapActiveAssetCount.put(a.Package_Definition_Code__c, nAssetCount);
                            }
                            else{
                                mapActiveAssetCount.put(a.Package_Definition_Code__c, 1);
                            }
                        }

                        Map<Id,Decimal> mapTotalActiveSubsInB2BOrder = new map<Id,Decimal>();
                        for(OrderItem oi:lstB2BOrderItems){
                            Decimal nB2BOrderTotalActiveSubs;
                            if(mapTotalActiveSubsInB2BOrder.containsKey(oi.OrderId)){
                                nB2BOrderTotalActiveSubs = mapTotalActiveSubsInB2BOrder.get(oi.OrderId);
                                system.debug('nB2BOrderTotalActiveSubs' +nB2BOrderTotalActiveSubs);
                            }
                            else{
                                nB2BOrderTotalActiveSubs = 0;
                                system.debug('nB2BOrderTotalActiveSubs' +nB2BOrderTotalActiveSubs);
                            }

                            if(mapActiveAssetCount.containsKey(oi.Package_Definition_Code__c)){
                                Decimal nCurrentAssetCountByPkgDefCode = (Decimal) mapActiveAssetCount.get(oi.Package_Definition_Code__c);
                                system.debug('nCurrentAssetCountByPkgDefCode' +nCurrentAssetCountByPkgDefCode);
                                if(nCurrentAssetCountByPkgDefCode > 0){
                                    // System.debug('Package_Definition_Code__c : ' + oi.Package_Definition_Code__c );
                                    // System.debug('nCurrentAssetCountByPkgDefCode : ' + nCurrentAssetCountByPkgDefCode );
                                    
                                    // System.debug('Order.NumberOfDigitalSubscriptionSold__c : ' + oi.Order.NumberOfDigitalSubscriptionSold__c );
                                    // System.debug('nB2BOrderTotalActiveSubs : ' + nB2BOrderTotalActiveSubs );
                                    
                                    if((oi.Order.NumberOfDigitalSubscriptionSold__c >= nCurrentAssetCountByPkgDefCode) && (nB2BOrderTotalActiveSubs < nCurrentAssetCountByPkgDefCode)){
                                        Decimal nCountUp = nCurrentAssetCountByPkgDefCode - nB2BOrderTotalActiveSubs;
                                        oi.NoOfActiveSubscriptionsExclBuffer__c += nCountUp;
                                        nB2BOrderTotalActiveSubs += nCountUp;
                                        nCurrentAssetCountByPkgDefCode -= nCountUp;
                                        system.debug('nCountUp' +nCountUp);
                                    }
                                    else if((oi.Order.NumberOfDigitalSubscriptionSold__c < nCurrentAssetCountByPkgDefCode) && (nB2BOrderTotalActiveSubs < oi.Order.NumberOfDigitalSubscriptionSold__c)){
                                        Decimal nCountUp = oi.Order.NumberOfDigitalSubscriptionSold__c - nB2BOrderTotalActiveSubs;
                                        oi.NoOfActiveSubscriptionsExclBuffer__c += nCountUp;
                                        nB2BOrderTotalActiveSubs += nCountUp;
                                        nCurrentAssetCountByPkgDefCode -= nCountUp;
                                        system.debug('nCountUp' +nCountUp);
                                    }
                                    mapTotalActiveSubsInB2BOrder.put(oi.OrderId, nB2BOrderTotalActiveSubs);
                                    mapActiveAssetCount.put(oi.Package_Definition_Code__c, nCurrentAssetCountByPkgDefCode);
                                }
                            }
                        }

                        update lstB2BOrderItems;
                        system.debug('lstB2BOrderItems' +lstB2BOrderItems);

                        //Reconciling NumberofDigitalSubscriptionsActive__c in B2B Orders
                        if(lstB2BOrderIds.size()>0){
                            List<Order> lstB2BOrders = [SELECT Id, NumberofDigitalSubscriptionsActive__c, TECH_TotalNumberofActiveSubscription__c FROM Order WHERE Id IN: lstB2BOrderIds];
                            system.debug('lstB2BOrders' +lstB2BOrders);
                            if(lstB2BOrders.size()>0){
                                for(Order o : lstB2BOrders){
                                    o.NumberofDigitalSubscriptionsActive__c = o.TECH_TotalNumberofActiveSubscription__c;
                                }
                                update lstB2BOrders;
                            }
                        }
                    }
                }
            }
        }


LWC JS:
import { LightningElement,track  } from 'lwc';
import recountAssets from '@salesforce/apex/B2BActiveAssetsRecountHandler.recountAssets';
export default class ReCountMechforAssetManagement extends LightningElement {
    clickedButtonLabel;
    @track b2bAccountId;
    @track b2bOrderId;
    @track error;
    handleClick(event) {
        this.clickedButtonLabel = event.target.value;
        recountAssets()
        .then(result =>{
            this.b2bAccountId = result;
            this.b2bOrderId = result;
        })
        .catch(error => {
            this.error = error;
        });
        //this.clickedButtonLabel = event.target.label;
    }
}

HTML:

<template>
    <div class="slds-m-top_small slds-m-bottom_medium">
        <!-- Brand outline variant: Identifies the primary action in a group of buttons, but has a lighter look -->
        <lightning-button variant="brand-outline" label="Recount" title="Primary action with lighter look" onclick={handleClick} class="slds-m-left_x-small"></lightning-button>
    </div>
</template>
</template>

I have a table created with lightning datatable where I get records from a query in an apex class. I added an add button where the click of the button fetches the record from me and creates a new table with the fetched record. How can I do ?
Component:
<aura:attribute name="mydata" type="Object"/>
<aura:attribute name="mycolumns" type="List"/>
<aura:handler name="init" value="{! this }" action="{! c.init }"/>

<div class="container" style="height:280px">

    <lightning:datatable style="color:blue ;font-size:12px" data="{! v.mydata }"
                         columns="{! v.mycolumns }"
                         keyField="Id"
                         hideCheckboxColumn="true"
                         />
</div>

Controller:
init: function (cmp, event, helper) {
    cmp.set('v.mycolumns', [
        { label: 'Name Number', fieldName: 'Name'},
        { label: 'Product Name', fieldName: 'Name__c', type: 'text'},
        { label: 'Weight For Single Product', fieldName: 'WeightForSingleProduct__c', type: 'number'},
        { label: 'Available Quantity', fieldName: 'AvailableQuantity__c', type: 'number'},
        { label: 'Genre', fieldName: 'GenreBook__c', type: 'text'},
          {type: "button", typeAttributes: {
            label: 'Add Cart',
            name: '',
            title: '',
            disabled: false,
            value: '',
            iconPosition: ''
        }},
        {type: "button", typeAttributes: {
            label: 'Preview Cart',
            name: '',
            title: '',
            disabled: false,
            value: '',
            iconPosition: 'l'
        }}
    ]);
    helper.getData(cmp);
}
Helper:
getData : function(cmp) {
    var action = cmp.get('c.getSearchQuery');
    action.setCallback(this, $A.getCallback(function (response) {
        var state = response.getState();
        if (state === "SUCCESS") {
            cmp.set('v.mydata', response.getReturnValue());
        } else if (state === "ERROR") {
            var errors = response.getError();
            console.error(errors);
        }
    }));
    $A.enqueueAction(action);
}


 
Hello 
 
Condition for validation:
If Opportunity Team Member is marked locked by checking a "Team Locked" checkbox on any Team Members, no more members can be added or deleted to the Opportunity Team using the "Add Opportunity Team Member" Or 'Delete" button unless addition/deletion is made by User with checkbox "Commission Admin" checked. 
 
Alternatively, the checkbox "Team Locked" can be on Opportunity. 
 
Error Message " You don't have permission to Add or Delete Team Members. Please contact Commission Admin". 

 Thanks in advance. 
Hi Team,
I have a below requirement. Lead record type field should be read only (uneditable) when:
- Lead Record type = Deal
- Lead record type  = Partner.

Please help me in acheiving this.
Thanks.
 

Hi ,
for below code, Test coverage is failed and getting erros. can you pls check below my post :

Apex classs :
User-added imageand below is my Test class :
@isTest
public class Test_PickListController {
    static testMethod void insertValues() {
        Resourse__c resource = new Resourse__c();
        resource.Name='Test1';
        resource.Job_type__c='Automation Engineer';
        resource.Type_of__c= 'Bestshore';
        resource.EngagementType__c = 'Fixed Price';
        insert resource;
        
        PickListController.getResource(resource.Id);
        
        Skill_Management__c skillMgt = new Skill_Management__c();
        skillMgt.Name='Java' ;
        skillMgt.Skill_Category__c='Java' ;
        skillMgt.Skills__c='Java' ;
        insert skillMgt;
        
        Skill_Management__c skillUpdate = [select Id,Name,Skill_Category__c,Skills__c from Skill_Management__c
                                           where Id =:skillMgt.Id limit 1];
              
        Skill__c ac = new Skill__c();
       /* ac.Resource__c = resource.Id;
        ac.Skill_Management__c = skillUpdate.id ;        
        insert ac;*/

        PickListController pc = new PickListController();
        
        PickListController.insertValues(ac,skillMgt.Id,resource.Id);
          
    }
}

When i try to execute the Test class getting below and its coverage only 35% .
Class.PickListController.insertValues: line 29, column 1
Class.Test_PickListController.insertValues: line 29, column 1.


can
 you pls check and help on this.
Thanks

  • March 21, 2022
  • Like
  • 0
I Have QuickAction Button In Quick Action I'm using LWC Component
The Requirement Is it Showing On Record Detail Page in Lightning Experience But Not Showing On Community Site 
i have 4 checkbox field on an object and 1 pickilist field 



1>    if all four checkbox is checked picklist isequal to all active
2>    if any three checkbox is checked picklist isequal to review
3>    if any two checkbox is checked picklist isequal to approved
4>     if one or none checkbox is checked picklist isequal to rejected
global class BatchOnContact implements Database.Batchable<sObject>, Database.Stateful{
    
    global Database.QueryLocator start(Database.BatchableContext bc){     
        
        return Database.getQueryLocator('select Id, name, StageName from opportunity where StageName=\'Closed Won\'');
        
    }
    global void execute(Database.BatchableContext bc, List<opportunity> Opplist){
        List<OpportunityLineItem> OList = new List<OpportunityLineItem>();
        List<Product2> prolist= [SELECT Id from Product2 Limit 10];
              For(opportunity opp:  Opplist){
            for(Integer i=0; i<10; i++){
               OpportunityLineItem op= new OpportunityLineItem(opportunityId=opp.id, Product2Id=prolist.get(i).id,Quantity =1, TotalPrice=1000);
                OList.add(op);                                                               
            }  opp.Pricebook2Id='0066F00000yUeDpQAK';            
        }update opplist;
        insert OList;      
    }
 global void finish(Database.BatchableContext bc){ }
}
Hi, 
I'm writing some Apex code and I need to query a custom object's ID as in the URL below:
https://telfed--pras.lightning.force.com/lightning/setup/ObjectManager/01I3q0000026FS5/Details/view
What I have is the ID of a record of that type, and I know how to get the type's name, for example by doing: 
recordId.getSobjectType().getDescribe().getName()
However, I can't seem to find a function that will get me the ID of type. 

I want the ID because I want to query the correct Custom Metadata Record that corresponds to this type via an Entity Definition Relationship field. I can see in the Query Editor Results that the value stored in the record is not the type's name, but the type's ID. So I would like to get the ID so that I can construct the correct where clause. 
SELECT FIELDS(ALL) FROM Incoming_Contact_Data__mdt LIMIT 200
User-added imageAny help would be appreciated!
 
  • May 18, 2022
  • Like
  • 0
Hi All,

We have a requirement to calculate all child accounts amount field and show it on the parent account.

We have look up relationship so we need to write a trigger for this. Can I someone help on this requirement??

I have got a sample code in google however it is not working please check

Amount field 
__________________________________________________________
trigger ParentAccUpdate on Account  (after insert,after update, after delete,after undelete) {
    if(checkRecursive.runOnce())
        
    {
        
        
        List<id> ParentIds = new List<id>();
        if(Trigger.isInsert || Trigger.isUndelete || Trigger.isupdate){
            For(Account Acc: Trigger.new){
                ParentIds.add(Acc.parentid);
            }
        }
        if(Trigger.isDelete){
            For(Account Acc: Trigger.old){
                ParentIds.add(Acc.parentid);
            }
        }
        List<account> accountToUpdate = new List<account>();
        decimal sum = 0;
        
        if(Trigger.isInsert || Trigger.isUndelete || Trigger.isupdate || trigger.isdelete){
            For(account q : [SELECT Total_Revenue_2021__c ,X2020_Revenue__c, (SELECT id,X2020_Revenue__c,Total_Revenue_2021__c FROM  ChildAccounts) FROM account WHERE id =: ParentIds]){ 
                sum = 0;
                
                for(Account p : q.ChildAccounts){
                    
                    sum = sum + (q.X2020_Revenue__c!=NULL ? q.X2020_Revenue__c : 0);//Use the fields you want here to get the sum and include those                     fields in above query eg is given below from my understanding
                                   

                    q.Total_Revenue_2021__c = sum;
                    
                    
                }
                accountToUpdate.add(q);
            }
            try{
                update accountToUpdate ;
            }
            Catch(Exception e){
                System.debug('Exception :'+e.getMessage());
            }
        }
    }   
}

 
How to display opportunity associated all products in trigger.
Here is my code:
trigger opportunityProductCount on Product2 (after insert, after update, after delete, after undelete) {
    set<Id> setIds = new set<Id>();
    list<Opportunity> opplist= new list<Opportunity>();
    if(trigger.isafter){
        if(trigger.isinsert|| trigger.isUpdate|| trigger.isUndelete){
            for(Product2 p: trigger.new){
                setIds.add(p.OpportunityId);
            }
        }
        if(trigger.isupdate|| trigger.isdelete){
            for(Product2 po:trigger.old){
                setIds.add(po.OpportunityId);
            }
        }
    }
    List<Opportunity> oplist = [Select Id,Name,Number_of_Product__c,(select id,name from Products2)from Opportunity where Id in:setIds];
    system.debug('show products'+ oplist);
    for (Opportunity opp: oplist){
        Integer count = opp.Products2.size();
        opp.Number_of_Product__c = count;
        opplist.add(opp);
        
    }
    update opplist;

}
Can anybody help to out of this que how to associated record and count display in oppoprtunity in trigger.I just started to learn development.

I have a situation where I have two objects Opportunity and a custom Object Contract__c. In both the object I have a field called reference_name__c. Now the situation is that I have to query the objects and return the reference_name__c values. If Opportunity has reference_name__c value and Contract__c don't have reference_name__c value return value. If Opportunity has no reference_name__c value and Contract__c has reference_name__c value then return the value. How could I write the query? The query was written by me just satisfies the 1st condition. Please help me with the query.


Select Id, reference_name__c,(Select ID, reference_name__c from Contract__r where reference_name__c !=null Limit 10) from opportunity where AccountId != null AND reference_name__c != null AND Owner.AccountId =loggedInUser.Contact.AccountId limit 10

How to achieve this with helper. 
component:
<aura:component controller="AccountSearch" implements="flexipage:availableForRecordHome,force:hasRecordId" access="global" >
    <!--button-->
    <aura:attribute name="searchkeyword" type="string" description="used to store user search"/>
    <aura:attribute name="TotalnoofRecords" type="integer" default="0" description="used to display the  no of records"/>
    <aura:attribute name="searchResult" type="List" description="used to store and display result"/>
    <aura:attribute name="message" type="boolean" description="used to  display message"/>
    <aura:attribute name="AccList" type="Account[]" />
    <aura:attribute name="columns" type="List"/>
    <!--aura:handler name="init" value="{!this}" action="{!c.fetchAccount}" /-->
    <lightning:button variant="brand" label="search" iconName="utility:search" onclick="{!c.Search}"/>
    <lightning:input value ="{!v.searchkeyword}"
                keyField="True"
                placeholder="search accounts.."
                label="AccountName"/>
      
    </aura:component>
controller:
({
     Search:function(component,event,helper) {
         helper.Searchhelper(component,event,helper);
     }
     })
Helper:
({
    SearchHelper : function(component,event) {
        
       component.set('v.columns', [
          {label:'AccountName', fieldName:'Name', type: 'text'},
          {label:'Type', fieldName:'Type', type: 'text'},
          {label:'Industry', fieldName:'Industry', type: 'text'},
          {label:'Phone', fieldName:'Phone', type: 'Phone'},
          {label:'Fax', fieldName:'Fax', type: 'text'}]);

           
        //Step1: Get the Apex method that should be invoked
        
         var action = component.get("c.fetchAccount");
         
       
         //step2: set the parameters
         action.setParams({ 
           'searchword':component.get("v.searchkeyword")
           
         });
        //Step4: handle the response from apex class method/Server side method
        action.setCallback(this, function(response){
            var storeResponse = response.getReturnValue();
            if (storeResponse.length==0){
                component.set("v.message",true);
            }
            else{
                component.set("v.message",false);
            }

           component.set("v.TotalnoofRecords",storeResponse.length);
            component.set("v.searchResult",storeResponse);
           
        });
        //Step3: Enqueue action/ApexMethod to be executed 
        $A.enqueueAction(action);
     

       
    }
})

Apex:
public class AccountSearch {
@AuraEnabled
    public static List<Account> fetchAccount(string searchword){
        string Searchkey = '%'+searchword+'%';
        List<Account> AccList = [select id,Name,Type,Industry,Phone,Fax from Account where Name=:Searchkey LIMIT 500];
        return AccList;
}
  
}
write a wrapper class to display accounts and its related contacts in a single lightning table using lwc??
Hello, can you please help me a test class for this class.
I tried to write one but I always have 0% coverage.
Any help or suggestions please.

public without sharing class SendEmaile { 
    public class Params { 
        @InvocableVariable 
        public String template; 
        @InvocableVariable
        public String orgWideEmailAddress; 
        @InvocableVariable 
        public String toAddress; 
        @InvocableVariable 
        public Id contactId; 
        @InvocableVariable
        public Id recordId; 
        @InvocableVariable
        public Id relatedId; 
        @InvocableVariable
        public Boolean sendAttachment; 
    } 

    @InvocableMethod 
    public static void sendEmail(List<Params> requests) { 
        try { 
            Params request = (requests.size() == 1) ? requests[0] : null; 
            if (request != null) { 
                // Get Content Document Ids 
                Set<String> contentDocumentIds = new Set<String>(); 
                List<ContentDocumentLink> cdls = [SELECT ContentDocumentId FROM ContentDocumentLink WHERE LinkedEntityId = :request.recordId]; 
                for (ContentDocumentLink doc : cdls) { 
                    contentDocumentIds.add(doc.ContentDocumentId); 
                } 
                EK_Parameter__mdt noReplyEmail = EK_Parameter__mdt.getInstance('Facture');
               // Get Email Template 
                Id templateId = [SELECT Id FROM EmailTemplate WHERE DeveloperName = 'Interv'].Id; 
                // New email message 
                Messaging.SingleEmailMessage mail = Messaging.renderStoredEmailTemplate(templateId, null, request.relatedId); 
                // Set OrgWideEmailAddress Id 
                Id orgWideEmailAddressId = [SELECT Id FROM OrgWideEmailAddress WHERE Address =: noReplyEmail.Value__c LIMIT 1].Id; 
                if (orgWideEmailAddressId != null) { 
                    mail.setOrgWideEmailAddressId(orgWideEmailAddressId); 
                } 
                // Set Email Properties 
                mail.toAddresses = new String[]{request.toAddress}; 
                mail.setTargetObjectId(request.contactId); 
                mail.setWhatId(request.relatedId); 
                mail.setTreatTargetObjectAsRecipient(false); 
                mail.setTreatBodiesAsTemplate(false); 
                // Set Email Attachments 
                if (request.sendAttachment == true) { 
                    List<ContentVersion> contentVersionFile = [SELECT VersionData, Title, FileType FROM ContentVersion WHERE ContentDocumentId IN :contentDocumentIds AND IsLatest = true]; 
                    List<Messaging.EmailFileAttachment> emailFileAttachments = new List<Messaging.EmailFileAttachment>(); 
                    for (ContentVersion cv : contentVersionFile) { 
                        Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment(); 
                        efa.setFileName(cv.Title + '.' + cv.FileType); 
                        efa.setBody(cv.VersionData); 
                        emailFileAttachments.add(efa); 
                    } 
                    if (!emailFileAttachments.isEmpty()) { 
                        mail.setFileAttachments(emailFileAttachments); 
                    } 
                } 
                // Send Email 
                Messaging.SingleEmailMessage[] messages = new List<Messaging.SingleEmailMessage>{mail}; 
                if (!Test.isRunningTest()) { 
                    Messaging.SendEmailResult[] results = Messaging.sendEmail(messages); 
                    if (results[0].success) { 
                        System.debug('The email was sent successfully.'); 
                    } else { 
                        System.debug('The email failed to send: ' + results[0].errors[0].message); 
                    } 
                } 
            } 
        } catch (Exception e) { 
            throw new SendEmailException(e.getMessage(), e); 
        } 
    } 
    /** 
     * EXCEPTIONS 
     */ 
    public class SendEmailException extends Exception { } 
}
  • April 29, 2022
  • Like
  • 0
 public static void mapBirthdayFieldsOnEducationSession(map<Id,Lead> newLeadMap, map<Id,Lead> oldLeadMap){
        map<Id,Lead> newConvertedIdMap = new map<Id,Lead>();
        for(Lead listLead : newLeadMap.values()){
            if(listLead.isConverted && listLead.ConvertedAccountId !=null && listLead.HealthCloudGA__BirthDate__c !=null){
                newConvertedIdMap.put(listLead.ConvertedAccountId,listLead );
            } 
        }
        if(!newConvertedIdMap.isEmpty()){
            List<Account> listAccount = [SELECT Id , PersonBirthdate FROM Account WHERE Id IN : newConvertedIdMap.keySet()];
            for(Account account : listAccount){
                Account.PersonBirthdate = newConvertedIdMap.get(account.Id).HealthCloudGA__BirthDate__c;
            }
            update listAccount ;
        }
    }
Hi Guys,
Here is the batch class, how to write test coverage for batch class

public class ServiceBatchable implements Database.Batchable<sObject>, Database.Stateful {
    private Id lastJobId = null;
    private Id serRecTypeId = null;
    public ServiceBatchable () {
    }
  public Database.QueryLoSeror start(Database.BatchableContext BC) {
        Integer limitInt = 10000;
        List<AsyncApexJob> aajList = new List<AsyncApexJob>();
                                if(lastJobId!=null && lastJobId!=BC.getJobId()) {
             aajList.addAll([SELECT Id, Status, CompletedDate FROM AsyncApexJob WHERE ID =: lastJobId and JobType!='BatchApexWorker' and Status not in ('Aborted','Completed','Failed')]);
        }
                                if(lastJobId==null || aajList.isEmpty()) {
            lastJobId = BC.getJobId();
            if(serRecTypeId ==null) {
                RecordType rt = opportunityRTMap.get('Service Record');
                if(rt!=null) {
                   serRecTypeId = rt.Id;
                }
            }
        }
        if(lastJobId!=BC.getJobId()) {
            limitInt = 0;
            System.debug('ServiceBatchable: Previous Job alive still - aborting '+BC.getJobId());
        }
return Database.getQueryLocator([
            select id,CurrencyIsoCode,StageName,Ser_Currency_Code__c,Ser_Line_Item_ID__c,Ser_Duration__c,Ser_Start_Date__c,Ser_Monthly_Amount__c,SER_Updated__c
            from Opportunity where
             ((StageName='1 - Lead' and Ser_Line_Item_ID__c != null) or (StageName!='1 - Lead')) and
             SER_Updated__c = true and
             External_Id__c != null and
             RecordTypeId=: serRecTypeId and
             isDeleted=FALSE
             limit :limitInt
            ]);
    }
 public void execute(Database.BatchableContext BC, List<Opportunity> scope){
        Map<Id,OpportunityLineItem> opportunityLineItemMap = new Map<Id,OpportunityLineItem>();
        for(OpportunityLineItem oli : [select id,OpportunityId,X2022_Revenue__c,X2023_Revenue__c,Wave__c,UnitPrice,ServiceDate,Seats__c,Quantity,PricebookEntryId,Language__c,FTE__c,Delivery_LoSerion__c from OpportunityLineItem where OpportunityId in :scope]) {
            opportunityLineItemMap.put(oli.Id,oli);
        }
        List<OpportunityLineItem> removeOpportunityLineItemList = new List<OpportunityLineItem>();
        List<Opportunity> newScope = new List<Opportunity>();
        List<Opportunity> alteredScope = new List<Opportunity>();
        for(Opportunity o: scope) {
            if(o.StageName=='1 - Lead' && opportunityLineItemMap.containsKey(o.Ser_Line_Item_ID__c)) {
                removeOpportunityLineItemList.add(opportunityLineItemMap.remove(o.Ser_Line_Item_ID__c));
                o.Ser_Line_Item_ID__c = null;
                o.CurrencyIsoCode=o.Ser_Currency_Code__c;
                alteredScope.add(o);
            } else if(o.StageName!='1 - Lead' && o.CurrencyIsoCode!=o.Ser_Currency_Code__c) {
                if(opportunityLineItemMap.containsKey(o.Ser_Line_Item_ID__c)) {
                              removeOpportunityLineItemList.add(opportunityLineItemMap.remove(o.Ser_Line_Item_ID__c));
                                o.Ser_Line_Item_ID__c = null;
               }
                o.CurrencyIsoCode=o.Ser_Currency_Code__c;
                alteredScope.add(o);
                newScope.add(o);
            } else if(o.StageName!='1 - Lead' && opportunityLineItemMap.containsKey(o.Ser_Line_Item_ID__c)){
                newScope.add(o);
            } else if(o.StageName!='1 - Lead' && !opportunityLineItemMap.containsKey(o.Ser_Line_Item_ID__c)){
                o.CurrencyIsoCode=o.Ser_Currency_Code__c;
                newScope.add(o);
            }
        }
        // Delete those marked as invalid
        delete removeOpportunityLineItemList;
        // Remove old reference after we delete
        update alteredScope;
       
        // Opportunity map.
                                Map<Id,Opportunity> ServiceOpportunityMap = new Map<Id,Opportunity>(newScope);
        List<OpportunityLineItem> upsertOpportunityLineItemID = new List<OpportunityLineItem>();

        // Populate ServicePriceBookEntryMap with map of ISO code to ID
                                Map<String,PricebookEntry> ServicePriceBookEntryMap = new Map<String,PricebookEntry>();
        for(PricebookEntry pbe : [select id, CurrencyisoCode from PricebookEntry where ProductCode = 'Ser']) {
            if(!ServicePriceBookEntryMap.containsKey(pbe.CurrencyIsoCode)) {
               ServicePriceBookEntryMap.put(pbe.CurrencyisoCode,pbe);
            }
        }
for(Opportunity o: newScope) {
            Id pricebookEntryId = null;
            if(ServicePriceBookEntryMap.containsKey(o.Ser_Currency_Code__c)) {
                pricebookEntryId = ServicePriceBookEntryMap.get(o.Ser_Currency_Code__c).Id;
            }
            OpportunityLineItem oli;
            // get old lineitem
            if(opportunityLineItemMap.containsKey(o.Ser_Line_Item_ID__c)) {
                oli = opportunityLineItemMap.get(o.Ser_Line_Item_ID__c);
            }
            // if none found create new one and setup defaults
            if(oli==null) {
                oli = new OpportunityLineItem();
                oli.OpportunityId = o.Id;
                oli.PricebookEntryId = pricebookEntryId;
                oli.Seats__c = 0;
                oli.Wave__c = '1';
                oli.X2023_Revenue__c = 0;
                oli.X2022_Revenue__c = 0;
                oli.Delivery_LoSerion__c = 'Other';
                oli.FTE__c = 0;
                oli.Language__c = 'English';
            }
            // New or Update copy these fields
            oli.Quantity = Math.max(1,o.Ser_Duration__c);
            oli.ServiceDate = o.Ser_Start_Date__c;
            oli.UnitPrice = o.Ser_Monthly_Amount__c;
            upsertOpportunityLineItemID.add(oli);
        }
       if(!upsertOpportunityLineItemID.isEmpty()) {
            upsert upsertOpportunityLineItemID;
            for(OpportunityLineItem oli : upsertOpportunityLineItemID) {
                Opportunity o = ServiceOpportunityMap.get(oli.OpportunityId);
                o.Ser_Line_Item_ID__c = oli.Id;
                o.SER_Updated__c = false;
            }
            update newScope;
        }
    }
public void finish(Database.BatchableContext BC){       
        if(BC.getJobId()==lastJobId) {
            lastJobId=null;
        }
                }   
private Map<String,RecordType> opportunityRTMap = getRecordTypeMap('Opportunity');
private List<RecordType> getRecordTypes(String[] objects) {
        return [SELECT Id, name, SObjectType FROM RecordType WHERE SObjectType in :objects order by SobjectType, Name];
    }
private Map<String,RecordType> getRecordTypeMap(String objectName) {
        Map<String,RecordType> target = new Map<String,RecordType>();
        for(RecordType r : getRecordTypes(new String[] {objectName})) {
            target.put(r.name,r);
        }
        return target;
    }
   private Map<String,RecordType> getRecordTypeMap(String[] objects) {
        Map<String,RecordType> target = new Map<String,RecordType>();
        for(RecordType r : getRecordTypes(objects)) {
            target.put(r.SObjectType+'.'+r.name,r);
        }
        return target;
    }
     public static ID execute() {
        try {
            return System.scheduleBatch(new ServiceBatchable(),'ServiceBatchable',1,200);
        } Catch (Exception ex) {
            // We don't care that another is setup
            System.debug(ex);
        }
        return null;
    }
}

 
HI i have a requirement to do the following

Once Case Owner is changed from queue to user, Case Status should automatically change to In Progress
• Once status is In Progress, user can only update this field to either Closed, Duplicate, or Escalated

Any idea how to acomplished this ?
Please anbody help me to write handler class??

trigger OppValidation on Opportunity (before insert,before update) {
    
    Id profileId= userinfo.getProfileId();
    String profileName=[Select Id,Name from Profile where Id=:profileId].Name;
    if(Trigger.isupdate){
        for(Opportunity opp:Trigger.new){
            opportunity oldoppy= Trigger.oldmap.get(opp.id);
            
            if(opp.Active__c ==false && oldoppy.Active__c==True && opp.stagename!='Closed Won' && profileName!='System Administrator'){
                opp.adderror('You do not have the access to perform this operation. Kindly contact your system administrator');
            }
        }
        
    }
    
    if(Trigger.isinsert){
        for(Opportunity opp:Trigger.new){
            
            if(opp.Active__c ==false && opp.stagename!='Closed Won' && profileName!='System Administrator'){
                opp.adderror('You do not have the access to perform this operation. Kindly contact your system administrator');
            }
        }
    }
}
Here is my code,  I was not able to find the error 
-----------------Component ---------------------------------------------------

<aura:component controller="QuickOpportunityController"
    implements="force:lightningQuickActionWithoutHeader,force:hasRecordId">

    <aura:attribute name="account" type="Account" />
    <aura:attribute name="newOpportunity" type="Opportunity"
        default="{ 'sobjectType': 'Opportunity' }" /> <!-- default to empty record -->
    
    <aura:attribute name="options" 
                  type="list" 
      default="[
                {'label': 'Discovery', 'value': 'Discovery'},
                {'label': 'Decision Maker Meeting', 'value': 'Decision Maker Meeting'},
                {'label': 'Custom Proposal', 'value': 'Custom Proposal'},
                {'label': 'Verbal Agreement', 'value': 'Verbal Agreement'},
                {'label': 'Signed Contract', 'value': 'Signed Contract'},
                 {'label': 'Closed-Installed', 'value': 'Closed-Installed'},
                 {'label': 'Closed-Lost', 'value': 'Closed-Lost'},
                {'label': 'Closed-No Decision', 'value': 'Closed-No Decision'},
                {'label': 'Closed – Duplicate', 'value': 'Closed – Duplicate'},
                {'label': 'Closed - Not Awarded', 'value': 'Closed - Not Awarded'}
               ]" 
           description="Below attribute will define picklist values if you want dynamic values then you can query that from the database and set those values"/>
     
    <aura:attribute name="options2" 
                  type="list" 
      default="[
                {'label': 'Coin and Card', 'value': 'Coin and Card'},
                {'label': 'Coin Only', 'value': 'Coin Only'},
                {'label': 'Card Only', 'value': 'Card Only'},
                 {'label': 'Change Point Only', 'value': 'Change Point Only'},
                 {'label': 'No Change or N/A', 'value': 'No Change or N/A'},
                {'label': 'Non-Vend', 'value': 'Non-Vend'},
                {'label': 'In-Unit BOLB', 'value': 'In-Unit BOLB'},
                {'label': 'In-Unit Comm Direct', 'value': 'In-Unit Comm Direct'}
               ]" 
           />
    <aura:attribute name="options3" 
                  type="list" 
      default="[               
                 {'label': 'Straight Percent', 'value': 'Straight Percent'},
                {'label': 'Sliding Scale', 'value': 'Sliding Scale'},
               {'label': 'Flat Amount', 'value': 'Flat Amount'}
               ]" 
           />
    
    <aura:attribute name="options4" 
                  type="list" 
      default="[                
                 {'label': 'None', 'value': 'None'},
                {'label': '50%', 'value': '50%'},
               {'label': '100%', 'value': '100%'}
               ]" 
           />
    
    <aura:attribute name="options1" 
                  type="list" 
      default="[
                
                 {'label': 'New', 'value': 'New'},
                {'label': 'Renewal', 'value': 'Renewal'}
               ]" 
           />
  
    
    <aura:handler name="init" value="{!this}" action="{!c.doInit}" />

    <!-- Display a header with details about the account -->
    <div class="slds-page-header" role="banner">
        <p class="slds-text-heading_label">{!v.account.Name}</p>
        <h1 class="slds-page-header__title slds-m-right_small
            slds-truncate slds-align-left">Create New Opportunity</h1>
    </div>

    <!-- Display the new opportunity form -->
     <lightning:input aura:id="opportunityField" name="Name" label="Name"
                      value="{!v.newOpportunity.Name}" required="true"/>
     <lightning:input aura:id="opportunityField" name="RecordType" label="Record Type"
                      value="Air IRR" required="true"/>
    
     <lightning:input aura:id="opportunityField" name="Lease_Term_Months__c" label="Proposed Lease Term (mos)"
                      value="{!v.newOpportunity.Lease_Term_Months__c}" required="true"/>
    <lightning:input aura:id="opportunityField" name="CSC_Pay_Value_Recovery_Method__c" label="CSC Pay Value Recovery Method"
                      value="None" required="true"/>     
    
    <lightning:input aura:id="opportunityField" name="Capital_Date__c" label="Capital Date" type="date"
                     value="{!v.newOpportunity.Capital_Date__c}" />
    
    <lightning:input aura:id="opportunityField" name="CloseDate" label="Close Date" type="date"
                     value="{!v.newOpportunity.CloseDate}" />
    
    <lightning:combobox aura:id="opportunityField" name="Admin_Fee__c" label="Admin Fee" value="{!v.newOpportunity.Admin_Fee__c}" placeholder="Select" options= "{!v.options4}" />
    
    
    <lightning:combobox aura:id="opportunityField" name="Commission_Equation_Type__c" label="Commission Equation Type" value="{!v.newOpportunity.Commission_Equation_Type__c}" placeholder="Select" options= "{!v.options3}" />
    
     <lightning:combobox aura:id="opportunityField" name="StageName" label="Stage Name" value="{!v.newOpportunity.StageName}" placeholder="Select Stage" options= "{!v.options}" />
    
    <lightning:combobox aura:id="opportunityField" name="Type" label="Type"
                     value="{!v.newOpportunity.Type}" placeholder="Select type" required="true" options= "{!v.options1}" />
    
    <lightning:combobox aura:id="opportunityField" name="Sub_Type__c" label="Sub-Type" value="!v.newOpportunity.Sub_Type__c" placeholder="Select Sub-type" options= "{!v.options2}" />
        
    <lightning:button label="Cancel" onclick="{!c.handleCancel}" class="slds-m-top_medium" />
    <lightning:button label="Save Opportunity" onclick="{!c.handleSaveOpportunity}"
               variant="brand" class="slds-m-top_medium"/>
    
</aura:component>



-------------Controller -------------------------------------------------------------

public with sharing class QuickOpportunityController {

    @AuraEnabled
    public static Account getAccount(Id accountId) {
        // Perform isAccessible() checks here
        return [SELECT Name, BillingCity, BillingState FROM Account WHERE Id = :accountId];
    }
    
    @AuraEnabled
    public static Opportunity saveOpportunityWithAccount(Opportunity opportunity, Id accountId) {
        // Perform isAccessible() and isUpdateable() checks here
        opportunity.AccountId = accountId;
        insert opportunity;
        return opportunity;
    }

}


--------------------------------Controller JS file ----------------------------------

({
    doInit : function(component, event, helper) {

        // Prepare the action to load account record
        var action = component.get("c.getAccount");
        action.setParams({"accountId": component.get("v.recordId")});

        // Configure response handler
        action.setCallback(this, function(response) {
            var state = response.getState();
            if(state === "SUCCESS") {
                component.set("v.account", response.getReturnValue());
            } else {
                console.log('Problem getting account, response state: ' + state);
            }
        });
        $A.enqueueAction(action);
    },

    handleSaveOpportunity: function(component, event, helper) {
        if(helper.validateOpportunityForm(component)) {
            
            // Prepare the action to create the new opportunity
            var saveOpportunityAction = component.get("c.saveOpportunityWithAccount");
            saveOpportunityAction.setParams({
                "opportunity": component.get("v.newOpportunity"),
                "accountId": component.get("v.recordId")
            });

            // Configure the response handler for the action
            saveOpportunityAction.setCallback(this, function(response) {
                var state = response.getState();
                if(state === "SUCCESS") {

                    // Prepare a toast UI message
                    var resultsToast = $A.get("e.force:showToast");
                    resultsToast.setParams({
                        "title": "Opportunity Saved",
                        "message": "The new opportunity was created."
                    });

                    // Update the UI: close panel, show toast, refresh account page
                    $A.get("e.force:closeQuickAction").fire();
                    resultsToast.fire();
                    $A.get("e.force:refreshView").fire();
                }
                else if (state === "ERROR") {
                    system.debug('Problem saving opportunity, response state: ' + state);
                }
                else {
                    console.log('Unknown problem, response state: ' + state);
                }
            });

            // Send the request to create the new opportunity
            $A.enqueueAction(saveOpportunityAction);
        }
        
    },

    handleCancel: function(component, event, helper) {
        $A.get("e.force:closeQuickAction").fire();
    }
})


---------------------------------Helper Js -------------------------------------------

({
    validateOpportunityForm: function(component) {
        var validOpportunity = true;

        // Show error messages if required fields are blank
        var allValid = component.find('opportunityField').reduce(function (validFields, inputCmp) {
            inputCmp.showHelpMessageIfInvalid();
            return validFields && inputCmp.get('v.validity').valid;
        }, true);

        if (allValid) {
            // Verify we have an account to attach it to
            var account = component.get("v.account");
            if($A.util.isEmpty(account)) {
                validOpportunity = false;
                console.log("Quick action context doesn't have a valid account.");
            }
        }

        return(validOpportunity);
    }
})
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??
 

Hi Everyone!

I want a list of account using Lightning-datatable. But it is not displaying the list of accounts.
HTML:

<template>
    <lightning-card title="t">
        <template if:true={accList}>
    <lightning-datatable
    key-field="Id"
    data={data}
    columns={columns}>
    </lightning-datatable>
    </template>
    <template if:true={error}>
        {error}
    </template>
</lightning-card>
</template>

JS:

import { LightningElement ,api, wire, track} from 'lwc';
import getAccountList from '@salesforce/apex/AccountHelper.getAccountList';
export default class Test extends LightningElement {
    @track columns = [{
            label: 'Account name',
            fieldName: 'Name',
            type: 'text',
            sortable: true
        },
        {
            label: 'Type',
            fieldName: 'Type',
            type: 'text',
            sortable: true
        },
      
    ];
 
    @track error;
    @track accList ;
    @wire(getAccountList)
    wiredAccounts({
        error,
        data
    }) {
        if (data) {
            this.accList = data;
            alert(JSON.stringify(accList));
            alert(JSON.stringify(data));
        } else if (error) {
            this.error = error;
        }
    }
}

Apex Class: 

public with sharing class AccountHelper {
    @AuraEnabled(cacheable=true)
    public static List<Account> getAccountList() {
        return [SELECT Id, Name, Type, Rating,
                Phone, Website, AnnualRevenue
            FROM Account LIMIT 10];
    }
}

xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>50.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        
            <target>lightning__AppPage</target>
            <target>lightning__RecordPage</target>
            <target>lightning__HomePage</target>
        
    </targets>
</LightningComponentBundle>

Output: 

User-added image

I want the list of accounts.

Thank you in Advance!

Hi,
I have created a drop down menu in lightning web component. But, I want a pop up will appear on click of a menu item. 
I tried this for pop up, But it is not working. On click of a "Rename " Menu item . A pop up will be shown.

button.html

<template>
    <div class="slds-p-around_medium lgc-bg">
        {selectedItemValue}
        {ready}
        <lightning-card title="Drop Down">
            <lightning-button-menu alternative-text="Show menu" variant="border-filled" onselect={handleOnselect}>
                {selectedItemValue}
                <lightning-menu-item value="openinsharepoint" label="Open in SharePoint" prefix-icon-name="utility:new_window"
                    href="#"
                    target="_blank">
                </lightning-menu-item>
                <lightning-menu-item value="rename" label="Rename" prefix-icon-name="utility:edit">
                    <template if:true={ready}>
                        <section role="dialog" tabindex="-1" class="slds-modal slds-fade-in-open slds-modal_small"
                            aria-labelledby="modal-heading-01" aria-modal="true" aria-hidden="true"
                            aria-describedby="modal-content-id-1">
                            <div class="slds-modal__container">
                                <!-- Modal/Popup Box LWC header here -->
                                <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>
                                        <span class="slds-assistive-text">Close</span>
                                    </button>
                                    <h2 id="modal-heading-01" class="slds-text-heading_medium slds-hyphenate">Rename LWC Setup.docx</h2>
                                </header>
                                <!-- Modal/Popup Box LWC body starts here -->
                                <div class="slds-modal__content slds-p-around_medium" id="modal-content-id-1">
                                    <lightning-input type="text" name="folder_name" label="Rename" placeholder="Enter new item name">
                                    </lightning-input>
                                </div>
                                <!-- Modal/Popup Box LWC footer starts here -->
                                <footer class="slds-modal__footer">
                                    <button class="slds-button slds-button_neutral" onclick={closeModal} title="Cancel">Cancel</button>
                                    <button class="slds-button slds-button_brand" onclick={submitDetails} title="Create">Create</button>
                                </footer>
                            </div>
                        </section>
                        <div class="slds-backdrop slds-backdrop_open"></div>
                    </template>
                </lightning-menu-item>
                <lightning-menu-item value="download" label="Download" prefix-icon-name="utility:download">
                </lightning-menu-item>
                <div class="slds-has-divider_top-space" role="separator">
                    <lightning-menu-item value="delete" label="Delet" prefix-icon-name="utility:close"></lightning-menu-item>
                </div>
            </lightning-button-menu>
        </lightning-card>
    </div>
</template>

button.js

import { LightningElement, track } from 'lwc';
export default class ButtonMenuOnselect extends LightningElement {
    @track selectedItemValue;
    @track ready;
    handleOnselect(event) {
        this.selectedItemValue = event.detail.value;
        if(this.selectedItemValue == "rename")
        {
        alert("ready");
        this.ready = true;
        alert("false");
        }
        
    }
}

 

i have 3 fields 
field 1- mr
field 2- bean
in the field 3 i have to show 'mr bean '
basically i have to show the 2 fields value in the 3rd field