• Prateek Prasoon 25
  • SMARTIE
  • 734 Points
  • Member since 2022

  • Chatter
    Feed
  • 24
    Best Answers
  • 0
    Likes Received
  • 2
    Likes Given
  • 0
    Questions
  • 163
    Replies
Hi, good morning, I get the following error in the logs "Error message: List index out of bounds: 0" on line 52 of the code. 
This is the code of line 52, how can I validate or how can I fix the error?
 
new CampaignMembersService_SV().constructRegistrantCampaignMember(regData.optIn, newCon,ProfHubEmailSendSelector_SV.newInstance().selectByMasterLabel(new Set<String> {countryMap.get(regData.country)})[0].Communication_Optin__c, uow);

Thanks!
trigger CountContacts on Contact (after insert, after delete) {
List<Account> addAccCount= new List<Account>();
    Set<Id> addConId= new Set<Id>();
if(trigger.isInsert){
for(Contact con:trigger.new){
addConId.add(con.AccountId);
}
}
if(trigger.isDelete){
for(Contact con:trigger.old){
addConId.add(con.AccountId);
}
}
List<Account> accList=[SELECT Id,CountofContacts__c, (SELECT Id FROM Contacts) FROM Account WHERE Id in: addConId];
for(Account acc:accList){
acc.CountofContacts__c = acc.Contacts.size();
addAccCount.add(acc);
}
Update addAccCount;
}
if(trigger.isDelete){
for(Contact con:trigger.old){
addConId.add(con.AccountId);
}
}
List<Account> accList=[SELECT Id,CountofContacts__c, (SELECT Id FROM Contacts) FROM Account WHERE Id in: addConId];
for(Account acc:accList){
acc.CountofContacts__c = acc.Contacts.size();
addAccCount.add(acc);
}
Update addAccCount;
}
Hi, I have a trigger that updates a field on a custom object, Pitch.  I got it to partially work with help from ChatGPT and my own tweaks.

1. What it does is update a field that shows the total of all Opportunity Amounts related to a specific Opportunity Property Group.
2. Next it should find all other Pitch records that have the same Opportunity Property Group do the same update so all related records should be in sync.

ie Select SUM(Opportunity__r.Amount) From Pitch__c where Property_Group__c = :record.Property_Group__c

It does not do step 2 but I can't figure out why.  Any idea?

trigger calculatePropertyGroupAmountBeforeFull on Pitch__c (before insert, before update) {
  // Get the records that are being triggered on.
  List<Pitch__c> records = Trigger.new;

  // Get the property group amount for each record.
  for (Pitch__c record : records) {
    List<AggregateResult> propertyGroupAmounts = [

      SELECT SUM(Opportunity__r.Amount)
      FROM Pitch__c
      WHERE Id = :record.Id OR     
     Property_Group__c = :record.Property_Group__c
      GROUP BY propertyhighspot__r.Property_Group_Text__c

    ];

    // Set the property group amount for each record.
    if (propertyGroupAmounts != null && propertyGroupAmounts.size() > 0) {
      record.Property_Group_Amount__c = (Decimal)propertyGroupAmounts[0].get('expr0');
    } else {
      // Set the property group amount to 0 if there is no amount.
      record.Property_Group_Amount__c = 0;
    }
  }

  // Check if the trigger is currently running.
  if (RecursiveTriggerHandler.isFirstTime) {
    return;
  }


  // Get the property group amount for each record.
  for (Pitch__c record : records) {
    List<AggregateResult> propertyGroupAmounts = [
      SELECT SUM(Opportunity__r.Amount)
      FROM Pitch__c
      WHERE Id = :record.Id OR Property_Group__c = :record.Property_Group__c
      GROUP BY propertyhighspot__r.Property_Group_Text__c
    ];

    // Set the property group amount for each record.
    if (propertyGroupAmounts != null && propertyGroupAmounts.size() > 0) {
      record.Property_Group_Amount__c = (Decimal)propertyGroupAmounts[0].get('expr0');
    } else {
      // Set the property group amount to 0 if there is no amount.
      record.Property_Group_Amount__c = 0;
    }
  }

  // Update all records with the same value for Property_Group__c.
  List<Pitch__c> matchingRecordsToUpdate = new List<Pitch__c>();
  for (Pitch__c record : records) {
    if (record.Property_Group__c != null) {
      // Get all records with the same value for Property_Group__c.
      List<Pitch__c> matchingRecords = [
        SELECT Id, Property_Group_Amount__c
        FROM Pitch__c
        WHERE Property_Group__c = :record.Property_Group__c
        AND Id != :record.Id
      ];

      // Update the property group amount for all matching records.
      for (Pitch__c matchingRecord : matchingRecords) {
        if (!matchingRecord.IsUpdated__c) {
          matchingRecord.Property_Group_Amount__c = record.Property_Group_Amount__c;
          matchingRecord.IsUpdated__c = true;
          matchingRecordsToUpdate.add(matchingRecord);
        }
      }
    }
  }

  // Update all matching records outside of the trigger context.
  if (!matchingRecordsToUpdate.isEmpty()) {
    update matchingRecordsToUpdate;
  }
}

Apex Class
public class RecursiveTriggerHandler{
public static Boolean isFirstTime = true;
}

Hi,
i have a trigger on the emailMessage object. I have a removeReplyText method that searches for some strings inside the TextBody and Htmlbody of the emailMessage object and deletes/hides it in order to streamline the display of the email when it is copied/stored on a case
 

private static void removeReplyText(List<EmailMessage> newObjects){
        Map<Id, Case> casesMap;
        Set<Id> caseIds = new Set<Id>();
        List<EmailMessage> emsToUpdate = new List<EmailMessage>();
        for(EmailMessage em : newObjects){
            System.debug('Clean body: ' + em.Id + ' - Parent: ' + em.ParentId);
            System.debug('Clean TXT: ' + em.TextBody);
            System.debug('Clean HTML: ' + em.HtmlBody);
            

            if(em.ParentId != null){
                caseIds.add(em.ParentId);
            }
        }
        casesMap = new Map<Id, Case>(getCases(caseIds));
        System.debug('CaseMap' +casesMap);
        
        

        for(EmailMessage em: newObjects){
            Case myCase = casesMap.get(em.ParentId);
            Boolean changed = false;
            if(myCase != null){
                System.debug('Found case');
                String body = em.TextBody;
                if(String.isNotBlank(em.TextBody)) {
                    Integer occurrence1 = body.indexOfIgnoreCase(Constants.EMAIL_QUOTEDBODY_1);
                    Integer occurrence2 = body.indexOfIgnoreCase(Constants.EMAIL_QUOTEDBODY_2);
                    Integer occurrence = occurrence1 != -1 && occurrence2 != -1 && occurrence1 < occurrence2 ? occurrence1 : occurrence2;

                    //system.debug('occurrence3' +occurrence3);

                    if (occurrence != -1) {
                        body = body.substring(0, occurrence);
//                        em.TextBody = body;
                        changed = true;
                    }
                    
        
                    system.debug('Constants.EMAIL_FooterPlain' +Constants.EMAIL_FooterPlain);

                    Integer occurrenceFooter = body.indexOfIgnoreCase(Constants.EMAIL_FooterPlain);
                    if (occurrenceFooter != -1) {
                        body = body.substring(0, occurrenceFooter);
//                        em.TextBody = body;
                        changed = true;
                    }
                }

                String htmlBody = em.HtmlBody;
                if(String.isNotBlank(em.HtmlBody)) {
                    System.debug('HTML Body');
                    Integer occurrenceh1 = htmlBody.indexOfIgnoreCase(Constants.EMAIL_QUOTEDBODY_1);
                    System.debug('occurrenceh1: ' + occurrenceh1);

                    Integer occurrenceh2 = htmlBody.indexOfIgnoreCase(Constants.EMAIL_QUOTEDBODY_2);
                    System.debug('occurrenceh2: ' + occurrenceh2);
                    

                    Integer occurrenceh = occurrenceh1 != -1 && occurrenceh2 != -1 && occurrenceh1 < occurrenceh2 ? occurrenceh1 : occurrenceh2;
                    System.debug('occurrenceh: ' + occurrenceh);
                    
                        

                    if (occurrenceh != -1) {
                        htmlBody = htmlBody.substring(0, occurrenceh);            
                        htmlBody += '</body> </html>';
//                        em.HtmlBody = htmlBody;
                        System.debug('new em.HtmlBody: ' + em.HtmlBody);
                        changed = true;
                    }
                    
                
                    system.debug('Constants.EMAIL_FooterHTML' +Constants.EMAIL_FooterHTML);

                    Integer occurrenceFooter = htmlBody.indexOfIgnoreCase(Constants.EMAIL_FooterHTML);
                    if (occurrenceFooter != -1) {
                        htmlBody = htmlBody.substring(0, occurrenceFooter);
//                        em.TextBody = body;
                        changed = true;
                    }
                }
                if (changed){
                    emsToUpdate.add(new EmailMessage(Id=em.Id, TextBody=body, HtmlBody=htmlBody));
                }

            }
        }

        update emsToUpdate;
    }
now I would like to modify this method to be able to delete/hide this initial piece as well :
Rif. Preventivo {{{Quote.Name}}} ({{{Quote.IdPreventivo__c}}})
Stato: {{{Quote.TranslatedStatus__c}}}
Mittente: {{{Sender.Name}}}



how could I do? is it possible to do this? I initially did a test with replace and replaceAll but without success.

Thanks for any help
I am  writing my first APEX class and I need some high level help if anyone is willing.  This is what I am trying to accomplish:

Org is an NPSP org.  Using the Salesforce Labs Event package to house events.  Events have associated Registration records. There is a custom field on the Contact record containing a Strava Member Id. I would like to build an APEX class that makes a call out to the Strava API and query the organization Strava Club with the Club Id Number. 

I would like to return Strava data for club members who have an active Registration for the Event. If they have a registration then I want to return Strava member data for the time period associated with the event. If the Strava Activity record exists, then update the record, if not create the record.  The record should be related with a master detail relationship with the Event Registration.

I anticipate this class being executed manually with a Lightning Component on the Event Lighting Page. 

I have attempted to write this but can't seem to pull it all together.  If anyone wants to take a look I can post the Strava Class and Helper classes that I have. 

I guess I am looking for Highlevel steps on what best practices are to accomplish this to make sure I am on the right track.  Hopefully this is detailed enough.  Thanks for any thoughts.
This is my code
 
public without sharing class AS_GroupDatatableSourceCollection {

    @InvocableMethod(label = 'Groups Action')
    public static List<Response> getResults( List<Request> parserInput ) {


        // My Group
        List<Id> myGroupIds                     = new List<Id>();
        List<CollaborationGroupMember> cgmList  = [SELECT CollaborationGroupId FROM CollaborationGroupMember WHERE MemberId = :parserInput[0].user_id];
        for ( CollaborationGroupMember cgm : cgmList ) {
            myGroupIds.add(cgm.CollaborationGroupId);
        }
        system.debug('myGroupIds>>>' +myGroupIds);
        // Public
        
        List<Id> publicGroupIds                 = new List<Id>();
        for ( CollaborationGroup cg : [SELECT Id FROM CollaborationGroup WHERE CollaborationType = 'Public' AND Id NOT IN :myGroupIds] ) {
            publicGroupIds.add(cg.Id);
        }

        system.debug('publicGroupIds>>>' +publicGroupIds);
        // Same Type Groups
        List<AS_Membership_Groups__c> listmg    = Database.query('SELECT Id, Name, AS_Type__c, AS_Group_Id__c, AS_Paid__c, AS_Status__c FROM AS_Membership_Groups__c WHERE AS_Type__c INCLUDES (\''+ parserInput[0].type +'\')');
        List<Id> collabGroupsFromMG             = new List<Id>();
        // For eacgh membership groups, parse and store all into a single collection
        for (AS_Membership_Groups__c mg : listmg) {
            
            if ( ! String.isBlank( mg.AS_Group_Id__c ) ) {

                collabGroupsFromMG.addAll( mg.AS_Group_Id__c.split(',') );
            }
        }

        List<Id> myGroupTypeIds                 = new List<Id>();
        for ( CollaborationGroup cg : [SELECT Id FROM CollaborationGroup WHERE Id IN :collabGroupsFromMG AND Id NOT IN :myGroupIds] ) {
            myGroupTypeIds.add(cg.Id);
        }
        system.debug('myGroupTypeIds>>>' +myGroupTypeIds);


        Response res                            = new Response();
        res.myGroups                            = myGroupIds;
        res.eligibleGroups                      = myGroupTypeIds;
        res.publicGroups                        = publicGroupIds;

        List<Response> resList                  = new List<Response>();
        resList.add(res);

        return resList;
    }
        

    public class Request {

        @InvocableVariable
        public String type;
        
        @InvocableVariable
        public String user_id;

    }

    public class Response {
        @InvocableVariable
        public List<Id> myGroups;
        
        @InvocableVariable
        public List<Id> eligibleGroups;

        @InvocableVariable
        public List<Id> publicGroups;

        @InvocableVariable
        public List<String> parsedCollectionOfStrings;
    }
}

Thanks in advance
Hello Developers, I have apex class which consists of 2 queries and I want to merge it inside wrapper class.
here's my class
public class NonBillableReport {

    @AuraEnabled
    public static List<Event> getNonBillable(){
    List<Event> nonBill = [Select Subject, Id, Facilities__c, Services__c, Appointment_Status__c, OwnerId, WhoId,
             ActivityDateTime, ActivityDate, WhatId, Facilities__r.Address_1__c,Facilities__r.City__c, Facilities__r.Name,Facilities__r.Country__c, Sup_Provider__c,Sup_Provider__r.Name, Owner.FirstName, Owner.MiddleName, Owner.LastName,
EndDateTime, Facilities__r.State__c,
Sup_Provider__r.Provider_Role__c FROM Event WHERE IsRecurrence = false AND Appointment_Status__c = 'Non-Billable' LIMIT 100];
 return nonBill;

 List<Session> SessionRecords = [Select Case_Number__c,Case_Number__r.Client_Insurance__c,      Case_Number__r.Total_Amounts__c,Case_Number__r.Client_Insurance__r.Insurance_Type__c,Case_Number__r.Client_Insurance__r.Insured_ID__c,       Client_Name__c,Case_Number__r.Patient_Customer__r.Client_ID__c,Case_Number__r.Patient_Customer__r.DOB__c,Insurance_Name__c,     Case_Number__r.InsuranceType__c,Case_Number__r.Claim_ID__c,Case_Number__r.Insurance__r.Payer_Id__c,Case_Number__r.Insurance__r.Name,From_DOS__c,Case_Number__r.Location_Name__c,Case_Number__r.Facility_Type__c,Case_Number__r.Provider_Name__c,Case_Number__r.Provider__c,   Case_Number__r.Authorization_Number__c, Authorization_Number__c,Case_Number__r.CaseNumber , Procedure_Code__c,Modifier1__r.Name,Modifier2__r.Name,Modifier3__r.Name,Modifier4__r.Name ,Unit_Count__c, Case_Number__r.Billed_Amount__c,       Practice_Fee__c,Case_Number__r.Status,Case_Number__r.First_Bill_Date__c,Case_Number__r.Last_Bill_Date__c, ICD_Code__c,     	NDC_Code__c,NDC_Unit_Price__c,Unit_of_Measure__c,Case_Number__r.Unit__c,Case_Number__r.FacilitiesV3__c, 
Audit_Status__c,lastModifiedBy.Name, lastModifiedDate,PracticeFee__c FROM Case_Line_Item__c limit 10];
     }
}
Please help me or suggest if something is incorrect
 
we have an AutoCallController which uses StandardController sc to autocall whenever a user opens that record, but i need to prevent when redirect occur from Bell Icon notification of that record..pls help
Hello Friends. I hope you're well.
I'm new in Apex so I would like to have your input regarding how to handle this requirement that I have to complete.

A new CustomObject that will be created in order to be filled with records that represents update instructions that needs to be performed. The Custom Object will have the following fields: SObject (were the update is to be performed), the SObjectID (ID of the record), Field (Name of the field in the SObject) and Value (Value to be applied in the update).

So, if the user adds the following record in the Custom Object:
sObject - Account
SObjectID - 221hdi21u213
Field - Name
Value - David

The process when is executed (it will be scheduled), the record is fetched and a update will performed in Account (to change the value for the field Name, for the record ID 221hdi21u213)

In this case, I know that I need a Scheduler Apex class and Batchable class. Since the aim is to be flexible and be able to add multiple records (and multiple objects), what should be the best approach to handle this?

Thanks a lot!

 
  • March 09, 2023
  • Like
  • 0

We have a managed package that contains a few global interface classes. These classes are extended within the package but can also be extended after installation in the target org.

These interfaces are chained.

Interface D extends interface C extends interface B extends interface A, which is the base Interface. 

And Class D implements interface D
Class C implements interface C
And so on, you get the picture...

All interface classes are used as implementations.

But now we want to add methods to one of the interfaces, let's say B in our example.

This is not possible since we can't add new methods to an interface class. But we need ot inject some methods here for new funcionality.

What would be the best way to go about this? We can't just add them to Class B because we cast the class instances as an instance of the interfaces and then we get an error that object of type interface B doesn't have the method we just added, which makes sense since it's not added to the interface class itself...

I have this Map, and it's on my repository class
 

public Map<Id,List<AggregateResult>> buscaPBsAtivacao(){
        Map<Id, List<AggregateResult>> membroCampanhaMap = new Map<Id, List<AggregateResult>>();
        List<String> Territories= new List<String>{
           'Some Territories Names'
        };
       
        List<AggregateResult> territorioAssociado = [
            SELECT
                Object.Name, //here is the account name
                ObjectId, // here is the account Id
                Territory2Id,
                Territory2.DeveloperName
            FROM
                ObjectTerritory2Association
            WHERE
                Territory2.DeveloperName IN : Territories
            GROUP BY
                Territory2.DeveloperName,
                Object.Name,
                ObjectId,
                Territory2Id  
            ORDER By
                Territory2.DeveloperName
        ];
        for (AggregateResult agr : territorioAssociado) {
            Id objectId = (Id) agr.get('ObjectId');
            if (!membroCampanhaMap.containsKey(objectId)) {
                membroCampanhaMap.put(objectId, new List<AggregateResult>());
            }
            membroCampanhaMap.get(objectId).add(agr);
        }
        System.debug('MembroCampanhaMap -> ' + MembroCampanhaMap);
        return membroCampanhaMap;
    }

and I have a List<Account> with all the accounts (including the ones that are on the membroCampanhaMap). This account list is passed on the function parameter.

I have to iterate over just the accounts that are on the membroCampanhaMap, so there is a way to like to compare these 2 and maybe create a new one with just the needed Accounts?

so I can do what I need with these records.

By the way, I even tried to Query more fields on the membroCampanhaMap, but when I added Object.LastModifiedDate (for example), it says that is an invalid field, with the ones that are on the select working fine

Can we acheive this through lightning component to show the duplicate cases on the bases of Email, Casenumber and in subject if casenumber is mentioned.
Something like this.

User-added image
Thank you in advance

Looking to save SOQL queries in various apex classes. Just wondering if its possible to use a schema or describe method instead of an SOQL query to retrieve them?

Really appreciate any information, help or sample solution.  

Code sample below where I would like to replace the SOQL if possible: 

 

private static Map<String,ID> getQueuesByName(){
        Map<String,ID> queuesByName = new Map<String,ID>();
        
        Set<String> queueNameSet = new Set<String>{Constants.QUEUE_VEHICLES,Constants.QUEUE_GENERAL,
                                                    Constants.QUEUE_CMT_RECONCILIATIONS,Constants.QUEUE_CMT_RECOVERIES,
                                                    Constants.QUEUE_SFLEET_ADMIN,Constants.QUEUE_SFLEET_ACC_MGMT};
        
        List<Group> queues = [
            SELECT 
                Id,DeveloperName 
            FROM 
                Group 
            WHERE 
            Type = 'Queue' AND DeveloperName IN :queueNameSet
        ];

        if (!queues.isEmpty()){
            for(Group queue : queues ) {
                queuesByName.put(queue.DeveloperName, queue.Id);
            }
        }

        return queuesByName;
    }
I am new to Apex, but I have been tasked with sending a Salesforce Custom Object to another Company system. My Class works as expected, but my test class fails due to having a @future method. I did look into the Mock callout classes but those seem to be aimed at getting a fake response but I don't really have any logic based around the response.

My Test Class code coverage is only at 4% because my createRecord method calls the sendCase method which has the Http Callout in it.

So my question is: Do I write the Mock Class for the 'sendCase` method? Or will I need to completely refactor my code?

Any help would be greatly appreciated .

Reference Links
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_restful_http_testing_httpcalloutmock.htm
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_callouts_wsdl2apex_testing.htm
https://hicglobalsolutions.com/blog/how-to-create-a-mock-callout-to-test-the-apex-rest-callout-in-salesforce/

My Class
public without sharing class Processmaker_CreateSiteSurvey {
        
    public string endpoint;
    public string pro_uid;
    public string tas_uid;

    public Processmaker_CreateSiteSurvey() {
        //endpoint = 'https://<redacted>/api/1.0/workflow/cases'; // Prod Processmaker Endpoint
        endpoint = 'https://<redacted>/api/1.0/workflow/cases'; // Dev Processmaker Endpoint
        pro_uid = '308138621584f0518bd8f89094895074';
        tas_uid = '562545883584f060a62b559007702299';
    }

    /*-----------------------------------------
    createRecord() - - Invocable Method
    This methods builds a ProcessMaker case using the invocable variable
    -----------------------------------------*/
    @InvocableMethod (label='Create a New Site Survey')
    public static void createRecord(List<Create_Case_Params> params) {
        
        Processmaker_CreateSiteSurvey p0 = new Processmaker_CreateSiteSurvey();
        PM_SiteSurvey cs1 = new PM_SiteSurvey();
        PM_SiteSurvey.Variables cv1 = new PM_SiteSurvey.Variables();
        List<PM_SiteSurvey.Variables> lcv1 = new List<PM_SiteSurvey.Variables>();
        Processmaker_Case__c fc1 = new Processmaker_Case__c();

        String recordTypeID = [Select Id FROM RecordType WHERE Name = 'Business Site Survey'].Id;

        //Salesforce Field Check Record
        for (Create_Case_Params param: params) {
            String servSelected = string.join(param.surveySelection, ';');
            fc1.Survey_Selection_s__c = servSelected;  
            fc1.SF_User__c = param.lookupUser;
            fc1.SF_Contact__c = param.lookupContact;
            fc1.SF_Account__c = param.lookupAccount;
            fc1.Service_Rep__c = param.origName;
            fc1.Contact_Number__c = param.contactNum;
            fc1.Service_Area__c = param.serviceArea;
            fc1.Submitted_Date__c = param.submitDate;
            fc1.Site_Survey_Scheduled__c = param.sssDate;
            fc1.Site_Survey_Scheduled_Time__c = param.sssTime;
            fc1.Business_Name__c = param.busName;
            fc1.Business_Address__c = param.busAddy;
            fc1.Local_Contact__c = param.localContact;
            fc1.Local_Contact_Phone__c = param.localContactPhone;
            fc1.Other__c = param.surveySelectionOther;
            fc1.Remarks__c = param.remarks;
            fc1.RecordTypeId = recordTypeID;
        }

        try {
            insert fc1;
        } catch (StringException e) {
            System.debug('An error has occurred: ' + e.getMessage());
        }

        //Processmaker Field Check Array
        for (Create_Case_Params param: params) {
            cs1.pro_uid = p0.pro_uid;
            cs1.tas_uid = p0.tas_uid;
            cv1.CustomerSvcFullName = param.origName;
            cv1.CustomerSvcPhone = param.contactNum;
            cv1.ServiceArea = param.serviceArea;
            cv1.ServiceArea_label = param.serviceArea_label; //label
            cv1.SubmitDate = param.submitDate;
            cv1.SubmitDate_label = param.subDate_label; //label
            cv1.ScheduledSiteSurveyDate = param.sssDate;
            cv1.ScheduledSiteSurveyDate_label = param.siteSurveySched_label; //label
            cv1.ScheduledSiteSurveyTime = param.sssDate + ' ' + param.sssTime;
            cv1.ScheduledSiteSurveyTime_label = param.sssTime;
            cv1.BusinessName = param.busName;
            cv1.BusinessAddress = param.busAddy;
            cv1.BusinessLocalContact = param.localContact;
            cv1.BusinessContactTelephone = param.localContactPhone;
            cv1.SurveySelection = param.surveySelection;
            String surveySelection_label = json.serialize(param.surveySelection_label);
            cv1.SurveySelection_label = surveySelection_label; //label
            cv1.SelectionOther = param.surveySelectionOther;
            cv1.SelectionOther_label = param.surveySelectionOther;
            cv1.RequestRemarks = param.remarks;
            cv1.SalesforceRecordID = fc1.Id;
            cv1.CustomerSvcUserID = [SELECT SamAccountName__c FROM User WHERE Id = :param.lookupUser].SamAccountName__c;
            lcv1.add(cv1);
            cs1.variables = lcv1;
        }
        sendCase(json.serialize(cs1), fc1.Id);
    }

    /*-----------------------------------------
    sendCase() - returns ProcessMaker Response
    This method send the case to Processmaker via HTTP POST Request
    -----------------------------------------*/
    @future(callout = true)
    public static void sendCase(String payload, String recordID) {
        
        Processmaker_CreateSiteSurvey p1 = new Processmaker_CreateSiteSurvey();
        String access_token = Processmaker_Connector.getloginToken();

        try {
            HttpRequest req = new HttpRequest();
            req.setMethod('POST');
            req.setEndpoint(p1.endpoint);
            req.setHeader('Content-Type', 'application/json; charset=utf-8');
            req.setHeader('Authorization', 'Bearer ' + access_token);
            req.setBody(payload);

            Http binding = new Http();
            HttpResponse res = binding.send(req);
            ProcessmakerResponse pr1 = (ProcessmakerResponse) JSON.deserialize(res.getBody(), ProcessmakerResponse.class);
            Processmaker_ExecuteTrigger.executeTrigger(pr1.app_uid, '478587874638e4d6b391802022646525');
            Processmaker_RouteCase.routeCase(pr1.app_uid);
            Processmaker_Case__c caseRecord = new Processmaker_Case__c(
                Id = recordID,
                app_uid__c = pr1.app_uid,
                Case_Number__c = pr1.app_number
            );
            upsert caseRecord; 
            System.debug('Case Creation Successful');
        } catch (StringException e) {
            System.debug('An error has occurred: ' + e.getMessage());
        }
    }

    /*----------------------------------------------
    Create Case Params - Class - Invocable Variables
    This class houses all of the invocalble variables for the createCase() invocable method
    ----------------------------------------------*/
    public class Create_Case_Params {

        @InvocableVariable(label='Originator Name' required=true)
        public String origName; 

        @InvocableVariable(label='Contact Number' required=true)
        public String contactNum; 

        @InvocableVariable(label='Service Area' required=true)
        public String serviceArea; 

        @InvocableVariable(label='Submission Date' required=true)
        public String submitDate; 

        @InvocableVariable(label='Site Survey Scheduled' required=true)
        public String sssDate; 

        @InvocableVariable(label='Siter Survey Scheduled (Time)' required=true)
        public String sssTime; 

        @InvocableVariable(label='Business Name' required=true)
        public String busName; 

        @InvocableVariable(label='Business Address' required=true)
        public String busAddy; 

        @InvocableVariable(label='Local Contact for Business' description='must be AptSelectionApartment, AptSelectionSuite, AptSelectionLot, AptSelectionNA' required=true)
        public String localContact; 

        @InvocableVariable(label='Local Contact Phone' required=true)
        public String localContactPhone; 

        @InvocableVariable(label='Survey Selection' description='values must be SurveySelectionVoIP, SurveySelectionWiring, SurveySelectionKeySystem, SurveySelectionMETS, SurveySelectionZipstream' required=true)
        public List<String> surveySelection;
        
        @InvocableVariable(label='Survey Selection Other')
        public String surveySelectionOther;

        @InvocableVariable(label='Remarks' required=true)
        public String remarks;

        //Labels
        @InvocableVariable(label='Label: Survey Selection')
        public List<String> surveySelection_label;

        @InvocableVariable(label='Label: Site Survey Date Scheduled')
        public String siteSurveySched_label;

        @InvocableVariable(label='Label: Site Survey Time Scheduled')
        public String siteSurveySchedTime_label;

        @InvocableVariable(label='Label: Service Area')
        public String serviceArea_label;

        @InvocableVariable(label='Label: Submission Date')
        public String subDate_label;

        //Salesforce Fields
        @InvocableVariable(label='Account' )
        public String lookupAccount;

        @InvocableVariable(label='Contact' )
        public String lookupContact;

        @InvocableVariable(label='User' )
        public String lookupUser;
    }
}


My Test Class
@isTest
public without sharing class Processmaker_CreateSiteSurveyTest {
    
    public Processmaker_CreateSiteSurveyTest() {

    }

    //--------Data Generation

    @isTest
    public static List<Processmaker_CreateSiteSurvey.Create_Case_Params> createTestData() {

        //Create a test Account
        Account testAccount = new Account(
            Name = 'Salesforce Testing',
            Phone = '0123456789',
            BillingStreet = '123 Fake Street',
            BillingCity = 'Fake City',
            BillingState = 'Fake State',
            BillingPostalCode = '12345',
            BillingCountry = 'Fake Country'
        );
        insert testAccount;

        //Create a test Contact
        Contact testContact = new Contact(
            FirstName = 'Salesforce',
            LastName = 'Testing',
            Phone = '0123456789',
            AccountId = testAccount.Id
        );
        insert testContact;
        
        //Get the User, Account and Contact IDs
        String testSFUser = [SELECT Id FROM User WHERE Name = 'Nigel Dendy'].Id;

        //Create Case Params
        List<Processmaker_CreateSiteSurvey.Create_Case_Params> caseParams = new List<Processmaker_CreateSiteSurvey.Create_Case_Params>();
        Processmaker_CreateSiteSurvey.Create_Case_Params caseParam = new Processmaker_CreateSiteSurvey.Create_Case_Params();
        caseParam.origName = 'Salesforce Testing';
        caseParam.contactNum = '0123456789';
        caseParam.serviceArea = 'ServiceAreaRKHL';
        caseParam.submitDate = '2023-02-16';
        caseParam.sssDate = '2023-02-21';
        caseParam.sssTime = '08:24';
        caseParam.busName = 'TestBusinessName';
        caseParam.busAddy = '123 Fake Address';
        caseParam.localContact = 'Bob Barker';
        caseParam.localContactPhone = '0123456789';
        caseParam.surveySelection = new List<String>{'SurveySelectionVoIP','SurveySelectionWiring'};
        caseParam.surveySelectionOther = 'CustomRequest';
        caseParam.remarks = 'blah blah blah blah blah';

        //Labels
        caseParam.surveySelection_label = new List<String>{'VoIP','Wiring'};
        caseParam.siteSurveySched_label = '2023-02-21';
        caseParam.siteSurveySchedTime_label = '08:24';
        caseParam.serviceArea_label = 'ServiceAreaRKHL';
        caseParam.subDate_label = '2023-02-16';

        //Salesforce Fields
        caseParam.lookupAccount = testAccount.Id;
        caseParam.lookupContact = testContact.Id;
        caseParam.lookupUser = testSFUser;

        caseParams.add(caseParam);

        return caseParams;
    }

    //--------Tests

    @isTest
    public static void Processmaker_CreateSiteSurveyTest() {
        Processmaker_CreateSiteSurvey testClass = new Processmaker_CreateSiteSurvey();
    }

    @isTest
    public static void createCaseTest() {
        List<Processmaker_CreateSiteSurvey.Create_Case_Params> testClass = createTestData();
        Processmaker_CreateSiteSurvey.createRecord(testClass);
    }
}

 
Users are not permitted to approve a record that they have submitted themselves for approval Trigger on this scenario 

Hi dear community,

I'm trying to schedule a batch apex class several time at the same start time.

I pass a parameter to my apex batch class : 

TBR_APB026_SendSMS batch = new TBR_APB026_SendSMS(partner);

And then the parameter is use to filter the data in my queryLocator :

AND ServiceTerritory.TopLevelTerritory.TBR_Partner__r.Name =: partner

 

However, when I try to schedule several instance of this apex batch class with different values in the parameter, at the same time, with the code bellow : 
 

Set<String> partners = new Set<String>{'PARTNER_A','PARTNER_B','PARTNER_C'};
for(String partner : partners){
    TBR_APB026_SendSMS batch = new TBR_APB026_SendSMS(partner);
    String sch = '0 15 10 14 2 ?';
    system.schedule('TBR_APB026_SendSMS_' + partner, sch, batch);
}

 

After that, only the first one scheduled batch class is executed, and the two others are not event started.

 

hello

   i write a test method for a controller.but i get only  71% code coverage.

  i am facing  problem to write the test method for get set method.please help me

 here is my code:
public class eiException extends exception{
    public String code{get; set;}
    public String text{get; set;}
    public String severity{get; set;}
    public String category{get; set;}
    public String subcategory{get; set;}
    public String dataState{get; set;}
    public Boolean retryAllowed{get; set;}
    public String additionalInformation{get; set;}
    
    public eiException(Dom.XmlNode node){
        dom.XmlNode p;
        
        p=node.getChildElement('code', eiEnvelope.namespace);
        if(p != null){code = p.getText();}
        
        p=node.getChildElement('text', eiEnvelope.namespace);
        if(p != null){text = p.getText();}
        
        p=node.getChildElement('severity', eiEnvelope.namespace);
        if(p != null){severity = p.getText();}
        
        p=node.getChildElement('category', eiEnvelope.namespace);
        if(p != null){category = p.getText();}
        
        p=node.getChildElement('subcategory', eiEnvelope.namespace);
        if(p != null){subcategory = p.getText();}
        
        p=node.getChildElement('dataState', eiEnvelope.namespace);
        if(p != null){dataState = p.getText();}
        
        p=node.getChildElement('retryAllowed', eiEnvelope.namespace);
        if(p != null){retryAllowed = p.getText().equalsIgnoreCase('true');}
        
        p=node.getChildElement('additionalInformation', eiEnvelope.namespace);
        if(p != null){additionalInformation = p.getText();}
        
    }
    
    public static testmethod void testeiException() {
    
        
        DOM.Document doc = new DOM.Document();
        dom.XmlNode envelope= doc.createRootElement('Envelope',null,null);
        dom.XmlNode body= envelope.addChildElement('code', null, null);

        eiException eiEx = new eiException(body);
      
    }
}
I have below requirment - 
Train and Coach are 2 objects. Where I need to build logic based on train schedule and availibility. From UI side admin can add the coach to the train. 

Train (Parent Object - From, To, Timings)
Coach (Child Object - From, To, Timings) Field is there. 

Now from UI side when user book the tickets. based on given 3 fields I need to add coachs in the train. lets say next week on monday there will 3 trains are schedule from X to Y location. now today we see many passanger book the train from X to Y location. so basically, based on timings I need to add number of coaches in next week train so I can accomodate all customers. Its not like 1 train run with 5-6 coach, while other train runs with 30-35 coach. there has to balance. 

Please let me know if need further clarification in scenario. 
I have a  batch class which is running everyday and checks if the contract status is Activated or not if activated then it creates the order and its products.

1. Get the everyday logs on batch runs and number of order created and its status.

2. In case batch did not run due to any issue(exceptions)  that also needs to be notified.

Can I get any help how to achieve on this.

Thanks

I'm trying to start a flow that receives a record collection as input.

I have the following code:

List<YB_Dosage_Line__c> parsedDosagelines =(List<YB_Dosage_Line__c>)JSON.deserializeStrict(serializedApplicationRecord,List<YB_Dosage_Line__c>.class);
                
                Map<String, Object> flowParams = new Map<String, Object>{'dosageLines' => parsedDosagelines};
    
                Flow.Interview.YB_Dosage_Lines_Process_Related_Generic_Group_and_Product_Family flowInstance = new Flow.Interview.YB_Dosage_Lines_Process_Related_Generic_Group_and_Product_Family(flowParams);
    
flowInstance.start();

But, it throws the following error:

Malformed JSON: Expected '[' at the beginning of List/Set
Any ideas?
I have a trigger and i am trying to create a test class. But not sure how to write test class to fulfill the test coding coverage for test apex class


TRIGGER:



trigger opportunitytrigger on opportunity(after update){
    Set<Id> oppIds = new Set<Id>();
   // Set<Id> oppWithContractAgreement = new Set<Id>();
     List<APXT_Redlining__Contract_Agreement__c> oppWithContractAgreement = new List<APXT_Redlining__Contract_Agreement__c>();
     List<Opportunity> opportunity = new List<Opportunity>();
     
    for(opportunity opp:Trigger.new)
    {
        if(opp.Stagename=='Closed Won')
        {
            oppIds.add(opp.id);
            opportunity.add(opp);

        }

    }

List<APXT_Redlining__Contract_Agreement__c> con =[Select Id, Opportunity__c,APXT_Redlining__Status__c,Verified_Signed_IO__c from APXT_Redlining__Contract_Agreement__c  where Opportunity__c IN :oppIds];
    
    {
     if(con.size()>0)
     system.debug(+con.size());
      
      {
          for(APXT_Redlining__Contract_Agreement__c c :con)
          
          {
          if( c.APXT_Redlining__Status__c == 'Active' && c.Verified_Signed_IO__c ==FALSE){
            oppWithContractAgreement.add(c);
            system.debug('-----------'+oppWithContractAgreement.size());
            }
}
      }
    }

 For(Opportunity opps:opportunity)
 {
    if(oppWithContractAgreement.size()>0)
    {
        system.debug(oppWithContractAgreement.size());
        opps.addError('Closed Won Opportunity must need to have active contract agreement and customer signed date captured or Closed Won Opportunity must need to have active contract agreement');
    }
    
    if(con.size()==0)
    {
        opps.addError('Closed Won Opportunity must need to have contract agreement' );
    }
    
 }

}


TEST CLASS:

@isTest
private class OpportunityTriggerHandler1_Test {
    
    @isTest static void testCreateOpportunityTarget() {
        
        //create Account
        Account acc = new Account();
        acc.Name = 'Test Account';
        insert acc;
        
        
        Test.startTest();
        
        Opportunity opp = new Opportunity();
        opp.AccountId = acc.Id;
        opp.Name = 'Test Opportunity';
        opp.StageName = 'Closed Won';
        opp.CloseDate = Date.Today().addDays(20);
        insert opp;
        
        Test.stopTest();
        
        List<APXT_Redlining__Contract_Agreement__c> CA = new List<APXT_Redlining__Contract_Agreement__c>();
        CA = [Select Id, Opportunity__c,APXT_Redlining__Status__c,Verified_Signed_IO__c from APXT_Redlining__Contract_Agreement__c ];

        System.assert(CA[0].Opportunity__c == opp.Id); 
    }      
}
Hi, good morning, I get the following error in the logs "Error message: List index out of bounds: 0" on line 52 of the code. 
This is the code of line 52, how can I validate or how can I fix the error?
 
new CampaignMembersService_SV().constructRegistrantCampaignMember(regData.optIn, newCon,ProfHubEmailSendSelector_SV.newInstance().selectByMasterLabel(new Set<String> {countryMap.get(regData.country)})[0].Communication_Optin__c, uow);

Thanks!
trigger CountContacts on Contact (after insert, after delete) {
List<Account> addAccCount= new List<Account>();
    Set<Id> addConId= new Set<Id>();
if(trigger.isInsert){
for(Contact con:trigger.new){
addConId.add(con.AccountId);
}
}
if(trigger.isDelete){
for(Contact con:trigger.old){
addConId.add(con.AccountId);
}
}
List<Account> accList=[SELECT Id,CountofContacts__c, (SELECT Id FROM Contacts) FROM Account WHERE Id in: addConId];
for(Account acc:accList){
acc.CountofContacts__c = acc.Contacts.size();
addAccCount.add(acc);
}
Update addAccCount;
}
if(trigger.isDelete){
for(Contact con:trigger.old){
addConId.add(con.AccountId);
}
}
List<Account> accList=[SELECT Id,CountofContacts__c, (SELECT Id FROM Contacts) FROM Account WHERE Id in: addConId];
for(Account acc:accList){
acc.CountofContacts__c = acc.Contacts.size();
addAccCount.add(acc);
}
Update addAccCount;
}
Create two Objects say Teacher(Parent) and Student(Child) having similar fields. On creating record of Teacher, associated student record should be created and vice versa. Additionally, updates should also be in sync i.e. updating the parent should reflect in the child and vice versa.
I want to do this with the help of salesforce flow how to do that?

Thanks
Hello Everyone ,
I need to convert MS to Dasy:hh:mm:ss in lwc. I tried below code it is givng me days in decimal which I dnot want. Can anyone please help me on the same.
msToTime(s) {
        var ms = s % 1000;      
        s = (s - ms) / 1000;
        var secs = s % 60;

        s = (s - secs) / 60;
        var mins = s % 60;

        s= (s - mins) / 60;
        var hrs = s % 60;
        var hrs = (s - mins) / 60;

        var days = (s-hrs) / 24;

        var timer = '';
        if(days && days>0){
            timer = days +' days ';
        }
        
        if(hrs && hrs>0){
            timer = timer + hrs +' hr ';
        }
        if(mins && mins>0){
            timer = timer + mins +' min ';
        }
        if(secs && secs>0){
            timer = timer + secs +' sec ';
        }
        return timer;
      }
}

 

Hi all,

I am a novice, looking to write a test class for a redirect.
 

public class RedirectController {
    public String itemName { get; set; }
    public String externalID { get; set; }
    public String SFID { get; set; }

    public Client ac { get; set; }
    public License lic { get; set; }
    public Opportunity opp { get; set; }

    public RedirectController() {
        itemName = ApexPages.currentPage().getParameters().get('itemName');
        externalID = ApexPages.currentPage().getParameters().get('externalID');

        if (itemName == 'Client') {
            ac = [SELECT Id FROM Client__c WHERE extid_client__c = :externalID limit 1];
            SFID = ac.Id;
        }

        if (itemName == 'License') {
            lic = [SELECT Id FROM License__c WHERE extid_license__c = :externalID limit 1];
            SFID = lic.Id;
        }
        
        if (itemName == 'Opportunity') {
            opp = [SELECT Id FROM Opportunity WHERE extid_opportunity__c = :externalID limit 1];
            SFID = opp.Id;
        }
    }

    public PageReference redirect() {
        PageReference pageRef = new PageReference('/' + SFID);
        pageRef.setRedirect(true);
        return pageRef;
    }

}

The VF page is then:

<apex:page controller="RedirectController" action="{!redirect}">
</apex:page>

The above all works, but I can't deploy to Production without a test class and I am not even sure what I am testing, I've written them before with dummy data, but this one has be a bit confused.

Any direction would be greatly appreciated!

Hi,

I am trying to send an email, whenever there is an update on contact field. I am able to access the con.email but not con.name. In the body, I am trying to use the contact name(tried firstname, lastname - both has values in it), which is returning null. Any suggestions will appriciated.User-added imageUser-added image
@isTest 

private class ListViewControllerTest {
    /**This is the list which will be passed to Visualforce Page and in turn passed to Flow from Visualforce**/
    public List<Matching_Facility__c> LstSelectedFacilities { get; set; }
    
  

    public ListViewControllerTest(ApexPages.StandardSetController listcontroller) {
      
        Set<Id> facilitySelectedIds = new Set<Id>();
        LstSelectedFacilities = new List<Matching_Facility__c>();
            
        for (Matching_Facility__c f : (Matching_Facility__c[])listcontroller.getSelected()) {
            facilitySelectedIds.add(f.Id);
        }

        /**Querying on the Selected records and fetching fields which are required in Flow **/
        LstSelectedFacilities = [SELECT Id,  Client_Search__c FROM Matching_Facility__c WHERE Id IN :facilitySelectedIds];
    }
}

Need code coverage to depoy, but cannot test.
I need to insert key of map as parent objects and value of map as child object. 
Map<Case,List<Case>> parentChildMap = new Map<Case,List<Case>>();

How can we do this?
  • May 04, 2023
  • Like
  • 0

Hi everyone,

I do a lot of work that involves the Opportunity object, along with the attached Price Book, Product, and Opportunity Product objects.

Because these objects and their relationships can get kind of complicated (especially creating standard and custom Price Book entries for each Product before creating an Opportunity Product), I want to create an Apex Class that will generate this data when needed. That way I can call the necessary data whenever I run a new test, instead of adding that code into each new Apex test class I create.


This is what I have so far, but I'm unsure if I'm on the right track:

@isTest
public class OpportunityDataGenerator {
    
    // create test data
    @testSetup public static void createOpportunityData() {
        // create standard price book
        Pricebook2 stdPricebook = new Pricebook2(
            Name = 'Standard Price Book', 
            IsActive = true
        );
        insert stdPricebook;
        
        // create custom price book
        Pricebook2 customPricebook = new Pricebook2(
            Name = 'Custom Price Book', 
            IsActive = true
        );
        insert customPricebook;
        
        // create product with standard price book and custom price book entries
        Product2 product = new Product2(
            Name = 'Test Product',
            ProductCode = 'TEST001',
            IsActive = true
        );
        insert product;
        
        // add standard price book entry for the product
        PricebookEntry stdPricebookEntry = new PricebookEntry(
            Pricebook2Id = stdPricebook.Id,
            Product2Id = product.Id,
            UnitPrice = 100.0,
            IsActive = true
        );
        insert stdPricebookEntry;
        
        // add custom price book entry for the product
        PricebookEntry customPricebookEntry = new PricebookEntry(
            Pricebook2Id = customPricebook.Id,
            Product2Id = product.Id,
            UnitPrice = 150.0,
            IsActive = true
        );
        insert customPricebookEntry;
        
        // create account with Client_Type__c field
        Account account = new Account(
            Name = 'Test Account',
            Client_Type__c = 'Associate'
        );
        insert account;
        
        // create opportunity related to the account
        Opportunity opportunity = new Opportunity(
            Name = 'Test Opportunity',
            StageName = 'Prospecting',
            CloseDate = Date.today(),
            AccountId = account.Id
        );
        insert opportunity;
        
        // create opportunity product related to the opportunity and the product
        OpportunityLineItem opportunityProduct = new OpportunityLineItem(
            OpportunityId = opportunity.Id,
            PricebookEntryId = customPricebookEntry.Id,
            Quantity = 10,
            UnitPrice = customPricebookEntry.UnitPrice
        );
        insert opportunityProduct;
    }
}
What is the soql query to get userid of a active user .
'Could not fetch Java version from path C:\Program Files\Java\jdk1.8.0_333. Reason: spawn C:\Program Files\Java\jdk1.8.0_333\bin\java ENOENT'

I have set the environment variable to jdk11 path, and I am able to run the java files but not sfdx scanner.

Any help would be really appreciated.

Thanks in advance.
Any one please advise me how to write a trigger that will send an email to alert when that record is created or updated or deleted.
Need to create a formula feed that should redirect to "Contact" page on clicking the Hyperlink.
public class AksChecklist 
{
   // public Eagle_Arrangement__c agr{get;set;}
    public Internal_Risk_Rating_Detail__c irr{get;set;}
    public AKS_Checklist_AGR__c aksrec{set;get;}
    public integer i=0;
   // public Id agreementid{get;set;}
    public Id internalid{get;set;}
    
    Id recordTypeId = [Select Id,Name from RecordType where Name='Consulting Arrangement' and SOBjectType='Eagle_Arrangement__c'].Id;
   // public id recordtype{set;get;}
    public AksChecklist(apexpages.StandardController cont)
        
    {
      aksrec=(AKS_Checklist_AGR__c)cont.getRecord();
        system.debug('aksid'+aksrec);
        internalid=ApexPages.currentPage().getParameters().get('irrid');
        if(aksrec!=null && aksrec.id!=null){
           
            aksrec=[select id,name,Createddate__c ,LastModifiedDate__c,LastModifiedBy.name,CreatedBy.name,Internal_Risk_Details__c,Internal_Risk_Details__r.Arrangement__c,Internal_Risk_Details__r.Arrangement__r.recordtype.name,Respond_to_Question_1__c,Internal_Risk_Details__r.Arrangement__r.Agreement_Sub_Type__c ,
                    Respond_to_Question_2__c,Respond_to_Question_3__c,Respond_to_Question_4__c,Respond_to_Question_5__c,Respond_to_Question_6__c,Respond_to_Question_7__c,Respond_to_Question_8__c,Respond_to_Question_9__c,Respond_to_Question_10__c,Respond_to_Question_11__c from AKS_Checklist_AGR__c where id=:aksrec.id]; 
            internalid=aksrec.Internal_Risk_Details__c;
        }
        irr=[select id,name,legal_AKS_confirmation__c,Arrangement__c,Arrangement__r.name,Arrangement__r.Agreement_Sub_Type__c,Arrangement__r.Recordtype.name,Arrangement__r.ROD__c,Arrangement__r.DVP__c,Arrangement__r.Status__c,Arrangement__r.Next_Approver__c from Internal_Risk_Rating_Detail__c where id=:internalid];
       // system.debug(irr.Arrangement__r.Recordtype.name);
         
      // this.agreementid=ApexPages.currentPage().getParameters().get('agrid');
          // agr=[Select Id,ROD__c,DVP__c ,Status__c, Next_Approver__c,recordtype.name from Eagle_Arrangement__c where id=:agreementid];
  
    }
    public pagereference divert(){
        PageReference pr=new PageReference('/apex/akschecklistredirection');//other developer page url here
       if(irr.Arrangement__r.recordtype.name=='RS Lease' || irr.Arrangement__r.recordtype.name=='Settlement' || irr.Arrangement__r.recordtype.name=='other'|| irr.Arrangement__r.recordtype.name=='Consulting Arrangement' || irr.Arrangement__r.recordtype.name=='Hospital Services Arrangement' || irr.Arrangement__r.recordtype.name=='SNF HHD Coordination Agreement' || irr.Arrangement__r.recordtype.name=='MDA' || irr.Arrangement__r.recordtype.name=='Sublease Remediation' || irr.Arrangement__r.recordtype.name=='Patient Pathways' ){//add othe record types here 
            pr=null;
        }
        return pr;
    }
    public pagereference divert1(){
        PageReference pr=new PageReference('/apex/akschecklistredirectionview');//other developer page url here
       if(irr.Arrangement__r.recordtype.name=='RS Lease' || irr.Arrangement__r.recordtype.name=='Settlement' || irr.Arrangement__r.recordtype.name=='other'|| irr.Arrangement__r.recordtype.name=='Consulting Arrangement' || irr.Arrangement__r.recordtype.name=='Hospital Services Arrangement' || irr.Arrangement__r.recordtype.name=='SNF HHD Coordination Agreement' || irr.Arrangement__r.recordtype.name=='MDA' || irr.Arrangement__r.recordtype.name=='Sublease Remediation' || irr.Arrangement__r.recordtype.name=='Patient Pathways'){//add othe record types here 
           pr=null;
        }
        return pr;
    }
     public pagereference divert2(){
        PageReference pr=new PageReference('/apex/akschecklistredirectionedit');//other developer page url here
       if(irr.Arrangement__r.recordtype.name=='RS Lease' || irr.Arrangement__r.recordtype.name=='Settlement' || irr.Arrangement__r.recordtype.name=='other'|| irr.Arrangement__r.recordtype.name=='Consulting Arrangement' || irr.Arrangement__r.recordtype.name=='Hospital Services Arrangement' || irr.Arrangement__r.recordtype.name=='SNF HHD Coordination Agreement' || irr.Arrangement__r.recordtype.name=='MDA' || irr.Arrangement__r.recordtype.name=='Sublease Remediation' || irr.Arrangement__r.recordtype.name=='Patient Pathways'){//add othe record types here 
            pr=null;
        }
        return pr;
    }
   /* public pagereference akspagego()
    {
      PageReference pr=new PageReference('/apex/AksChecklist');
          pr.getParameters().put('varArrangementId',agr.Id);
              pr.getParameters().put('varRecordType',recordTypeId);
              
        pr.getParameters().put('irrid',aksrec.id);
        pr.getParameters().put('retURL',agr.id);
            return pr ;
    }*/
    
        
   
    
    public pagereference save(){
        aksrec.Internal_Risk_Details__c=irr.id;
        if(aksrec.id!=null){
         
                update aksrec;
            //list<AKS_Checklist_AGR__c> akss=[select id,name,Internal_Risk_Details__c,Respond_to_Question_1__c,Respond_to_Question_2__c,Respond_to_Question_3__c,Respond_to_Question_4__c,Respond_to_Question_5__c,Respond_to_Question_6__c,Respond_to_Question_7__c,Respond_to_Question_8__c,Respond_to_Question_9__c,Respond_to_Question_10__c,Respond_to_Question_11__c from AKS_Checklist_AGR__c where Internal_Risk_Details__c=:irr.id];
            //for(AKS_Checklist_AGR__c aksrec1:akss){
            if((aksrec.Respond_to_Question_1__c=='Yes' && aksrec.Respond_to_Question_2__c=='Yes' && aksrec.Respond_to_Question_3__c=='Yes' && aksrec.Respond_to_Question_4__c=='Yes'  && aksrec.Respond_to_Question_5__c=='Yes' && aksrec.Respond_to_Question_6__c=='Yes' && aksrec.Respond_to_Question_7__c=='Yes'  && aksrec.Respond_to_Question_8__c=='Yes'  && aksrec.Respond_to_Question_9__c=='Yes') || (aksrec.Respond_to_Question_10__c=='Yes'  && aksrec.Respond_to_Question_11__c=='Yes'))
            {
                //i++;
                //}
            //}if(akss.size()==i){
            irr.legal_AKS_confirmation__c='Complete';
                  }
            else{
                    irr.legal_AKS_confirmation__c='Not All Affirmative';   
                  }
            update irr;
        }else{
           
            insert aksrec;
 //list<AKS_Checklist_AGR__c> akss=[select id,name,Internal_Risk_Details__c,Respond_to_Question_1__c,Respond_to_Question_2__c,Respond_to_Question_3__c,Respond_to_Question_4__c,Respond_to_Question_5__c,Respond_to_Question_6__c,Respond_to_Question_7__c,Respond_to_Question_8__c,Respond_to_Question_9__c,Respond_to_Question_10__c,Respond_to_Question_11__c from AKS_Checklist_AGR__c where Internal_Risk_Details__c=:irr.id];
            //for(AKS_Checklist_AGR__c aksrec1:akss){
            if((aksrec.Respond_to_Question_1__c=='Yes' && aksrec.Respond_to_Question_2__c=='Yes' && aksrec.Respond_to_Question_3__c=='Yes' && aksrec.Respond_to_Question_4__c=='Yes'  && aksrec.Respond_to_Question_5__c=='Yes' && aksrec.Respond_to_Question_6__c=='Yes' && aksrec.Respond_to_Question_7__c=='Yes'  && aksrec.Respond_to_Question_8__c=='Yes'  && aksrec.Respond_to_Question_9__c=='Yes') || (aksrec.Respond_to_Question_10__c=='Yes'  && aksrec.Respond_to_Question_11__c=='Yes'))
            {
               // i++;
                //}
            //}if(akss.size()==i){
            irr.legal_AKS_confirmation__c='Complete';
                  }
            else{
                    irr.legal_AKS_confirmation__c='Not All Affirmative';   
                  }
            update irr;       
        }
        PageReference pr =new PageReference('/'+irr.id);
       // PageReference pr =new PageReference('/apex/AKSChecklistview?id=aksrec.id');
        
        return pr;
    }

   /* public pagereference aksflow()
    {
      PageReference pr=new PageReference('/flow/AKSChecklist_flow');
          pr.getParameters().put('varArrangementId',agr.Id);
              pr.getParameters().put('varRecordType',recordTypeId);
              
        pr.getParameters().put('irrid',irr.id);
        pr.getParameters().put('retURL',agr.id);
            return pr ;
    }*/
    
    public pagereference closepage()
    {
        pagereference pr1=new pagereference('/'+irr.id);
        return pr1;
    }
     
}
hi,
Whenever the record is deleated the count is not reflecting in the account below is the code

Trigger For_counting_the_CPDrecords on Customer_Policy_details__c (after update,after delete){

 if(trigger.isafter == true && trigger.isdelete == true){

                                 updating_count_of_ploicies_in_Account.Method_for_calucating_when_deleated(trigger.oldMap);

 }
 
 

public class  updating_count_of_ploicies_in_Account {
Public static void Method_for_calucating_when_deleated (map<id,Customer_Policy_details__c> varoldmap){

             map<id,Customer_Policy_details__c>  varmaplist = new map<id,Customer_Policy_details__c>();

                system.debug(varoldmap);
          for(Customer_Policy_details__c varc : varoldmap.values()){

             if(varc.Account__c != null){
                         varmaplist.put(varc.Account__c,varc);
                 system.debug(varmaplist);
         }
              
              
     }
       

       List<Account> Addingrecords = [SELECT id,Expired__c,Active_Policies__c,(SELECT id,Policy_Status__c FROM Customer_Policy_details__r where id in: varoldmap.keyset())
                                      FROM Account WHERE id IN:varmaplist.keyset()];
         system.debug(Addingrecords.size());
    
    if(Addingrecords.size() > 0) {
 for(Account vara : Addingrecords){
  system.debug(Addingrecords);
     
 for(Customer_Policy_details__c a : vara.Customer_Policy_details__r){
     
 system.debug(vara.Customer_Policy_details__r);
               if(a.Policy_Status__c == 'Active'){
                    system.debug(vara.Active_Policies__c);
                  vara.Active_Policies__c -=1;
                 system.debug(vara.Active_Policies__c);
              }
                if(a.Policy_Status__c == 'Expired'){
                 
                        vara.Expired__c -=1;
                 
               }
         }
 }
         update Addingrecords; 
        }
   }
}
hello

   i write a test method for a controller.but i get only  71% code coverage.

  i am facing  problem to write the test method for get set method.please help me

 here is my code:
public class eiException extends exception{
    public String code{get; set;}
    public String text{get; set;}
    public String severity{get; set;}
    public String category{get; set;}
    public String subcategory{get; set;}
    public String dataState{get; set;}
    public Boolean retryAllowed{get; set;}
    public String additionalInformation{get; set;}
    
    public eiException(Dom.XmlNode node){
        dom.XmlNode p;
        
        p=node.getChildElement('code', eiEnvelope.namespace);
        if(p != null){code = p.getText();}
        
        p=node.getChildElement('text', eiEnvelope.namespace);
        if(p != null){text = p.getText();}
        
        p=node.getChildElement('severity', eiEnvelope.namespace);
        if(p != null){severity = p.getText();}
        
        p=node.getChildElement('category', eiEnvelope.namespace);
        if(p != null){category = p.getText();}
        
        p=node.getChildElement('subcategory', eiEnvelope.namespace);
        if(p != null){subcategory = p.getText();}
        
        p=node.getChildElement('dataState', eiEnvelope.namespace);
        if(p != null){dataState = p.getText();}
        
        p=node.getChildElement('retryAllowed', eiEnvelope.namespace);
        if(p != null){retryAllowed = p.getText().equalsIgnoreCase('true');}
        
        p=node.getChildElement('additionalInformation', eiEnvelope.namespace);
        if(p != null){additionalInformation = p.getText();}
        
    }
    
    public static testmethod void testeiException() {
    
        
        DOM.Document doc = new DOM.Document();
        dom.XmlNode envelope= doc.createRootElement('Envelope',null,null);
        dom.XmlNode body= envelope.addChildElement('code', null, null);

        eiException eiEx = new eiException(body);
      
    }
}
Hello Everyone,

We have added og meta tags in the community advanced settings which are working fine, to get the knowledge article name and description dynamically, we have added the og tags in the article detail community page which are not working.
Has anyone had success passing Open Graph tags in community page meta tags?

Thank you in advance for your help!