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


  • Chatter
    Feed
  • 305
    Best Answers
  • 0
    Likes Received
  • 8
    Likes Given
  • 2
    Questions
  • 1214
    Replies
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);
    }
}
public static void contractExpiration(Set<Id> contIds){
        
        List<Contract> contractsToBeUpdated = new List<Contract>();
        for(Contract cont : [select Id,EndDate, Status from Contract where Id =:  contIds]){
            if(cont.Status!='Expired' && cont.Status!='Cancelled'){
                cont.EndDate = system.today();
                cont.Status = 'Expired';
                contractsToBeUpdated.add(cont);  
            }
            
        }
        if(!contractsToBeUpdated.isEmpty()){
            UtilClass.isFirstTime = false;
            update contractsToBeUpdated;
        }
    }
  • June 22, 2022
  • Like
  • 0
This is apex class i want test class 


public class BstockCMtokensave {

    @AuraEnabled

    public static void savetoken (String personId,String accesstoken,String refreshToken,DateTime createdTime){

try{

            System.debug(accesstoken);

            System.debug(refreshToken);

            System.debug(createdTime);

            System.debug(PersonId);

           

            //Fetch access token from custom object

            String strPersonId = 'bstock_' + personId;

            List<Fusion_Auth_Tokens__c> listFAuth = new List<Fusion_Auth_Tokens__c>();

            listFAuth = [Select Id, Access_Token__c,Refresh_Token__c,Last_Refresh_Time__c FROM Fusion_Auth_Tokens__c WHERE Name =: strPersonId];

            for(Fusion_Auth_Tokens__c objFAuth: listFAuth){

                objFAuth.Name = strPersonId;

                objFAuth.Access_Token__c = accesstoken;

                objFAuth.Refresh_Token__c = refreshToken;

                objFAuth.Last_Refresh_Time__c = createdTime;

            }

            if(listFAuth.size() == 0) {

                Fusion_Auth_Tokens__c objFAuth = new Fusion_Auth_Tokens__c();

                objFAuth.Name = strPersonId;

                objFAuth.Access_Token__c = accesstoken;

                objFAuth.Refresh_Token__c = refreshToken;

                objFAuth.Last_Refresh_Time__c = createdTime;

                listFAuth.add(objFAuth);

            }

            upsert listFAuth;

           

            System.debug('listFAuth...' + listFAuth);

        }

        catch(Exception ex){ 

            system.debug('Error while creating modifying custom metadata.');

            System.debug(ex.getMessage());

           

        }

    }

}
public static List<Notes__c> getAllNotes(String accountId){
        List<Notes__c> lstNotes =[SELECT Reference__c, Description__c, CreatedBy.Name
                                         FROM Notes__c WHERE Reference__c =: accountId];
        return lstNotes;
    }
 
Please help me to this test class code
 
 
I wrote an Apex Class to create an account. The user is giving the Account Name as input.  am reading the input using JS and passing the parameter for Apex Class. I have to write a Test Class for the same. Please help me with it.
public with sharing class AddAccount {
    @AuraEnabled
    public static Account insertNewAccount(String accountName){
        Account newAccount = new Account();
        newAccount.Name = accountName;
        try{
            insert newAccount;
            return newAccount;
        }
        catch(Exception d){
            return null;
        }
    }
}

 
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 requirement to check if Case Owner ID is any Queue Id then change the Flag value to True.

I am strucked here how to compare Case Owner Id with List of Queue Id's.

Thanks!!
  • September 05, 2022
  • Like
  • 0
If one record is inserted i want to insert another record with same information
Trigger : 
trigger opprunitybeforeandafter on Opportunity (Before insert, after insert){

if(trigger.isbefore == true && trigger.isinsert == true){

         oppurinityamountclass.makefunction(trigger.new);
}
if(trigger.isafter == true && trigger.isinsert == true){

           oppurinityamountclass.makefunction2(trigger.new,trigger.oldMap);
}
}User-added image




Public class oppurinityamountclass{

     Public static void makefunction(list<Opportunity> varocc){

         for(Opportunity varo : varocc){
           if (varo.Amount >= 50000){
          varo.Amount = varo.Amount/2;
      }
    }
}

    
    Public static void makefunction2(list<Opportunity> varocd,map<id,Opportunity> varold){

     
          List<Opportunity> varins = new List<Opportunity>();

      for (Opportunity opp : varocd ){

  

          opp.Amount = varold.get(opp.id).Amount;

          opp.Name = varold.get(opp.id).Name;
          opp.CloseDate = varold.get(opp.id).CloseDate;
          opp.StageName = varold.get(opp.id).StageName;
         
           varins.add(opp);




}
insert varins;
}
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,
I have below objects
Account Object.
Field 1: Total Amount | Total_Amount__c 
Oppotunity Object.
Field : Amount | Amount | Currency 
Account(Master), Oppotunityetail)
My usecase.
i want to show total of all Amount(opp) in to field Total_Amount__c(Account)
public static List<ProductWrapper> getFilterProduct(String familyname,String searchtext){
        String filter ='SELECT Product2.Id,Name,Product2.Image_ID__c,Product2.Family,UnitPrice '
                         +' FROM PricebookEntry WHERE PriceBook2.IsStandard=true ';
         List<PricebookEntry> filterList;
        if(familyname =='All') { 
            filter+= 'AND Product2.Family != NULL AND Name LIKE \'%' + searchtext + '%\'';
        } else {   //get the filtered list 
            filter+= 'AND Product2.Family= \''+familyname +'\' AND Name LIKE \'%' + searchtext + '%\'';
        }
        filterList = DataBase.query(filter);
        List<ProductWrapper> wrapList = new List<ProductWrapper>();
         ProductWrapper wrap;    
        for(PricebookEntry prod : filterList){
            wrap = new ProductWrapper();
            wrap.id = prod.Product2.Id;
            wrap.name=prod.Name;
            wrap.ImageId=prod.Product2.Image_ID__c;
            wrap.Family=prod.Product2.Family;
            wrap.Price=prod.UnitPrice;
            wraplist.add(wrap);
        }
        return wraplist;
    }
    
“In contact Object we have Contacts status picklist Field when contact user have system administrator profile then he able select active, inactive & disqualify Value as well user have other profile then it only able to select active and in active status”
Create an Account Record with Name = “ABC”. Create associated contacts. Create aCustom field called Contact Count on Account. Query on Contact where Account.Name =“ABC” and count the associated contacts. Update the custom field on Accounts with thatcount.
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?

Fields on contact staging

Contact_Id__c,
Pronouns__c
Aboriginal_or_Torres_Strait_Islander__c, 
Date_of_Birth__c,
CALD__c,
Vaccination_status__c,
Require_an_interpreter__c, 
TIS_Interpreter_Language_Required__c, Safe_to_use_this_phone_number__c, 
Is_it_safe_to_use_this_email_address__c, Can_a_voicemail_be_left__c,
Street__c, 
City__c,
State_Province__c
Zip_Postal_Code__c
Country__c,
Why_is_this_their_current_location__c, 
Agency_Referral__c
Contact_Updated__c 

 

Need help to create a batch class for this the logic is to get all records on contact staging Then update the contact records base on the record info so in the photo below is the record needed to be created on contact staging and the contact Id is the same on contact the fields that are updated on contact staging will happen on contacts aswell


User-added image


did it make sense? Need Help. Thanks

Hello everyone, 
I am working on a test class in apex and this is the class:
global class Flow_Dynamic_EmailAlerts {
    //@AuraEnabled public String emailTemplateName;
    //@AuraEnabled public List<User> recipients;    @InvocableMethod(label='Send request alert' description='Given a list of users it sends an email with email template to the users')
    public static void innerMethodInvocable(List<Flow_Dynamic_EmailAlerts_Request> request){
        EmailTemplate emailTemplate = [
            SELECT Id, Subject,Description, HtmlValue,DeveloperName,Body
            FROM EmailTemplate
            WHERE DeveloperName =: request[0].emailTemplateName
        ];        Set<String> userIdsSet = new Set<String>(request[0].recipients);
        List<User> users = [SELECT Id, Email FROM User WHERE Id IN:new List<String>(userIdsSet)];
        List<String> addresses = new List<String>();        for(User recipient : users) addresses.add(recipient.Email);        Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
        message.setTargetObjectId(UserInfo.getUserId());
        message.setSenderDisplayName('Salesforce Alert');
        //message.setReplyTo(recipient.Email);
        message.setUseSignature(false);
        message.setBccSender(false);
        message.setSaveAsActivity(false);        //Get templete id for set the templete.        message.setTemplateID(emailTemplate.Id);
        //message.setWhatId(account.Id); //merge fields ???
        message.toAddresses = addresses;        Messaging.SingleEmailMessage[] messages = new List<Messaging.SingleEmailMessage> {message};        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);
    }    global class Flow_Dynamic_EmailAlerts_Request {
        @InvocableVariable(required=true)
        global String emailTemplateName;        @InvocableVariable(required=true)
        global List<String> recipients;
    }
}

I am trying to test the class but I cannot understand how to start. All the methotds I've try doesn't work. 

Can sb please see it and explain somehow how shoult I start?
Thanks very much

write trigger for:
Creates the number of contacts which are equal to the number which we will enter in the Number of Locations field on the Account Object.
Create Custom field called “Number of Locations” on the Account Object (Data Type=Number). can anyone provide code for this requirement
 
1.Write a trigger such that there is checkbox field on User,Account,Contact. Whenever we check the checkbox field on Contact, automatically Account and User should also get updated.
2.How can we able to display 70000 records on visualforce page?
 Best Regards,
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;
    }

}
trigger ClosedOpportunityTriigger on Opportunity (after insert,after update) {
    list<task> tasklist = new list<Task>();
    
    for(opportunity opp : Trigger.new){
        if(opp.stagename == 'closed won'){
            tasklist.add(new task(subject = 'follow up Test Task',whatid = opp.id));
        }
    }if(tasklist.size()>0){
        insert tasklist;
    }

}
display all oppurtunities,

in the below code am getting error, can anyone tell me how to fix it?
User-added image
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