// Trigger: Update Contact Count on Account
trigger UpdateContactCount on Contact (after insert, after update, after delete,
after undelete) {
Set<Id> accountIds = new Set<Id>();
// Collecting Account Ids from inserted, updated, deleted, or undeleted
Contacts
if (Trigger.isInsert || Trigger.isUpdate || Trigger.isUndelete) {
for (Contact con: Trigger.new) {
if (con.AccountId != null) {
accountIds.add(con.AccountId);
}
}
}
if (Trigger.isUpdate || Trigger.isDelete) {
for (Contact con: Trigger.old) {
if (con.AccountId != null) {
accountIds.add(con.AccountId);
}
}
}
// Recalculate Contact Count for each Account
if (!accountIds.isEmpty()) {
List<Account> accountsToUpdate = new List<Account>();
Map<Id, Integer> contactCountMap = new Map<Id, Integer>();
for (AggregateResult ar : [SELECT AccountId, COUNT(Id) contactCount FROM
Contact WHERE AccountId IN: accountIds GROUP BY AccountId]) {
contactCountMap.put((Id)ar.get('AccountId'),
(Integer)ar.get('contactCount'));
}
for (Id accId: accountIds) {
accountsToUpdate.add(new Account(Id = accId, Number_of_Contacts__c =
contactCountMap.get(accId) != null ? contactCountMap.get(accId) : 0));
}
update accountsToUpdate;
}
}
###################################################################################
##################################################################################
// Apex Trigger and method to check if an Account has related Contacts. If none
exist, it creates a default Contact.
// Trigger on Contact (After Delete)
trigger ContactTrigger on Contact (after delete) {
Set<Id> accountIds = new Set<Id>();
for (Contact con: Trigger.old) {
if (con.AccountId != null) {
accountIds.add(con.AccountId);
}
}
ContactHelper.ensureDefaultContact(accountIds);
}
// Trigger on Account (After Insert)
trigger AccountTrigger on Account (after insert) {
Set<Id> accountIds = new Set<Id>();
for (Account acc: Trigger.new) {
accountIds.add(acc.Id);
}
ContactHelper.ensureDefaultContact(accountIds);
}
// Apex Method: Check & Create Default Contact
Approach 1: Better
public class ContactHelper {
public static void ensureDefaultContact(Set<Id> accountIds) {
if (accountIds == null || accountIds.isEmpty()) {
return; // Exit if no Account IDs are provided
}
// Query existing Contacts and remove their AccountIds from the set
for (AggregateResult ar : [SELECT AccountId FROM Contact WHERE AccountId
IN: accountIds GROUP BY AccountId]) {
accountIds.remove((Id) ar.get('AccountId')); // Remove Accounts that
already have Contacts
}
// Create default Contact for Accounts that have no Contacts
List<Contact> contactsToInsert = new List<Contact>();
for (Id accId: accountIds) {
contactsToInsert.add(new Contact(FirstName = 'Default', LastName =
'Contact', AccountId = accId));
}
if (!contactsToInsert.isEmpty()) {
insert contactsToInsert;
}
}
}
Approach 2: Good but not Best
public class ContactHelper {
public static void ensureDefaultContact(Set<Id> accountIds) {
if (accountIds == null || accountIds.isEmpty()) {
return; // Exit if no Account IDs are provided
}
// Find Accounts that don't have at least one Contact
Set<Id> accountsWithNoContacts = new Set<Id>();
List<Account> accList = [SELECT Id, (SELECT Id FROM Contacts LIMIT 1) FROM
Account WHERE Id IN: accountIds];
for (Account acc: accList) {
if (acc.Contacts.isEmpty()) {
accountsWithNoContacts.add(acc.Id);
}
}
// Create default Contacts only for Accounts with no Contacts
List<Contact> contactsToInsert = new List<Contact>();
for (Id accId: accountsWithNoContacts) {
contactsToInsert.add(new Contact(FirstName = 'Default', LastName =
'Contact', AccountId = accId));
}
// Perform DML operation with error handling
if (!contactsToInsert.isEmpty()) {
Database.insert(contactsToInsert, false);
}
}
}
###################################################################################
##################################################################################
// Apex Trigger to Update Account’s StageName__c Field Based on Related
Opportunity's StageName
// Trigger: Update Account Stage from Opportunity
trigger UpdateAccountStage on Opportunity (after update) {
Set<Id> accountIds = new Set<Id>();
// Collect Account IDs from updated Opportunities
for (Opportunity opp: Trigger.new) {
if (opp.AccountId != null) {
accountIds.add(opp.AccountId);
}
}
if (!accountIds.isEmpty()) {
// Fetch the latest Opportunity Stage for each Account
Map<Id, String> accountStageMap = new Map<Id, String>();
for (AggregateResult ar : [SELECT AccountId, MAX(StageName) stage FROM
Opportunity WHERE AccountId IN: accountIds GROUP BY AccountId]) {
accountStageMap.put((Id) ar.get('AccountId'), (String)
ar.get('stage'));
}
// Update Account records with the latest Opportunity Stage
List<Account> accountsToUpdate = new List<Account>();
for (Id accId : accountStageMap.keySet()) {
accountsToUpdate.add(new Account(Id = accId, StageName__c =
accountStageMap.get(accId)));
}
if (!accountsToUpdate.isEmpty()) {
update accountsToUpdate;
}
}
}
// Same trigger but without SOQL approach
trigger UpdateAccountStage on Opportunity (after update) {
Map<Id, Opportunity> accountLatestOppMap = new Map<Id, Opportunity>();
// Iterate through updated Opportunities and store the latest StageName
for (Opportunity opp: Trigger.new) {
if (opp.AccountId != null) {
// Store the opportunity only if it's the latest one encountered in the
trigger
if (!accountLatestOppMap.containsKey(opp.AccountId) ||
opp.LastModifiedDate > accountLatestOppMap.get(opp.AccountId).LastModifiedDate) {
accountLatestOppMap.put(opp.AccountId, opp);
}
}
}
// Prepare Account records for update
List<Account> accountsToUpdate = new List<Account>();
for (Id accId: accountLatestOppMap.keySet()) {
accountsToUpdate.add(new Account(Id = accId, StageName__c =
accountLatestOppMap.get(accId).StageName));
}
if (!accountsToUpdate.isEmpty()) {
update accountsToUpdate;
}
}
###################################################################################
##################################################################################
// Apex trigger to update the Account object's Description field with a comma-
separated list of related Opportunity names and update Total_Amount__c
// with the sum of all related Opportunity amounts.
trigger UpdateAccountFields on Opportunity (after insert, after update, after
delete, after undelete) {
Set<Id> accountIds = new Set<Id>();
// Collect related Account Ids
if (Trigger.isInsert || Trigger.isUpdate || Trigger.isUndelete) {
for (Opportunity opp: Trigger.new) {
if (opp.AccountId != null) {
accountIds.add(opp.AccountId);
}
}
}
if (Trigger.isDelete) {
for (Opportunity opp: Trigger.old) {
if (opp.AccountId != null) {
accountIds.add(opp.AccountId);
}
}
}
if (!accountIds.isEmpty()) {
OpportunityHelper.updateAccountFields(accountIds);
}
}
public class OpportunityHelper {
public static void updateAccountFields(Set<Id> accountIds) {
if (accountIds == null || accountIds.isEmpty()) {
return; // Exit early if no Account IDs are provided
}
// Query related Opportunities and organize data efficiently
Map<Id, List<Opportunity>> accountOppMap = new Map<Id,
List<Opportunity>>();
for (Opportunity opp : [SELECT Id, Name, Amount, AccountId FROM Opportunity
WHERE AccountId IN: accountIds]) {
if (!accountOppMap.containsKey(opp.AccountId)) {
accountOppMap.put(opp.AccountId, new List<Opportunity>());
}
accountOppMap.get(opp.AccountId).add(opp);
}
// Prepare list of Accounts to update
List<Account> accountsToUpdate = new List<Account>();
for (Id accId: accountIds) {
List<Opportunity> relatedOpps = accountOppMap.get(accId);
// Check if there are related Opportunities
if (relatedOpps == null || relatedOpps.isEmpty()) {
continue; // Skip Accounts without related Opportunities
}
// Build comma-separated Opportunity names
List<String> oppNames = new List<String>();
Decimal totalAmount = 0;
for (Opportunity opp: relatedOpps) {
if (opp.Name != null) {
oppNames.add(opp.Name);
}
if (opp.Amount != null) {
totalAmount += opp.Amount;
}
}
// Create new Account object with updated fields
accountsToUpdate.add(new Account(Id = accId, Description =
String.join(oppNames, ', '), Total_Amount__c = totalAmount));
}
if (!accountsToUpdate.isEmpty()) {
update accountsToUpdate;
}
}
}
###################################################################################
##################################################################################
// Method to return the accountId and the total Paid Payment value from the related
Payment object to the related Opportunity object of the Account
public class PaymentHelper {
public static Map<Id, Decimal> getAccountPaidPayments(Set<Id> accountIds) {
// Return an empty map if input is null or empty
if (accountIds == null || accountIds.isEmpty()) {
return new Map<Id, Decimal>();
}
// Query to aggregate total paid amount for each Account
Map<Id, Decimal> accountPaymentMap = new Map<Id, Decimal>();
for (AggregateResult ar : [SELECT Opportunity.AccountId accountId,
SUM(Payment_Paid__c) totalPaid FROM Payment__c WHERE Opportunity.AccountId IN:
accountIds AND Payment_Paid__c != null AND Status = 'Paid' GROUP BY
Opportunity.AccountId]) {
accountPaymentMap.put((Id) ar.get('accountId'), (Decimal)
ar.get('totalPaid'));
}
return accountPaymentMap;
}
}
###################################################################################
##################################################################################
// Trigger to calculate and update the Total_Quantity__c field on Invoice__c
whenever related LineItem__c records are inserted, updated, deleted, or undeleted.
trigger LineItemTrigger on LineItem__c (after insert, after update, after delete,
after undelete) {
Set<Id> invoiceIds = new Set<Id>();
// Collect related Invoice IDs
if (Trigger.isInsert || Trigger.isUpdate || Trigger.isUndelete) {
for (LineItem__c li : Trigger.new) {
if (li.Invoice__c != null) {
invoiceIds.add(li.Invoice__c);
}
}
}
if (Trigger.isUpdate || Trigger.isDelete) {
for (LineItem__c li : Trigger.old) {
if (li.Invoice__c != null) {
invoiceIds.add(li.Invoice__c);
}
}
}
// Call helper method to update Invoice total quantity
if (!invoiceIds.isEmpty()) {
InvoiceHelper.updateInvoiceTotalQuantity(invoiceIds);
}
}
public class InvoiceHelper {
public static void updateInvoiceTotalQuantity(Set<Id> invoiceIds) {
if (invoiceIds == null || invoiceIds.isEmpty()) {
return; // Exit early if no Invoice IDs are provided
}
// Step 1: Aggregate total quantity from related LineItems
Map<Id, Decimal> invoiceQuantityMap = new Map<Id, Decimal>();
for (AggregateResult ar : [
SELECT Invoice__c invoiceId, SUM(Quantity__c) totalQty
FROM LineItem__c
WHERE Invoice__c IN: invoiceIds
GROUP BY Invoice__c
]) {
invoiceQuantityMap.put((Id) ar.get('invoiceId'), (Decimal)
ar.get('totalQty'));
}
// Step 2: Prepare Invoices for update
List<Invoice__c> invoicesToUpdate = new List<Invoice__c>();
for (Id invId: invoiceIds) {
Decimal totalQty = invoiceQuantityMap.containsKey(invId) ?
invoiceQuantityMap.get(invId) : 0;
invoicesToUpdate.add(new Invoice__c(Id = invId, Total_Quantity__c =
totalQty));
}
// Step 3: Perform bulk update
if (!invoicesToUpdate.isEmpty()) {
update invoicesToUpdate;
}
}
}
###################################################################################
##################################################################################
// Trigger to update the Description field of an Opportunity if the Opportunity's
StageName is "Prospecting" and parent Account's Rating is "Hot".
// If both conditions are met, the Opportunity's Description should be set to the
Account's Description.
trigger oppsTrigger on Opportunity (before insert, before update) {
Set<Id> accIds = new Set<Id>();
// Collect all Account IDs related to Opportunities in Trigger
for (Opportunity opp: Trigger.new) {
if (opp.AccountId != null) {
accIds.add(opp.AccountId);
}
}
if (!accIds.isEmpty()) {
// Query only necessary fields and store in a Map for quick lookup
Map<Id, Account> accountMap = new Map<Id, Account>([SELECT Id, Rating,
Description FROM Account WHERE Id IN: accIds]);
// Update Opportunity descriptions based on Account rating
for (Opportunity opp: Trigger.new) {
if (opp.AccountId != null && accountMap.containsKey(opp.AccountId)) {
Account acc = accountMap.get(opp.AccountId);
if (opp.StageName == 'Prospecting' && acc.Rating == 'Hot') {
opp.Description = acc.Description;
}
}
}
}
}
###################################################################################
##################################################################################
// Trigger to Restrict Duplicate Opportunity Names
Trigger opportunityUniqueTrigger on Opportunity (before insert, before update) {
Set<String> oppNameSet = new Set<String>();
// Collect Opportunity names from Trigger.new
for (Opportunity op: Trigger.new) {
if (op.Name != null) {
oppNameSet.add(op.Name.trim().toLowerCase());
}
}
// If there are names, query existing Opportunities
if (!oppNameSet.isEmpty()) {
Set<String> existingOppNames = new Set<String>();
for (Opportunity existingOpp : [SELECT Name FROM Opportunity WHERE Name
IN:oppNameSet]) {
existingOppNames.add(existingOpp.Name.trim().toLowerCase());
}
// Check and add errors to duplicate records
for (Opportunity op : Trigger.new) {
if (op.Name != null &&
existingOppNames.contains(op.Name.trim().toLowerCase())) {
op.addError('An Opportunity with this name already exists!');
}
}
}
}
###################################################################################
##################################################################################
// Apex method to find duplicates in a list of strings and count how many times
each string appears
public static Map<String, Integer> findDuplicates(List<String> strList) {
Map<String, Integer> countMap = new Map<String, Integer>();
if (strList == null || strList.isEmpty()) {
return countMap; // Exit early if the list is null/empty
}
for (String str : strList) {
if (str != null) {
String key = str.trim().toLowerCase();
countMap.put(key, countMap.containsKey(key) ? countMap.get(key) + 1 :
1);
}
}
return countMap;
}
###################################################################################
##################################################################################
// Trigger to update an Account's lookup fields (BillingContact__c,
PrimaryContact__c, SiteContact__c) when related Contacts are inserted or updated
with their
// respective types. If a Contact has BillingContact__c = true, the related
Account's BillingContact__c lookup is updated with that Contact's ID.
// Similarly, it updates PrimaryContact__c and SiteContact__c lookup fields on the
Account when a Contact is marked as the respective type.
// Trigger:
trigger AccountUpdateFromContact on Contact (after insert, after update) {
if (Trigger.isInsert || Trigger.isUpdate) {
ContactTriggerHandler.updateAccountContacts(Trigger.newMap,
Trigger.oldMap);
}
}
// Handler Class:
public class ContactTriggerHandler {
public static void updateAccountContacts(Map<Id, Contact> newContactMap,
Map<Id, Contact> oldContactMap) {
if (newContactMap == null || newContactMap.isEmpty()) {
return; // Exit if no contacts to process
}
Map<Id, Account> accountUpdates = new Map<Id, Account>(); // To store
account updates
for (Contact con : newContactMap.values()) {
if (con.AccountId == null) continue; // Skip contacts without accounts
Account acc = accountUpdates.get(con.AccountId);
if (acc == null) {
acc = new Account(Id = con.AccountId);
accountUpdates.put(con.AccountId, acc);
}
// Check if it's a new Billing, Primary, or Site Contact
if (con.BillingContact__c) {
acc.BillingContact__c = con.Id;
}
if (con.PrimaryContact__c) {
acc.PrimaryContact__c = con.Id;
}
if (con.SiteContact__c) {
acc.SiteContact__c = con.Id;
}
// If it's an update, compare with old values
if (oldContactMap != null && oldContactMap.containsKey(con.Id)) {
Contact oldCon = oldContactMap.get(con.Id);
if (oldCon.BillingContact__c != con.BillingContact__c &&
con.BillingContact__c) {
acc.BillingContact__c = con.Id;
}
if (oldCon.PrimaryContact__c != con.PrimaryContact__c &&
con.PrimaryContact__c) {
acc.PrimaryContact__c = con.Id;
}
if (oldCon.SiteContact__c != con.SiteContact__c &&
con.SiteContact__c) {
acc.SiteContact__c = con.Id;
}
}
}
// Perform bulk update if there are changes
if (!accountUpdates.isEmpty()) {
update accountUpdates.values();
}
}
}
###################################################################################
##################################################################################
// Trigger to automate the deletion and restoration of related ActionPlan__c
records whenever a Contact record is deleted or undeleted.
// Trigger:
trigger ContactTrigger on Contact (after undelete, before delete, after insert,
after update, after delete) {
Set<Id> contactIds = new Set<Id>();
if (Trigger.isDelete || Trigger.isUndelete) {
for (Contact c : (Trigger.isDelete ? Trigger.old: Trigger.new)) {
contactIds.add(c.Id);
}
}
if (Trigger.isDelete) {
deleteRelatedActionPlans(contactIds);
}
if (Trigger.isUndelete) {
undeleteRelatedActionPlans(contactIds);
}
}
// Helper method to delete related Action Plans
private static void deleteRelatedActionPlans(Set<Id> contactIds) {
if (contactIds.isEmpty()) return;
// Step 1: Empty recycle bin for related Action Plans
List<ActionPlan__c> actionPlansToDelete = [
SELECT Id FROM ActionPlan__c WHERE Contact__c IN: contactIds AND isDeleted
= true ALL ROWS
];
if (!actionPlansToDelete.isEmpty()) {
Database.emptyRecycleBin(actionPlansToDelete);
}
// Step 2: Collect Action Plan IDs for batch deletion
List<Id> actionPlanIds = new List<Id>();
for (ActionPlan__c ap : [SELECT Id FROM ActionPlan__c WHERE Contact__c
IN :contactIds]) {
actionPlanIds.add(ap.Id);
}
// Step 3: Execute batch deletion if there are records
if (!actionPlanIds.isEmpty()) {
Database.executeBatch(new ActionPlansBatchDelete(actionPlanIds,
UserInfo.getUserId()));
}
}
// Helper method to undelete related Action Plans
private static void undeleteRelatedActionPlans(Set<Id> contactIds) {
if (contactIds.isEmpty()) return;
// Step 1: Retrieve soft-deleted Action Plans
List<ActionPlan__c> actionPlansToUndelete = [SELECT Id FROM ActionPlan__c WHERE
Contact__c IN: contactIds ALL ROWS];
try {
if (!actionPlansToUndelete.isEmpty()) {
Database.undelete(actionPlansToUndelete, false);
}
} catch (DmlException e) {
for (Contact c: Trigger.new) {
c.addError('You cannot undelete an Action Plan whose related Contact is
deleted.');
}
}
}
###################################################################################
##################################################################################
// Write a batch class to update the MailingCity and MailingCountry fields of
Contact records based on the BillingCity and BillingCountry of their
// parent Account records.
global class UpdateContactFields implements Database.Batchable<SObject> {
global Database.QueryLocator start(Database.BatchableContext BC) {
return Database.getQueryLocator('SELECT Id, MailingCity, MailingCountry,
AccountId FROM Contact WHERE AccountId != null');
}
global void execute(Database.BatchableContext BC, List<Contact> scope) {
if (scope.isEmpty()) return;
// Collect Account IDs from Contact records
Set<Id> accountIds = new Set<Id>();
for (Contact con: scope) {
accountIds.add(con.AccountId);
}
// Query related Accounts and store in a Map
Map<Id, Account> accMap = new Map<Id, Account>([SELECT Id, BillingCity,
BillingCountry FROM Account WHERE Id IN: accountIds]);
// List to store contacts for update
List<Contact> conListToUpdate = new List<Contact>();
for (Contact con : scope) {
Account acc = accMap.get(con.AccountId);
if (acc != null) {
if (acc.BillingCity != null) {
con.MailingCity = acc.BillingCity;
}
if (acc.BillingCountry != null) {
con.MailingCountry = acc.BillingCountry;
}
if (acc.BillingCity == null && acc.BillingCountry == null) {
con.MailingStreet = 'Not available';
}
conListToUpdate.add(con);
}
}
// Perform bulk update with error handling
if (!conListToUpdate.isEmpty()) {
try {
update conListToUpdate;
} catch (DmlException ex) {
System.debug('Error while updating contacts: ' + ex.getMessage());
}
}
}
global void finish(Database.BatchableContext BC) {
System.debug('Batch job completed successfully.');
}
}
###################################################################################
##################################################################################
// Write an Aura Component to create a dynamic Account creation form in Salesforce.
This form should allow users to:
// Fetch picklist values dynamically from an Account object field (e.g.,
"Rating").
// Fill in Account details (Name, Account Number, Phone, and Rating).
// Save the Account record to Salesforce.
// Reset the form on cancel.
// Aura Component:
<aura:component controller="createAccountRecords" implements="force:appHostable,
flexipage:availableForAllPageTypes, forceCommunity:AvailableForAllPageTypes,
force:hasRecordId" access="global">
<!-- Attributes -->
<aura:attribute name="createAcc" type="Account" default="{'sObjectType' :
'Account', 'Name' : '', 'Rating' : ''}"/>
<aura:attribute name="objName" type="String" default="Account"/>
<aura:attribute name="fldName" type="String" default="Rating"/>
<aura:attribute name="ratingList" type="List<String>"/>
<!-- Handler to fetch picklist values on component load -->
<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
<div class="slds-p-around_small">
<lightning:input type="Text" label="Name" value="{!v.createAcc.Name}"/>
<lightning:input type="Text" label="Account Number" value="{!
v.createAcc.AccountNumber}"/>
<lightning:input type="Phone" label="Phone Number" value="{!
v.createAcc.Phone}"/>
<lightning:select label="Rating" value="{!v.createAcc.Rating}">
<option value="">—None—</option>
<aura:iteration items="{!v.ratingList}" var="ac">
<option value="{!ac}">{!ac}</option>
</aura:iteration>
</lightning:select>
<lightning:button label="Save" variant="brand" onclick="{!c.doSave}"/>
<lightning:button label="Cancel" variant="destructive" onclick="{!
c.docancel}"/>
</div>
</aura:component>
// JavaScript Controller (.js):
({
doInit: function(component, event, helper) {
var action = component.get('c.getPickList');
action.setParams({
objName: component.get('v.objName'),
fldName: component.get('v.fldName')
});
action.setCallback(this, function(response) {
var state = response.getState();
if (state === "SUCCESS") {
component.set('v.ratingList', response.getReturnValue());
} else if (state === "ERROR") {
console.error('Error fetching picklist values:',
response.getError());
}
});
$A.enqueueAction(action);
},
doSave: function(component, event, helper) {
var action = component.get('c.createAccount');
action.setParams({
ac: component.get('v.createAcc')
});
action.setCallback(this, function(response) {
var state = response.getState();
if (state === "SUCCESS") {
alert('Account created successfully!');
// Reset the form after saving
component.set('v.createAcc', { 'sObjectType': 'Account', 'Name':
'', 'Rating': '' });
} else if (state === "ERROR") {
var errors = response.getError();
console.error('Error while creating account:', errors);
alert('Failed to create account. Please try again.');
}
});
$A.enqueueAction(action);
},
docancel: function(component, event, helper) {
// Reset the form
component.set('v.createAcc', { 'sObjectType': 'Account', 'Name': '',
'Rating': '' });
}
})
// Apex Controller Class:
public class createAccountRecords {
@AuraEnabled
public static List<String> getPickList(String objName, String fldName) {
List<String> pkList = new List<String>();
try {
// Get object schema
Map<String, Schema.SObjectType> allObj = Schema.getGlobalDescribe();
if (!allObj.containsKey(objName)) {
throw new Exception('Invalid object name: ' + objName);
}
// Get field schema
Map<String, Schema.SObjectField> allFlds =
allObj.get(objName).getDescribe().fields.getMap();
if (!allFlds.containsKey(fldName)) {
throw new Exception('Invalid field name: ' + fldName);
}
// Get picklist values
List<Schema.PicklistEntry> pickList =
allFlds.get(fldName).getDescribe().getPickListValues();
for (Schema.PicklistEntry pk: pickList) {
pkList.add(pk.getValue());
}
} catch (Exception e) {
System.debug('Error fetching picklist: ' + e.getMessage());
}
return pkList;
}
@AuraEnabled
public static List<Account> createAccounts(List<Account> accList) {
List<Account> insertedAccounts = new List<Account>();
if (accList == null || accList.isEmpty()) {
throw new AuraHandledException('Account list cannot be empty.');
}
try {
insert accList;
insertedAccounts = accList;
} catch (DmlException e) {
System.debug('Error inserting accounts: ' + e.getMessage());
throw new AuraHandledException('Failed to create accounts: ' +
e.getDmlMessage(0));
}
return insertedAccounts;
}
}