• Shubham Jain 338
  • NEWBIE
  • 188 Points
  • Member since 2020
  • Senior Software Engineer
  • Trantor

  • Chatter
    Feed
  • 6
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 40
    Replies
In Apex Test , i need to verify that specific method of the Apex class that i am testing, is getting called when i run the test. I am looking for something similar to .toHaveBeenCalledTimes () that is available in javascript.

Appreciate any help on this!
Hi ... i have count the field "is active " from contact object and should populate the value in "Total active contacts" in account object.
can anyone help me i'm new to codings..
I am trying to write Test Class for the following Batch Apex but unable to get more than 40 percentage coverage 
 
global class AutoRenewContractBatchApex implements Database.Batchable<SObject>, Database.Stateful {          
          global Database.QueryLocator start(Database.BatchableContext bc){         
                 return Database.getQueryLocator( 'SELECT Id, RenewalQuoted__c, Owner_Expiration_Notice__c, EndDate FROM Contract WHERE RecordType.DeveloperName = \'Class_Contract\' AND Owner_Expiration_Notice__c != Null AND RenewalQuoted__c = FALSE' );     

uncovered  [    
global void execute(Database.BatchableContext bc, List<Contract> crlist){  
          for(Contract contract:crlist){ 
              integer dateDifferene=(date.today()).daysBetween(contract.EndDate);
             String ExpireDays = String.valueOf(dateDifferene);             
             system.debug('@@dateDifferene-----' +dateDifferene);                                                                                 system.debug('@@OwnerExpirationNotice-----' +contract.Owner_Expiration_Notice__c);          if((ExpireDays==contract.Owner_Expiration_Notice__c)){ 
            contract.RenewalQuoted__c = TRUE;                 
           Id contrId = contract.Id;                 
            update crlist;                                                                                       ]uncovered   
                                            }
                      }                    
 }     
   global void finish(Database.BatchableContext bc){                 

}
 
The Test Class is following through which I am geeting 33 percent coverage.
 
@isTest  public class AutoRenewContractBatchTest {     
@isTest     static void checkAutoRenewContract()     {         
Id crId = Schema.SObjectType.Contract.getRecordTypeInfosByDeveloperName(). get('Class_Contract').getRecordTypeId();                  
 
Account acc = new Account(Name = 'Test', Paperwork__c = 'Fuels Indian',
                           CurrencyIsoCode = 'IND' );         insert acc;         
        
List<Contract> crList = new List<Contract>();         
for(Integer i=0; i < 200; i++){                          
Contract contract = new Contract();             
contract.AccountId = acc.id;             
contract.RenewalQuoted__c = False;             
contract.BPG_Owner_Expiration_Notice__c = '';             
contract.RecordTypeId = crId;             
contract.StartDate = System.today();            
 contract.ContractTerm = 4;                          
crList.add(contract);       
  }         
insert crList;                 
 test.startTest(); 
                 AutoRenewContractBatchApex batch = new AutoRenewContractBatchApex();         database.executeBatch(batch);                 
 test.stopTest();     

}
 
//unable to insert EndDate field as it is a not writable field, EndDate is being calculated by StartDate+ContractTerm
 
It also have a scheduler 
 
global class AutoRenewContractSchedule implements Schedulable {    
 global void execute(SchedulableContext ctx) {        
 AutoRenewContractBatchApex batchObject = new AutoRenewContractBatchApex();  
Id batchId = Database.executeBatch(batchObject, 1);     
  }
}
 
Can anyone tell how what should I do to improve code coverage. I am also marking the uncovered portion of the code.
Hi,

We have a use case where we would like to restrict the possibility of creating more than one open opportunity of a certain record type on an account. So for example: let's say we have a record type called New Sale, and one record type called Upsell. It should then only be possibly to create a single open New Sale opportunity. If there's an open New Sale opportunity a new one can not be created. However, if there's an old New Sale opportunity that's closed, then a new New Sale opportunity *can* be created. Meanwhile, the Upsell opportunity should not be affected by any of this, and multiple Upsell opportunities should always be able to be created.

Is this possible to do? If yes, would it have to be done in Apex, or could a flow be built for this?
Hello! I am working on a script to automatically merge duplicate Accounts, based on the Accounts sharing the same number in the field "FirmCRD__c."

I am getting a Compile Error: Unexpected token 'global'. at line 83 column 5 when I attempt to save the class below in my Sandbox.
May you please help me fix/improve this script?
 
global class BatchFirmCRDAccountMerge implements Database.Batchable<sobject> {

    global  Database.QueryLocator start(Database.BatchableContext ctx) {                  
        return Database.getQuerylocator([SELECT Id, Name, MasterRecordId, FirmCRD__c FROM Account]); 
    }
    
    global void execute(Database.BatchableContext BC, List<Account> accounts ) {
        
        
        // Create a map with FirmCRD code and its account
        Map<String, List<Account>> FirmCRDAccountsToMerge = new Map<String, List<Account>>();
        
        
        for (Account account : accounts) {
                
            List<Account> accountsToMerge = FirmCRDAccountsToMerge.get(account.FirmCRD_Code__c);
            
            if (accountsToMerge == null) {
                accountsToMerge = new List<Account>();
                FirmCRDAccountsToMerge.put(account.FirmCRD_Code__c, accountsToMerge);
            }
            
            if (accountsToMerge.size() < 2) {
                accountsToMerge.add(account);
            } else {
                
                // Merges takes up to two records to merge with the master
                // https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_database.htm
                System.debug('Maximum of accounts to merge reached.');
            }
            
        }

        System.debug('****FirmCRD and acc map*** ');
        System.debug(FirmCRDAccountsToMerge);

        List<account> dupacc = new list<account>();
            
        for (String FirmCRDCode : FirmCRDAccountsToMerge.keySet()) {
            
            List<Account> accountsToMerge = FirmCRDAccountsToMerge.get(FirmCRDCode);
            
            if (accountsToMerge.size() > 1) {  
            
                Account masterAccount;
                List<Id> duplicatedAccounts = new List<Id>();           
          
                for (Account account : accountsToMerge) {
                    
                        if (masterAccount == null) {
                            masterAccount = account;
                                      }

                System.debug('***Master account*** ' + masterAccount);
                System.debug('***Duplicated accounts*** ' + duplicatedAccounts);
                
                Database.MergeResult[] results = Database.merge(masterAccount, duplicatedAccounts, false);
                
                System.debug('***results merged** ' + results);
                
                for (Database.MergeResult res : results) {
                    if (res.isSuccess()) {
                        System.debug('Master record ID: ' + res.getId());
                        System.assertEquals(masterAccount.Id, res.getId());               
                        List<Id> mergedIds = res.getMergedRecordIds();
                        System.debug('IDs of merged records: ' + mergedIds);                       
                    } else {
                        for (Database.Error err : res.getErrors()) {
                            System.debug(err.getMessage());
                        }
                    }                       
                }                
            }
            
            // If the DML limit is reached, breaks the execution and continue on the next Batch execution
            if (Limits.getDMLRows() == Limits.getLimitDMLRows()) {
                System.debug('DML limit reached. Shall continue on the next execution');
                break;
            }

    
 
    global void finish(Database.BatchableContext BC) {
         
    }

}
Please help me write a test class for an apex trigger that sends an email when a contact is created.
 
trigger EmailContact on Contact (after insert) {
List<Messaging.SingleEmailMessage> emailList= new List<Messaging.SingleEmailMessage>();
EmailTemplate emailTemplate = [Select Id,Subject,Description,HtmlValue,DeveloperName,Body from EmailTemplate where name='Contract Signed Thank you'];
for(Contact conObj:Trigger.new){
if (conObj.Email != null) {
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setTargetObjectId(conObj.Id);
mail.setSenderDisplayName('System Administrator');
mail.setUseSignature(false);
mail.setBccSender(false);
mail.setSaveAsActivity(true);
mail.setTemplateID(emailTemplate.Id);
mail.toAddresses = new String[]{conObj.Email};
emailList.add(mail);
}
}
if(emailList.size()>0){
Messaging.SendEmailResult[] results = Messaging.sendEmail(emailList);
if (results[0].success)
{
System.debug('The email was sent successfully.');
} else {
System.debug('The email failed to send: '+ results[0].errors[0].message);
}
}
}


 
This is what i have so far. i get an error that lines 9&15 are missing ','
@isTest private class EmailContactTestClass { static testMethod void validateEmailContact() { Contact c = new Contact(LastName='Test',Email='test@test.org'); System.debug(c.LastName); insert c; System.assertEquals(0, Limits.getEmailInvocations(); c = [SELECT id FROM Contact WHERE LastName ='Test' limit 1]; System.assertEquals(1, Limits.getEmailInvocations(); } }

 
  • May 15, 2022
  • Like
  • 0
I have two lists with two different different fields to update the asset object in Salesforce. Below is the sample data.
 
List1:
====

AssetId                      Field1
a2i1                           abc
a2i2                           acb
a2i3                           cad
a2i4                           gfd


List2:
====

AssetId                      Field2
a2i0                           mnp
a2i2                           nop
a2i3                           mnh
a2i7                           pqr
a2i8                           iyo


Expected Output List:
==================

AssetId                      Field1             Field2
a2i0                                                  mnp
a2i1                           abc
a2i2                           acb                 nop
a2i3                           cad                 mnh
a2i4                           gfd
a2i7                                                   pqr
a2i8                                                   iyo

When I merge them into one list, I get an exception during the update as the list has duplicate ids in it (a2i2, a2i3). I would like to merge both lists into one, but having both fields in the list as shown above.

Since the lists contain Ids, I can convert them into two maps and loop thru the first map using KeySet() and check if the Id is present in the second map. If it is available, I can populate field2. But I need to repeat the same with map2.

Is there a better approach for this?
 
  • August 20, 2022
  • Like
  • 0
In Apex Test , i need to verify that specific method of the Apex class that i am testing, is getting called when i run the test. I am looking for something similar to .toHaveBeenCalledTimes () that is available in javascript.

Appreciate any help on this!
Hi ... i have count the field "is active " from contact object and should populate the value in "Total active contacts" in account object.
can anyone help me i'm new to codings..
I have the below code and there is a SOQL query inside for loop. I have been instructed to avoid SOQL in the loop as these are invoked for every iteration of the loop. Since i am a beginner in Salesforce i don't know how to implement that. Here's my code where i have advised to use Soql query and condition checking before for loop using a map.

 
if ((isTrgBefore && (isInsert||isUpdate ))){
   for( Item eachitem :newItemList ){
     if(eachItem.WhoId!=Null){
        Schema.SObjectType sobjectType =         eachItem.WhoId.getSObjectType();
        String sobjectName = sobjectType.getDescribe().getName();
        if(sobjectName.equals(UTIL_Constants.SubString)){ 
                    List<Strategy> stg=[select Type from Strategy where Id=:eachItem.WhoId];
                        for(Strategy s:stg){
                            if(s.Type=='Market Strategy' || s.Type=='Market Potency'){
                            eachItem.Strategy__c = eachItem.WhoId; 
                            }
                        }
         }
     }
     setWhatIds.add(eachItem.WhatId);
  }
}

 
  • May 23, 2022
  • Like
  • 0
Hi,
I have a field defined as number(16,2).  If I put in the value 0, SF UI shows 0.0 but in the database it is saved as 0 without the decimal points.  I have a web application that integrates with SF and the web application passes me a value for this field as a string to filter.  So, in my apex code, I need to do "double.valueOf(field)".  However, if the web application passes me a "0", my SOQL won't return anything b/c it will convert it to 0.00 but it's stored as a "0" in the DB.  How can I solve this problem?
  • May 20, 2022
  • Like
  • 0
Hello everyone, I am quite new on the platform and have a rather interesting task to solve. I have been playing around with a Trigger but I have not gotten that far. Help is much appreciated.

For Cases:
1. If the parent case is closed, I would like to prevent the child case status from changing from closed to open.
2. A generic error message should be displayed informing the user of this
3. When child case status has been changed from closed to open, the child case cannot be saved if the parent case is not open
4. When child case status has been changed from closed to open, the child case can be saved if parent case also has status of open
  • May 20, 2022
  • Like
  • 0
To fix the exception: System.LimitException: Too many SOQL queries: 101 made changes to the apex class as below. Can anyone please highlight the issue in it? as i am getting another error while saving-Method does not exist or incorrect signature: void add(String) from the type List<Order>

Apex Class-
Public class QTB_CreateOrderItem {
    public static final string className = QTB_CreateOrderItem.class.getName();
    public static boolean throwExplicitException = false;
    // Calling this method from flow to create orderitems based on selected products.
    @InvocableMethod
   Public static void updateOrderItemDetails(list <flowInputs> request)
    {   
        List<OrderItem> OrderItemlst = new List<OrderItem>();
        List <PriceBookEntry> book = new  List <PriceBookEntry>();
        List<Order> NewCrOrder = new List<Order>();
        String errorIds = '';
        List<Order> NewCrOrder1 = new List<Order>();
       
        
        For(flowInputs flow:request)
        {
            NewCrOrder1.add(flow.newOrderCreated);
            
            book=[select id, name,Product2Id,Product2.SBQQ__ChargeType__c,Product2.SBQQ__BillingFrequency__c,Product2.SBQQ__BillingType__c,Product2.blng__BillingRule__c,Product2.blng__TaxRule__c,Product2.blng__RevenueRecognitionRule__c,Product2.SBQQ__SubscriptionTerm__c from PricebookEntry where ProductCode in :flow.productCodes and Pricebook2Id = :flow.oldOrderData.Pricebook2Id ];
            system.debug('Retrieved PRbentry ----------'+ book.size());      
        }
        
        NewCrOrder1 = [Select id,name,EffectiveDate,EndDate,QTB_Legal_Entity_Country__c,Account.QTB_Contract_Entity__c from order  where id IN :NewCrOrder];    
        

            
        
        try {
            if (throwExplicitException) {
                system.debug('NullPointer');
                throw new NullPointerException();
            } 
            
            List<blng__BillingTreatment__c> sgListBillingTreat=[Select id, name,blng__BillingRule__r.id from blng__BillingTreatment__c Where Name='No Invoice Billing Treatment' LIMIT 1];
            if(book.size()>0)  {  
                For(pricebookentry pr : book)
                  {  
                    OrderItem temporderitem = new OrderItem();
                    temporderitem.OrderId = NewCrOrder[0].id;
                    temporderitem.blng__BillableUnitPrice__c= 0;
                    temporderitem.Product2Id = pr.Product2.Id;
                    temporderitem.Quantity = 1;
                    temporderitem.UnitPrice = 0;    
                    temporderitem.blng__HoldBilling__c = 'No';   
                    temporderitem.blng__TaxCountry__c = NewCrOrder[0].QTB_Legal_Entity_Country__c;
                    temporderitem.ServiceDate = NewCrOrder[0].EffectiveDate;
                    temporderitem.EndDate = NewCrOrder[0].EndDate;
                    temporderitem.SBQQ__BillingFrequency__c = 'Monthly';
                    temporderitem.SBQQ__BillingType__c = 'Arrears';
                    temporderitem.SBQQ__ChargeType__c  = 'Recurring';  
                    temporderitem.SBQQ__ContractAction__c  = 'New'; 
                    temporderitem.SBQQ__ContractingMethod__c  = 'Inherit';
                    temporderitem.SBQQ__SubscriptionTerm__c= 1;    
                    temporderitem.SBQQ__DefaultSubscriptionTerm__c= 1;
                    temporderitem.SBQQ__OrderedQuantity__c= 1;
                    temporderitem.SBQQ__PricingMethod__c='List';
                    temporderitem.SBQQ__ProductSubscriptionType__c = 'One-Time'; 
                    temporderitem.SBQQ__SubscriptionType__c = 'One-Time';
                    temporderitem.SBQQ__Status__c = 'Draft';   
                    temporderitem.SBQQ__SubscriptionPricing__c='Fixed Price';
                    temporderitem.PricebookEntryId = pr.Id;
                    temporderitem.blng__BillingRule__c =pr.Product2.blng__BillingRule__c;
                    temporderitem.blng__BillingTreatment__c = sgListBillingTreat[0].id;
                    temporderitem.blng__LegalEntity__c = NewCrOrder[0].Account.QTB_Contract_Entity__c;
                    temporderitem.blng__RevenueRecognitionRule__c  = pr.Product2.blng__RevenueRecognitionRule__c;
                    temporderitem.blng__TaxRule__c = pr.Product2.blng__TaxRule__c;
                    OrderItemlst.add(temporderitem);    
                   }
            }
            Insert OrderItemlst;
            system.debug('Inserted Items ======' +OrderItemlst.size());
            List<Id> OrdidtoLoad = new List<Id>();
            OrdidtoLoad.add(NewCrOrder[0].id);
            //To update order item for seperate invoicing 
            list<OrderItem> lstupdate= new list<OrderItem>();
            list<OrderItem> itemlst = new list<OrderItem>();
            itemlst=[Select id,blng__InvoiceGrouping__c,blng__InvoiceGroupId__c,Order.OrderNumber from OrderItem where order.id IN :OrdidtoLoad];
            system.debug('Total Selected to update:'+ itemlst.size());
            for(OrderItem ls : itemlst)
            {
                ls.blng__InvoiceGrouping__c= 'Invoice Group ID';
                ls.blng__InvoiceGroupId__c= ls.Order.OrderNumber;
                lstupdate.add(ls);
                
            }
            system.debug('Total Selected to update:'+ lstupdate.size());  
            update lstupdate;
            //To Update matching attribute on usage summary related to newly created orderItems
            List<blng__UsageSummary__c  > Uslsttoupdate =new List<blng__UsageSummary__c>();
            List<blng__UsageSummary__c  > Uslst = new List<blng__UsageSummary__c  >();
            Uslst =[Select id,blng__MatchingAttribute__c,blng__Order__r.OrderNumber from blng__UsageSummary__c Where blng__Order__r.id IN :OrdidtoLoad];
            system.debug('Size+++++++++++++++:'+ Uslst.size());
            for (blng__UsageSummary__c us :Uslst)
            {
                us.blng__MatchingAttribute__c = us.blng__Order__r.OrderNumber;
                Uslsttoupdate.add(us);
            }
            Update Uslsttoupdate;
            System.debug('Updated count====='+Uslsttoupdate.size());
            // To activate Created Orders/OrderItems
            Database.executeBatch(new QTB_AddOrderProductCSCRBatch(OrdidtoLoad), 200);
            
        }
          catch (exception e) {
            errorIds = e.getMessage() + errorIds;
            if (errorIds.length() > 100000)
                errorIds = errorIds.substring(0, 100000);
            system.debug('In catch method of batch Finish>>>>>>>>>>');
            system.debug('Error inf::' + errorIds);
            QTB_ExceptionLogger.createLog(
                e.getLineNumber(),
                e.getStackTraceString(),
                errorIds,
                e.getTypeName(),
                className
            );
        }  
        
    }
  Public class flowInputs{
        @InvocableVariable
        public Order oldOrderData;
        @InvocableVariable    
        Public string newOrderCreated;
        @InvocableVariable
        Public list<String> productCodes;
      }
    
}
I want to check that on opportunity if amount is greater than 10% of expected revenue then checked the coupon 1 and if 20% then checked coupon 2 and if 30% then checked coupon 3.

Coupon 1 and 2 and 3 these fields are discount coupon and this object are child object of opportunity 

How to write code for this scenario
I am trying to write Test Class for the following Batch Apex but unable to get more than 40 percentage coverage 
 
global class AutoRenewContractBatchApex implements Database.Batchable<SObject>, Database.Stateful {          
          global Database.QueryLocator start(Database.BatchableContext bc){         
                 return Database.getQueryLocator( 'SELECT Id, RenewalQuoted__c, Owner_Expiration_Notice__c, EndDate FROM Contract WHERE RecordType.DeveloperName = \'Class_Contract\' AND Owner_Expiration_Notice__c != Null AND RenewalQuoted__c = FALSE' );     

uncovered  [    
global void execute(Database.BatchableContext bc, List<Contract> crlist){  
          for(Contract contract:crlist){ 
              integer dateDifferene=(date.today()).daysBetween(contract.EndDate);
             String ExpireDays = String.valueOf(dateDifferene);             
             system.debug('@@dateDifferene-----' +dateDifferene);                                                                                 system.debug('@@OwnerExpirationNotice-----' +contract.Owner_Expiration_Notice__c);          if((ExpireDays==contract.Owner_Expiration_Notice__c)){ 
            contract.RenewalQuoted__c = TRUE;                 
           Id contrId = contract.Id;                 
            update crlist;                                                                                       ]uncovered   
                                            }
                      }                    
 }     
   global void finish(Database.BatchableContext bc){                 

}
 
The Test Class is following through which I am geeting 33 percent coverage.
 
@isTest  public class AutoRenewContractBatchTest {     
@isTest     static void checkAutoRenewContract()     {         
Id crId = Schema.SObjectType.Contract.getRecordTypeInfosByDeveloperName(). get('Class_Contract').getRecordTypeId();                  
 
Account acc = new Account(Name = 'Test', Paperwork__c = 'Fuels Indian',
                           CurrencyIsoCode = 'IND' );         insert acc;         
        
List<Contract> crList = new List<Contract>();         
for(Integer i=0; i < 200; i++){                          
Contract contract = new Contract();             
contract.AccountId = acc.id;             
contract.RenewalQuoted__c = False;             
contract.BPG_Owner_Expiration_Notice__c = '';             
contract.RecordTypeId = crId;             
contract.StartDate = System.today();            
 contract.ContractTerm = 4;                          
crList.add(contract);       
  }         
insert crList;                 
 test.startTest(); 
                 AutoRenewContractBatchApex batch = new AutoRenewContractBatchApex();         database.executeBatch(batch);                 
 test.stopTest();     

}
 
//unable to insert EndDate field as it is a not writable field, EndDate is being calculated by StartDate+ContractTerm
 
It also have a scheduler 
 
global class AutoRenewContractSchedule implements Schedulable {    
 global void execute(SchedulableContext ctx) {        
 AutoRenewContractBatchApex batchObject = new AutoRenewContractBatchApex();  
Id batchId = Database.executeBatch(batchObject, 1);     
  }
}
 
Can anyone tell how what should I do to improve code coverage. I am also marking the uncovered portion of the code.
In TriggerHandler i am getting 'FATAL_ERROR System.TypeException: Invalid conversion from runtime type Contact to REO_Application__c'
line number 15
REO_Application__c reo = (REO_Application__c)application;


Trigger:

trigger REOApplicationTrigger on REO_Application__c (before insert, before update, after update) {
    new REOApplicationTriggerHandler().run();
}

TriggerHandler :

public without sharing class REOApplicationTriggerHandler extends TriggerHandler {
    public REOApplicationTriggerHandler() {}
   
    override public void beforeInsert() {
        List<REO_Application__c> REOsToCreateContact = new List<REO_Application__c>();
        for(REO_Application__c reo : (List<REO_Application__c>)Trigger.new) {
            if(reo.Applicant_Contact__c == null) {
                REOsToCreateContact.add(reo);
            }                                                        
        }  
        if(!REOsToCreateContact.isEmpty()) {
            Map<SObject, Id> applicationContactIds = Utility.createContact(REOsToCreateContact, Utility.getContactFieldMapping('REO'));
            if(applicationContactIds != null) {
                for(SObject application : applicationContactIds.keySet()) {
                    REO_Application__c reo = (REO_Application__c)application;
                    reo.Applicant_Contact__c = applicationContactIds.get(reo);
                }                
            }          
        }
    }

Utility: getContactFieldMapping

  public static Map<String, String> getContactFieldMapping(String objType) {
        Map<String, String> fieldMap = new Map<String, String>();
        switch on objType {
            when 'REO' {
                fieldMap.put('Applicant_Last_Name__c', 'LastName');
                fieldMap.put('Applicant_Country__c', 'MailingCountry');
                fieldMap.put('Applicant_Postal_Code__c', 'MailingPostalCode');
                fieldMap.put('Applicant_Street__c', 'MailingStreet');
                fieldMap.put('Applicant_Mobile__c', 'MobilePhone');
                fieldMap.put('Applicant_NRIC_FIN__c', 'NRIC_FIN__c');
                fieldMap.put('Applicant_Phone__c', 'Phone');
                fieldMap.put('Date_of_Birth__c', 'Birthdate');                
                fieldMap.put('Gender__c', 'Gender__c');
                fieldmap.put('Applicant_Nationality__c', 'Nationality__c');
                fieldMap.put('Work_Permit_Expiry_Date__c', 'Work_Permit_Expiry_Date__c');
                fieldMap.put('Work_Permit_Number__c', 'Work_Permit_Number__c');
            }
            when 'RES' {
                fieldMap.put('Applicant_Last_Name__c', 'LastName');
                fieldMap.put('Applicant_Country__c', 'MailingCountry');
                fieldMap.put('Applicant_Postal_Code__c', 'MailingPostalCode');
                fieldMap.put('Applicant_Street__c', 'MailingStreet');
                fieldMap.put('Applicant_Mobile__c', 'MobilePhone');
                fieldMap.put('Applicant_NRIC_FIN__c', 'NRIC_FIN__c');
                fieldMap.put('Applicant_Phone__c', 'Phone');
                fieldMap.put('Date_of_Birth__c', 'Birthdate');                
                fieldMap.put('Gender__c', 'Gender__c');        
                fieldmap.put('Applicant_Nationality__c', 'Nationality__c');
                fieldMap.put('Work_Permit_Expiry_Date__c', 'Work_Permit_Expiry_Date__c');
                fieldMap.put('Work_Permit_Number__c', 'Work_Permit_Number__c');                
            }
            when else {
                return null;
            }
        }
        return fieldMap;
    }
Create some apex logic for old Accounts, so we can run this logic,get all accounts without 'custom users" then create these 'custom users', link them with the correspondent account and link all opportunities from Account record to the custom user.
Hi,

We have a use case where we would like to restrict the possibility of creating more than one open opportunity of a certain record type on an account. So for example: let's say we have a record type called New Sale, and one record type called Upsell. It should then only be possibly to create a single open New Sale opportunity. If there's an open New Sale opportunity a new one can not be created. However, if there's an old New Sale opportunity that's closed, then a new New Sale opportunity *can* be created. Meanwhile, the Upsell opportunity should not be affected by any of this, and multiple Upsell opportunities should always be able to be created.

Is this possible to do? If yes, would it have to be done in Apex, or could a flow be built for this?
Hi All,

This is My Code  
I need to access glist Type(id) in My postopptoslack() Method.
That's why I have made glist as Public But when I am Accessing glist In  My2() method it's showing value of Id.
But When I am try to accessing this glist variable in postopptoslack() method then it's Showing the value as Null. What Can I do to access this value in the method?.




public with sharing class PostToSlack {
   public static id glist;
@invocableMethod(label='post win opp to slack'
                description='posting deatils of opportunity'
                category='opportunity')
    public static void postopp(list<id> opp){
        system.debug('flow');
       system.debug('op'+opp[0]);     
        system.debug('oppid'+opp);
        PostToSlack.my2(opp[0]);
    }
   
    public static id my2(id gl){
            glist=gl;
        system.debug('methodlist'+glist+' '+gl);
        return gl;
    }
     static{
        system.debug('static'+glist);
    }
    @auraenabled(cacheable=true)
    public static void getlist(list<string> values1){
        PostToSlack.postopptoslack(values1);
    }
    public static void postopptoslack(list<string> values2){
        system.debug('this'+glist);
        string sn='';
         Date cd;
         decimal a;
         string n='';
        //string a='name';
        system.debug('opp'+values2);
        string q1='select ';
        for(integer i=0;i<values2.size();i++){
            q1+=values2[i]+',';
        }
        system.debug('g'+glist);
        q1+='id,Link__c from opportunity where id =:glist';
        
        list<opportunity> oplist=database.query(q1);
        system.debug('oplist'+oplist);

        if(!oplist.isEmpty()){
            string mssg='';
           
            for(opportunity op:oplist){
                
                for(integer i=0;i<values2.size();i++){
                   
                    String var =values2[i];
                    if(var=='stagename')
                    {
                        sn=op.StageName;  
                        mssg+='StageName ='+' '+sn+'\n';
                    }
                    else if(var=='amount'){
                        a=op.Amount;
                        mssg+='Amount ='+' '+a+'\n';
                    }
                    else if(var=='closeDate'){
                        cd=op.CloseDate;
                        mssg+='CloseDate ='+' '+cd+'\n';
                    }
                    else if(var=='name'){
                        n=op.Name;
                        mssg+='Name ='+' '+n+'\n';
                    }
                
               
                }
          
                }
            system.debug('message'+mssg);
            Http http=new Http();
            HttpRequest req=new HttpRequest();            
            req.setEndpoint('https://hooks.slack.com/services/xKdM9Mk29hFhhUcH2Khbkydf');
            req.setMethod('POST');
            req.setHeader('content-Type', 'application/json;charset=UTF-8');
            req.setBody('{"text":"'+ mssg+ '"}');
            
            try{
            HttpResponse response=http.send(req);
                if(response.getStatusCode()==200){
                    system.debug('success');
                }
                else{
                    system.debug('Error');
                }
            }
            catch(exception e){
                system.debug('Error'+e.getMessage());
            }
        }
    }
}
I am getting the following error when I am trying to create a new recurring donation:
npsp.TDTM_RecurringDonation: execution of AfterInsert caused by: System.DmlException: Insert failed. First exception on row 0; first error: INVALID_CROSS_REFERENCE_KEY, Record Type ID: this ID value isn't valid for the user: 01241000000jhWTAAY: [RecordTypeId] (System Code)

How do I resolve this?