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


  • Chatter
    Feed
  • 307
    Best Answers
  • 0
    Likes Received
  • 8
    Likes Given
  • 3
    Questions
  • 1239
    Replies
Develop a trigger that sends an email notification to the account owner when a high-priority case is created or updated.

I have written the below code but email is not getting fired 

public class CaseEmailNotificationHandler {
    public static void sendEmailNotifications(List<Case> casesToUpdate) {
        List<Messaging.SingleEmailMessage> emailMessages = new List<Messaging.SingleEmailMessage>();
 
        // Collect Account Owner Ids for high-priority cases and fetch User information
        Map<Id, User> accountOwners = new Map<Id, User>();
        
        for (Case updatedCase : casesToUpdate) {
            if (updatedCase.Priority == 'High') {
                Id ownerId = updatedCase.Account.OwnerId;
                
                // Check if the ownerId has not been processed already
                if (!accountOwners.containsKey(ownerId)) {
                    List<User> owners = [SELECT Id, Name, Email FROM User WHERE Id = :ownerId LIMIT 1];
                    if (!owners.isEmpty()) {
                        accountOwners.put(ownerId, owners[0]);
                    } else {
                        System.debug('No User found for ownerId: ' + ownerId);
                    }
                }
 
                User accountOwner = accountOwners.get(ownerId);

                if (accountOwner != null && !String.isBlank(accountOwner.Email)) {
                    // Create email message
                    Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
                    email.setSubject('High-Priority Case Notification');
                    email.setHtmlBody('<p>Hello, ' + accountOwner.Name + ',</p>' +
                                      '<p>A high-priority case has been created or updated. Please review the details.</p>' +
                                      '<p>Case Number: ' + updatedCase.CaseNumber + '</p>' +
                                      '<p>Case Subject: ' + updatedCase.Subject + '</p>' +
                                      '<p>Priority: ' + updatedCase.Priority + '</p>' +
                                      '<p>Thank you!</p>');
                    email.setTargetObjectId(accountOwner.Id);
                    email.setSaveAsActivity(false);
                    emailMessages.add(email);
                } else {
                    System.debug('Email not sent due to missing or invalid recipient for case Id: ' + updatedCase.Id);
                }
            }
        }
         
        if (!emailMessages.isEmpty()) {
            List<Messaging.SendEmailResult> sendResults = Messaging.sendEmail(emailMessages);
            for (Messaging.SendEmailResult result : sendResults) {
                if (!result.isSuccess()) {
                    System.debug('Failed to send email: ' + result.getErrors()[0].getMessage());
                }
            }
        }
    }
}
trigger CaseEmailNotificationTrigger on Case (after insert, after update) {
    if (Trigger.isAfter && (Trigger.isInsert || Trigger.isUpdate)) {
        CaseEmailNotificationHandler.sendEmailNotifications(Trigger.new);
    }
}
I have a class and I am trying to write a test class for it here is the code:
global class BatchMassDeleteDraftCaseRecs Implements Database.batchable<sobject>{
    
    global BatchMassDeleteDraftCaseRecs(){
         
    }
    global Database.QueryLocator start(Database.BatchableContext BC){
        
        String statusDraft = 'Draft';
        String statusNew = 'New';
        String statusClosed = 'Closed';
        return Database.getQueryLocator('SELECT Id, Status FROM Case WHERE (Status = :statusDraft OR Status = :statusNew OR Status = :statusClosed) and FileUploadFlag__c =true');
    }
    global  void execute(Database.BatchableContext BC,List<SObject> scope){
        delete scope;
    }
    global void finish(Database.BatchableContext BC){
    }
}
Hi,

I want to update the fields in a custom object based on the condition using the Batch class. 
I have written a code on batch class but I'm unable to update the fields.

Below is the code which I have worked, 

Global class BatchUpdateTrainer implements Database.Batchable<Sobject> {
    
    
    Global database.QueryLocator start(database.BatchableContext BC){
        return Database.getQueryLocator('Select id, Background_Check_Done__c, LinkedIn_Profile__c, Verification_Status__c from Trainer_Master__c where id!=null');
    }
    
    Global void execute(database.BatchableContext BC, List<Trainer_Master__c> Scope){
        for (Trainer_Master__c trainer : Scope){
            if(trainer.Background_Check_Done__c =='No' && trainer.LinkedIn_Profile__c == null){
                trainer.Verification_Status__c = 'Details Needed';
            }
            else if(trainer.Background_Check_Done__c =='No' && trainer.LinkedIn_Profile__c!= null){
                trainer.Verification_Status__c = 'Non Verified';
            }
            else if(trainer.Background_Check_Done__c =='Yes' && trainer.LinkedIn_Profile__c!= null){
                trainer.Verification_Status__c = 'Verified';
            }
        }
        system.debug('verification status' + scope);
        Database.update(Scope);
    }
    Global void finish(database.BatchableContext BC){
        
    }
}

Kindly Help me to fix the code.

Thank You..!!

Regards,
Sanjay Vinayak T
I want to write a batch class to delete leads whose last modified date is older than 3 months.
can anyone help?
i have one chackbox type field in account. & if chackbox is false the account owner != contact owner & if true account owner != contact owner through trigger?????
Hello Folks , 
    I will be working on one scenario where a case is been get created from one screen flow where there is one multiselect picklist fields  with the label state where end user can select multiple state value during the case creation . Now I need to create a child cases of the cases which is been created bu the screen flow.
So ideally one parent case is get created through screen flow where suppose state an end user selected is  AK, AL, CZ then the three child cases must be get created because  3 states is been selected  AK, AL, CZ

So 
Parent Case get created from screen flow and passing the case id from flow to apex class to create a no of child cases depend upon the number of state field values.
Code for creating a child Case 



public class createChildCase {
      @InvocableMethod
    public static void createChild(List<Id> caseIds){
        System.debug('createChildCaseInvoked');
        Case parentCase = [Select id, subject , description, DDI_States_Of_Interests__c from Case where id = : caseIds[0]];
         List<String> States = parentCase.DDI_States_Of_Interests__c.split(';');
        System.debug('States Size' +States.size() );
         List<Case> childCase = new List<Case>();
        for(integer i = 0; i< States.size(); i++ ){
            String state = States[i];
            System.debug('State :' +state);
             Case caseAL = new Case();
                         System.debug('@@');
                         caseAL.Subject = 'Sub Case for Different States';
                         System.debug('@@');
                         caseAL.ParentId = parentCase.Id;
                         System.debug('@@');
                         caseAL.RecordTypeId = '01223000000NZDEAA4';
                         System.debug('@@');
                         caseAl.DDI_States_Of_Interests__c = state;
                         //insert caseAK;
                         childCase.add(caseAL);
            
        }
         
       
                          
                          System.debug('@@' +childCase.size());
                         //System.debug('@@' +caseAL.Id);
          insert childCase;
                         //return childCase;
                         
        
    }

}
 
Test Class


@isTest
public class createChildCaseTest {
    
    @isTest
    public static void createChild(){
        Case cases = new Case();
        cases.CaseEmail__c= 'yadavsahil46623@gmail.com';
        cases.MultiSelect_State__c = 'AZ, AR, CA';
        cases.Subject = 'Case is been getting created';
        insert cases;
       
        List<Case> caseList = [Select Id, subject,CaseEmail__c, MultiSelect_State__c from Case where id =: cases.Id ];
        System.assertEquals('yadavsahil46623@gmail.com',cases.CaseEmail__c );
        
    }

}

Now how may i proceed futher not geting an idea please let me know if any comments 
How should i wrote a test class for this scenarios?
public class ContactandLeadSearch {
    public static list<list<sobject>> searchcontactsandleads(string lastname){
        
        list<list<sobject>> contactleadlist = [find : lastname in all fields returning contact (name),Lead(name)];
        return contactLeadlist;
    }

}
display sum of amount of opportunities in a stage (stage name as parameter-> you can take any one stage name)
can anyone help on this?
Custom object Production_Request__c has a picklist field named Production_Status__c which contains the values New, Approved, In Progress and Completed.
Custom object Merchandise__c has a picklist field named Status__c which contains the Item Requested, Production approved, In Production and Available.
Studying salesforce apex, I have 2 objects one is name Merch and the other is Production, the production object has a look up field to get the names of items available on the Merchandise object. What I want to do is when the status field of the Production record which is picklist is set to "New" the status field on the Merchandise record will update to "Item Requested" , when the production request status is set to "Approved" the status on the merchandise record will be changed to "Prodution Approved". Each update on the Production record status field there will be matching update on the Merch record status field.

Hi, i want to cover my class but i don't know what i do that.

public with sharing class LCCTRL_GenBop {

    @AuraEnabled
    public static void insertFile(Id oppId, String base64FileData, Opportunity recordData) {

        try {
            Id[] contentDocIdLs = new Id[]{};
    
            ContentDocumentLink[] ctLinkLs = [SELECT ContentDocumentId FROM ContentDocumentLink WHERE LinkedEntityId = :oppId];
            
            for(ContentDocumentLink ctLink : ctLinkLs) {
                contentDocIdLs.add(ctLink.ContentDocumentId);
            }
    
            ContentVersion[] cvLs = [SELECT Id FROM ContentVersion WHERE ContentDocumentId  IN :contentDocIdLs AND IsLatest = true AND Type_fileupload__c = 'BOP'];
    
            String fileTitle = 'BOP--'+ (recordData.Name!=null ? recordData.Name : '') + '_V'+(cvLs.size()+1);
            ContentVersion cv = new ContentVersion(Type_fileupload__c = 'BOP',  VersionData = EncodingUtil.base64Decode(base64FileData), Title = fileTitle, PathOnClient = fileTitle + '.' + 'pdf');
            insert cv;

            cv = [SELECT ContentDocumentId FROM ContentVersion WHERE Id = : cv.Id];
    
            insert new ContentDocumentLink(LinkedEntityId = oppId, ContentDocumentId = cv.ContentDocumentId);

        } catch (AuraHandledException e) {
            throw new AuraHandledException(e.getMessage());
        }
    }

    @AuraEnabled
    public static Map<String,Object> getData(Id oppId) {
        Map<String,Object> dataMap = new Map<String,Object>();

        Opportunity opp = [SELECT Id, Name, Customer_Selection_Criteria_Price__c, Customer_Selection_Criteria_Time__c, Customer_Selection_Criteria_Quality__c, Customer_Selection_Criteria_Location__c, Customer_Selection_Criteria_Reputation__c, Customer_Selection_Criteria_Relationship__c,
            Account.Name, TOLABEL(Account.Country__c), TOLABEL(Account.Type), Account.Market_cap_Investors__c, Account.Dedicated_to_therapeutic_fields__c, Account.Clinical_or_marketed_product_pipeline__c, Account.Linked_to_other_CDMO__c, Account.Cultural_fit__c, Account.Expertise__c, Account.Capacity__c, Account.Strategic__c, Account.Relationship__c, 
            Nature_of_the_molecule__c, Z_Indication__c, TOLABEL(Stage_of_Development__c), Sales_expected_at_Peak_Sale__c, Estimated_probability_of_Success__c, When__c, Which_technology__c, First_source__c, Dead_line_to_deliver_the_offer__c, Dead_line_to_select_the_CDMO__c
                FROM Opportunity WHERE Id = :oppId LIMIT 1];

        dataMap.put('record', opp);

        return dataMap;
    }
}


I have try this to make test for enter in the method testInsertFile but he doesn't work.

In the test class is my data used in the org for test.

@isTest
public with sharing class TEST_LCCTRL_GenBop {

    @TestSetup
    static void setup(){

        Map<String,Schema.RecordTypeInfo> rtMapByName = Schema.SObjectType.Account.getRecordTypeInfosByName();

        Schema.RecordTypeInfo recordtype = rtMapByName.get('Commercial');

        Account account4Test = new Account(name = 'TEST ACCOUNT'
                , Country__c = 'US'
                , CurrencyIsoCode = 'EUR'
                , Type = 'Commercial'
                , RecordTypeId = recordtype.RecordTypeId);

        insert account4Test;
        
        Product2 product = TestCreate_Product2.Create_Product2();

        GMID_Product__c gmid = new GMID_Product__c();

        gmid.Z_Commercial_Product__c = product.Id;
        gmid.Z_GMID_ext_key__c = 'GMID_EXT_001';
        gmid.Z_GMID_GUOM_to_KGM__c = '0';
        gmid.Z_GMID_Status__c = true;
        gmid.Z_CRI__c = 100;
        insert gmid;

        Term_of_payment__c temOfPayment = new Term_of_payment__c();
        temOfPayment.Z_EN_Description__c = 'TEST';
        temOfPayment.Z_Source_date__c = Date.today();
        insert temOfPayment;


        Opportunity opportunity = new Opportunity();
        opportunity.AccountId = account4Test.Id;
        opportunity.Z_Product__c = product.Id;
        opportunity.Z_GMID_Product__c = gmid.Id;
        opportunity.StageName= TRGHDL_Opportunity.QUALIFICATION;
        opportunity.Name = 'TEST1';
        opportunity.Z_Service_comments__c = 'TEST1';
        opportunity.CloseDate = Date.today().addDays(30);

        opportunity.Z_Incoterms__c = 'CIP';
        opportunity.Z_Incoterms_2__c = 'TEST';
        opportunity.Z_Terms_of_Payment__c = temOfPayment.Id;
        
        insert opportunity;
    }
    
    @IsTest
    private static void testInsertFile(){

        
        String fileData = 'Title';
        String fileDateBase64 = EncodingUtil.base64Encode(Blob.valueOf(FileData));

        Opportunity opportunity = [SELECT AccountId, StageName FROM Opportunity WHERE Z_Service_comments__c ='TEST1' LIMIT 1];

        ContentVersion[] cvLs = [SELECT Id, ContentDocumentId FROM ContentVersion];
        Test.startTest();
        insert opportunity;

    }
        
    @IsTest
    private static void getData(){


    }
}
  • July 19, 2022
  • Like
  • 0
trigger createfutherdetails on Opportunity (before insert) {
    Set<Id> accSpecificIds = new Set<Id>();
    
    List<OpportunityContactRole> ocrlist = new List<OpportunityContactRole>(); 
    
    Map<Id, List<Contact>> accountSpecificContacts = new Map<Id, List<Contact>>();
    
    for(Opportunity o: Trigger.New) { 
        if(o.AccountSpecificOppId__c != Null){
            accSpecificIds.add(o.AccountSpecificOppId__c);
        }
    }
    for(Contact con: [select Id,AccountSpecificId__c from Contact where AccountSpecificId__c IN: accSpecificIds]) {
            if(!accountSpecificContacts.containsKey(con.AccountSpecificId__c)){
                accountSpecificContacts.put(con.AccountSpecificId__c, new List<Contact>());
                accountSpecificContacts.get(con.AccountSpecificId__c).add(con);
            }
    }
    for(Opportunity opp: Trigger.New) {
                if(accountSpecificContacts.containskey(opp.AccountSpecificOppId__c)&& accountSpecificContacts.get(opp.AccountSpecificOppId__c) != NULL) { 
                    Boolean isFirstContact = true;
                                   
                    for(Contact c: accountSpecificContacts.get(opp.AccountSpecificOppId__c)) {
                        OpportunityContactRole ocr = new OpportunityContactRole(ContactId = c.Id, OpportunityId = opp.Id);
                        if(isFirstContact) {
                            ocr.IsPrimary = true; 
                            isFirstContact = false;
                        }
                        ocrList.add(ocr);
                    }
                }
            
    }
    
        if(ocrlist.size() > 0)
        insert ocrlist;
        
        
    }
I have a custom class which needs testing but I have no clue how to and where to get started. 
Below is an example of the original. 
This code is used on a custom Apex page to generate some output.
public with sharing class getCustomvalues {

		private final Account account;
    	public List<String> myitems {get; private set;}
    	
    	public List<Account_items__c> result {get;set;}
    
    	public getCustomvalues() {
            Id id = ApexPages.currentPage().getParameters().get('id');
            account =  [SELECT Account.Name, items__c FROM Account WHERE Id = :id];
            myitems = new List<String>();
            if (account.items__c== null) {
			    /*
					code
				*/
            } else {
			    /*
					code
				*/
            }
        }

        public Account getAccount() {
        
    	    return account;
	    }

}

My questions:
  1. How to instantiate this class from a testing class?
  2. How to set the currentPage Id ?
    1. Should I use a stub class too?
If I want exclude records starting with '__%' on an Account object how can we write a SOQL query  
Eg: SELECT Id, Name, Status from Account where Name Like 'HA%' - this query will fetch all the receords starting with HA.  But Here I want all the records by 
public static void setEmailDomain(List<Contact> contactNewList) {
        
        Set<Id> accountIds = new Set<Id>();
        
        for(Contact con : contactNewList) {
            if(con.AccountId != null) {
                accountIds.add(con.AccountId);
            }
        }
        
        List<Account> accountList = new List<Account>();
        List<Account> accountToUpdate = new List<Account>();
        
        if(!accountIds.isEmpty()) {
            accountList = [SELECT Id, Email_Domain__c, (SELECT Id, Email FROM Contacts WHERE Email != null) 
                           FROM Account WHERE Id IN : accountIds];
            
            for(Account acc : accountList) {
                String emailDomainString = '';
                
                if(!acc.Contacts.isEmpty()) {
                    for(Contact con : acc.Contacts){
                        if(emailDomainString.contains(con.Email.subStringAfter('@'))) {
                            emailDomainString = emailDomainString + con.Email.subStringAfter('@') + ', ';
                        }
                    }
                    acc.Email_Domain__c = emailDomainString;
                    accountToUpdate.add(acc);
                }
            }
            
            if(!accountToUpdate.isEmpty()) {
                update accountToUpdate;
            }
        }
    }
}

Hello All,
When a lead is converted, is it possible to find out, in an Apex trigger, whether the ConvertedAccountId is referecing to an existing Account or an Account created as a result of the conversion? Or in another word, can I find out whether a user selected an existing account or created a new account as part of the lead conversion process?

Thanks,

Afrose Ahamed 

public class eventCreation {
//eventCreation.demoEvent();
    public static void demoEvent(){
Event newEvent = new Event();
newEvent.OwnerId = '0055i000003MTGlAAO';
newEvent.Subject ='Testing Demo event';
//newEvent.WhatId = recordId;
newEvent.ActivityDate = System.today();
newEvent.IsRecurrence = true;
newEvent.RecurrenceStartDateTime = System.today();
newEvent.RecurrenceEndDateOnly = System.today()+30;
newEvent.RecurrenceType = 'RecursDaily';
newEvent.RecurrenceInterval = 1;
newEvent.IsAllDayEvent =true;
newEvent.DurationInMinutes =1440;

insert newEvent;
    }
}
trigger Count_Contact_Records on Contact (after insert,after update,after delete,after undelete) {   
   
 
    set<id> accIds = new set<id>();
    if(trigger.isafter && (trigger.isinsert || trigger.isupdate || trigger.isundelete)){
        for(contact con : Trigger.new){
            if(con.accountid != null){
                accIds.add(con.accountid);
            }
        }
    }
    if(trigger.isafter && (trigger.isupdate || trigger.isdelete)){
        for(contact con : Trigger.old){
            if(con.accountid != null){
                accIds.add(con.accountid);
            }
        }
    }
    if(accIds != null){
      list<Account> lstaccs =[select id,name,Total_child_records__c,(select id, name from contacts) from Account where id in :accIds];
        for(account acc : lstaccs)
        {
            acc.Total_child_records__c = acc.contacts.size();
        }
        update lstaccs;
    
    }



        
}
I wrote a trigger as followes:-
1) Create a contact 
  • If the checkbox (Create_Contact__c) while creating account is marked create contact wih same details.
  • If the checkbox is not marked create only account.
2) Update contact
  • If the user is updating the contact which has a related contact, update with the details added.
The trigger I wrote:-
trigger CreateContactOnAccount on Account (before insert,after insert, before update, after update) {
    if(Trigger.isBefore || Trigger.isInsert){
         List<Contact> addCon = new List<Contact>();
    	 for(Account acc : trigger.new){
            if(acc.Create_Contact__c == true){
                Contact cons = new Contact(Lastname = acc.Name,
                	AccountId = acc.id,
            		Fax = acc.Fax,
            		Phone = acc.Phone,
            		MailingStreet = acc.BillingStreet,
            		MailingCity = acc.BillingCity,
            		MailingCountry = acc.BillingCountry,
                    MailingPostalCode=acc.BillingPostalCode);
            	addCon.add(cons);
            }
        }
        insert addCon;
    }
    if(Trigger.isupdate && Trigger.isAfter){
        set<id> getaccountid =new set<id>(); //to get the accountid which is updating
        for(account account : trigger.new){
        	getaccountid.add(account.id);
   			list<contact> contactlist = [SELECT id, accountid FROM contact WHERE accountid =:getaccountid]; //gets the contact with same accountid
    		List<Contact> addCon = new List<Contact>();
    		for(Contact cons : contactlist){
        		Account acc = Trigger.newmap.get(cons.accountid);
            	cons.Lastname = account.Name;
        		//cons.AccountId = account.id;
            	cons.Fax = account.Fax;
            	cons.Phone = account.Phone;
            	cons.MailingStreet = account.BillingStreet;
            	cons.MailingCity = account.BillingCity;
            	cons.MailingCountry = account.BillingCountry;
            	addCon.add(cons);
       	 	}
        	update addCon;
    	}
    }
}
The Test class I have written so far. It is working for validateCreateContact() but not working for validateUpdateContact(). The error is logs is "List is out of bound". Please help me with the test class.
@isTest
public class CreateContactOnAccountTest {
	 @istest static void validateCreateContact(){
        
        Account acc = new Account();
		acc.Name='Test Account' ;
        acc.Phone= '7868754543';
		acc.Create_Contact__c = true;
	
		Test.startTest();
        insert acc;
        system.debug(acc.id);
        Test.stopTest();
        
         list<contact> contactlist = [SELECT Id, Name,Phone, AccountId FROM contact WHERE AccountId =: acc.id];
         System.debug(contactlist[0]);
         System.assertEquals('Test Account', contactlist[0].Name);
    } 
    @isTest static void validateUpdateContacts(){
		Account accnew = new Account();
		accnew.Name = 'Test Account 2';
        accnew.Phone = '76776537265';
       	insert accnew;
        
        accnew.Fax = '767653656';
        accnew.BillingCity = 'New Delhi';
        
        Test.startTest();
        update accnew;
        Test.stopTest();
        
        list<contact> contlist = [SELECT Id, Name,Phone, AccountId, Fax, MailingCity FROM contact WHERE AccountId =: accnew.id];
        System.debug(contlist[0]);
        System.assertEquals('767653656', contlist[0].Fax);
        System.assertEquals('New Delhi', contlist[0].MailingCity);
    }
}
Exporting Report From Salesforce In Excel And CSV Formatl Report Event Is Not Tracking Format Type For Excel It Only Tracks For Csv

SELECT Id, User.name, EventDate, ExportFileFormat, Format, ReportId, IsScheduled, Name FROM ReportEvent
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

I have a multiple case flow.
Flow works when activated, however, when I do a debug on all case object flow I am getting this debug log error.
CANNOT_EXECUTE_FLOW_TRIGGER : We can't save this record because the “Case: Create and/or Update Contact Email to Case” process failed
 
The flow Case: Create and/or Update Contact Email to Case has already been deleted
 
NOTE, I do not have a related contact record update node in this flow (NOT Case: Create and/or Update Contact Email to Case) 
Even on a new flow I am getting the same error message on debug.
Note : I do not have a field on case object named "[Last Name]"

 

User-added image

  • September 30, 2023
  • Like
  • 0
1- Write a batch class to update leads status as closed lost if no activity has been performed for last 30 days and send notification to manager
I am getting the attached wrrorUser-added image
global class UpdateLeadStatusBatch implements Database.Batchable<sObject> {

    global Database.QueryLocator start(Database.BatchableContext BC) {
        DateTime thirtyDaysAgo = System.now().addDays(-30);
        String query = 'SELECT Id, OwnerId, Owner.ManagerId__c FROM Lead WHERE LastActivityDate <= :thirtyDaysAgo AND Status != \'Closed - Lost\'';
        return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext BC, List<sObject> scope) {
        List<Lead> leadsToUpdate = new List<Lead>();
        Set<Id> managerIds = new Set<Id>();

        for (sObject s : scope) {
            Lead lead = (Lead) s;
            lead.Status = 'Closed - Lost';
            leadsToUpdate.add(lead);

            // Access the manager's Id through the custom field
            Id managerId = (Id)lead.get('Owner.ManagerId__c');
            if (managerId != null) {
                managerIds.add(managerId);
            }
        }

        update leadsToUpdate;

        // Send Notification to Managers
        // Using Email Services to send email notifications
        if (!managerIds.isEmpty()) {
            List<Messaging.SingleEmailMessage> emailMessages = new List<Messaging.SingleEmailMessage>();

            for (Id managerId : managerIds) {
                // Construct and send email to the manager
                User managerUser = [SELECT Id, Email FROM User WHERE Id = :managerId LIMIT 1];

                if (managerUser != null && !String.isBlank(managerUser.Email)) {
                    Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
                    email.setSubject('Lead Status Update');
                    email.setHtmlBody('<p>Hello, ' + managerUser.Name + ',</p>' +
                                      '<p>The status of some leads has been updated to "Closed - Lost" due to inactivity.</p>' +
                                      '<p>Thank you!</p>');
                    email.setTargetObjectId(managerUser.Id);
                    email.setSaveAsActivity(false);
                    emailMessages.add(email);
                }
            }

            if (!emailMessages.isEmpty()) {
                List<Messaging.SendEmailResult> sendResults = Messaging.sendEmail(emailMessages);
                for (Messaging.SendEmailResult result : sendResults) {
                    if (!result.isSuccess()) {
                        System.debug('Failed to send email: ' + result.getErrors()[0].getMessage());
                    }
                }
            }
        }
    }

    global void finish(Database.BatchableContext BC) {
        // Any logic you want to execute after the batch finishes
    }
}
 
Develop a trigger that sends an email notification to the account owner when a high-priority case is created or updated.

I have written the below code but email is not getting fired 

public class CaseEmailNotificationHandler {
    public static void sendEmailNotifications(List<Case> casesToUpdate) {
        List<Messaging.SingleEmailMessage> emailMessages = new List<Messaging.SingleEmailMessage>();
 
        // Collect Account Owner Ids for high-priority cases and fetch User information
        Map<Id, User> accountOwners = new Map<Id, User>();
        
        for (Case updatedCase : casesToUpdate) {
            if (updatedCase.Priority == 'High') {
                Id ownerId = updatedCase.Account.OwnerId;
                
                // Check if the ownerId has not been processed already
                if (!accountOwners.containsKey(ownerId)) {
                    List<User> owners = [SELECT Id, Name, Email FROM User WHERE Id = :ownerId LIMIT 1];
                    if (!owners.isEmpty()) {
                        accountOwners.put(ownerId, owners[0]);
                    } else {
                        System.debug('No User found for ownerId: ' + ownerId);
                    }
                }
 
                User accountOwner = accountOwners.get(ownerId);

                if (accountOwner != null && !String.isBlank(accountOwner.Email)) {
                    // Create email message
                    Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
                    email.setSubject('High-Priority Case Notification');
                    email.setHtmlBody('<p>Hello, ' + accountOwner.Name + ',</p>' +
                                      '<p>A high-priority case has been created or updated. Please review the details.</p>' +
                                      '<p>Case Number: ' + updatedCase.CaseNumber + '</p>' +
                                      '<p>Case Subject: ' + updatedCase.Subject + '</p>' +
                                      '<p>Priority: ' + updatedCase.Priority + '</p>' +
                                      '<p>Thank you!</p>');
                    email.setTargetObjectId(accountOwner.Id);
                    email.setSaveAsActivity(false);
                    emailMessages.add(email);
                } else {
                    System.debug('Email not sent due to missing or invalid recipient for case Id: ' + updatedCase.Id);
                }
            }
        }
         
        if (!emailMessages.isEmpty()) {
            List<Messaging.SendEmailResult> sendResults = Messaging.sendEmail(emailMessages);
            for (Messaging.SendEmailResult result : sendResults) {
                if (!result.isSuccess()) {
                    System.debug('Failed to send email: ' + result.getErrors()[0].getMessage());
                }
            }
        }
    }
}
trigger CaseEmailNotificationTrigger on Case (after insert, after update) {
    if (Trigger.isAfter && (Trigger.isInsert || Trigger.isUpdate)) {
        CaseEmailNotificationHandler.sendEmailNotifications(Trigger.new);
    }
}
Hello everyone, Just wanted to ask why my SOQL query is not working inside @RestResource?
 
List<Account> recordToUpdate = [Select id from Account where id = '001Dn00000PideYIAR' LIMIT 1];
System.debug(!recordToUpdate.isEmpty());

This code inside @RestResource returns false, which means that it can't get any record. 
But if I run the same code inside the Developer Console it returns true. Why is that?User-added image 
Also using Query Editor shows a record
User-added image

Any help would be appreciated. Thanks in advance!

Regards,
Ryan

 

OR (
$RecordType.Name = "Release",$RecordType.Name ='Digital Part Release'),
ISPICKVAL(Card_Closure_Status__c, 'None'),
IF( Associated_Credit_Card__c = 'Yes',True,False),
)
HTML >>>
<template>
   
    <div class="slds-m-top_medium slds-m-bottom_x-large">
        <h2 class="slds-text-heading_medium slds-m-bottom_medium">
            Button-icons with the <code>variant</code> attribute omitted or set to the default value of <code>border</code>.
        </h2>
        <!-- with border / by default -->
        <div class="slds-p-around_medium lgc-bg">
            <lightning-button-icon icon-name="utility:add"  alternative-text="New Request" title="New request" onclick={showModalpopUp}></lightning-button-icon>
            <template if:true={isModalpopupTrue}>
                <!-- //<c-modal-popup-component></c-modal-popup-component> -->
                <section role="dialog" tabindex="-1" aria-labelledby="modal-heading-01" aria-modal="true" aria-describedby="modal-content-id-1" class="slds-modal slds-fade-in-open">
                    <div class="slds-modal__container">
                     <!-- modal header start -->
                       <header class="slds-modal__header">
                          <button class="slds-button slds-button_icon slds-modal__close slds-button_icon-inverse" title="Close" onclick={hideModalBox}>
                             <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">Leave Request</h2>
                       </header>
                   
                       <!-- modal body start -->
                       <div class="slds-modal__content slds-p-around_medium" id="modal-content-id-1">
                        <lightning-record-edit-form object-api-name={objectApiName}
                        record-id={recordId} onsuccess={handleSuccess}>
                        <lightning-messages></lightning-messages>
                        <lightning-input-field field-name={user}> </lightning-input-field>
                        <lightning-input-field field-name={FromDate}> </lightning-input-field>
                        <lightning-input-field field-name={Todate}> </lightning-input-field>
                        <lightning-input-field field-name={Reason}> </lightning-input-field>
                        <lightning-button  variant="brand"  type="submit" name="save" label="Save">
                        </lightning-button>
                        <lightning-button   type="submit" name="Cancel" label="Cancel" onclick={hideModalBox}>
                        </lightning-button>
                        </lightning-record-edit-form>
                             
                       </div>
             
                       <!-- modal footer start
                       <footer class="slds-modal__footer">
                        <lightning-button  variant="brand"  type="submit" name="save" label="Save">
                        </lightning-button>
                          <button class="slds-button slds-button_neutral" onclick={hideModalBox}>Cancel</button>
                       </footer> -->
                   
                    </div>
                 </section>
                 <div class="slds-backdrop slds-backdrop_open"></div>
           
            </template>
        </div>
        <div style="height: 300px;">
            <lightning-datatable
                    key-field="id"
                    data={tabledata}
                    columns={columns}
                    hide-checkbox-column
                    onrowaction={handleRowAction}>
            </lightning-datatable>
        </div>
    </div>        
</template>

Js file >>>>>>>>> 

 showModalpopUp(){
       this.isModalpopupTrue = true;
       console.log('Get the details of Lig input tag >>>>>>'+this.template.querySelectorAll("lightning-input-field"));
       
       this.template.querySelectorAll('lightning-input').forEach(element => {            
        element.value = null;
      });  
    }

Getting error as  >>
Get the details of Lig input tag >>>>>>SecureNodeList: [object NodeList]{ key: {"namespace":"c"} }
How to trigger the bell notification when a file is attached to a task record. We only want the bell notification to trigger when the task is owned by specific role. Thanks
Here is my code, 
//1/to get parent unique id
Set<Id> accountIDs=new Set<Id>();
            for(Opportunity oppRecord:Trigger.new)
            {
                if(oppRecord.AccountId!=null)
                    accountIDs.add(oppRecord.AccountId);
            }
//2. parent to child relationship 
            List<Account> accountList=[Select ID, Rating, Highest_opp_record__c,
                                       (Select ID, StageName, Amount,AccountID FROM Opportunities Where Amount>=50000)
                                       FROM Account Where ID in:accountIDs
                                       ];
//3. update the amount in account record
            List<Account> accList=new List<Account>();                      
            for(Account accRecord:accountList)
            {
                accRecord.Highest_opp_record__c=(accRecord.Opportunities).Amount;
                accList.add(accRecord);
                
            }
            if(accList.size()>0)
                update acclist;
        }
While creating a record in opportunity am facing the below error:
System.QueryException: List has more than 1 row for assignment to SObject Trigger.OpportunityTriggerAmount: line 27, column 1
 
I want to create one picklist namely rating and having values 1,2,3,4,5 and we have five images of 1 star , 2 star etc upto 5 star and wanted to create one image formula field where we will be able able to see images which we have from 1 star to 5 star.
How to acieve this?

Thanks
Exporting Report From Salesforce In Excel And CSV Formatl Report Event Is Not Tracking Format Type For Excel It Only Tracks For Csv

SELECT Id, User.name, EventDate, ExportFileFormat, Format, ReportId, IsScheduled, Name FROM ReportEvent
Hi All

I have used one utility icon for the icon-name attribute of lightning-card.

<lightning-card title="Account GMV" icon-name="utility:table"></lightning-card>

By default the utility icon will be displayed with no colour. Now I want to give a colour to it.

I tried add a CSS class inside the tag and write css code to give colur. That didn't work.
<lightning-card title="Account GMV" class ="greenClour" icon-name="utility:table"></lightning-card>

.THIS.greenClour svg{
      fill: #7FFF00;
}


It didn't work. Can anyone please help me to achieve this?
Hello,
I try to build a custom Apex class for my search component. I get multiple errors and dont know how to fix them. Can you help me with the adjustment?

Greetings Jonathan

User-added image
I have a class and I am trying to write a test class for it here is the code:
global class BatchMassDeleteDraftCaseRecs Implements Database.batchable<sobject>{
    
    global BatchMassDeleteDraftCaseRecs(){
         
    }
    global Database.QueryLocator start(Database.BatchableContext BC){
        
        String statusDraft = 'Draft';
        String statusNew = 'New';
        String statusClosed = 'Closed';
        return Database.getQueryLocator('SELECT Id, Status FROM Case WHERE (Status = :statusDraft OR Status = :statusNew OR Status = :statusClosed) and FileUploadFlag__c =true');
    }
    global  void execute(Database.BatchableContext BC,List<SObject> scope){
        delete scope;
    }
    global void finish(Database.BatchableContext BC){
    }
}
public class acc_contact_num_rollup 
{
    public static Void InsertMethod(list<Contact> lstCon ){
        List<Account> accList=new List<Account>();

    Set<Id> setAccIds = new Set<Id>();
         for(Contact con : lstCon){ 
            if(con.AccountId != null){
                   setAccIds.add(con.AccountId);      
            }   
        }
        for(Account acc :[Select id,Number_of_Contact__c ,(Select id,name from contacts) from Account where Id in : setAccIds]){
     
        acc.Number_of_Contact__c = acc.contacts.size();
       
        acclist.add(acc);
    }
    if(!acclist.isempty()){
        update accList; 
    }
    }
    public static Void UpdateMethod(list<Contact> lstCon,map<Id,Contact>oldmap ){
        List<Account> accList=new List<Account>();

    Set<Id> setAccIds = new Set<Id>();
         for(Contact con : lstCon){ 
            if(con.AccountId != null){
                   setAccIds.add(con.AccountId); 
                setAccIds.add(oldMap.get(con.Id).AccountId);
            }   
        }
        for(Account acc :[Select id,Number_of_Contact__c ,(Select id,name from contacts) from Account where Id in : setAccIds]){
     
        acc.Number_of_Contact__c = acc.contacts.size();
       
        acclist.add(acc);
    }
    if(acclist.size()>0){
        update accList; 
    }
    }
    public static Void deleteMethod(list<Contact> lstCon){
        List<Account> accList=new List<Account>();

    Set<Id> setAccIds = new Set<Id>();
         for(Contact con : lstCon){ 
            if(con.AccountId != null){
                   setAccIds.add(con.AccountId);      
            }   
        }
        for(Account acc :[Select id,Number_of_Contact__c ,(Select id,name from contacts) from Account where Id in : setAccIds]){
     
        acc.Number_of_Contact__c = acc.contacts.size();    
        acclist.add(acc);
    }
    if(acclist.size()>0){
        update accList; 
    }
    }

}
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