• Ramk123
  • NEWBIE
  • 80 Points
  • Member since 2014

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 18
    Questions
  • 19
    Replies
Dear Experts,

I am getting "System Limit Exception: Apex CPU time limit exceeded" on my trigger. Kindly help me to correct the logic. Thank you very much for your quick help!

Trigger
trigger ContactTrigger on Contact (before insert, after insert, before update, after update) { 
    
    if(Trigger.isBefore && ContactTriggerHandler.runContactTrigger){
        if(Trigger.isInsert || Trigger.isUpdate){
            ContactTriggerHandler.validateAliedRegistrationNumbers(Trigger.new);
            ContactTriggerHandler.validateAClientMDHHSNumbers(Trigger.new);
            ContactTriggerHandler.setContactAccountByCaseIds(Trigger.new);
        }
    }
    if(Trigger.isAfter && ContactTriggerHandler.runContactTrigger){
        
        if(Trigger.isInsert){
            ContactTriggerHandler.getHouseholdAcctsForSharing(Trigger.new, Trigger.newMap);
            ContactTriggerHandler.runContactTrigger = false;
            ContactTriggerHandler.insertSubsidiaryAccounts(Trigger.new);
        }
        if(Trigger.isUpdate){
            ContactTriggerHandler.runContactTrigger = false;
        }
    }

Trigger Handler
 
public class ContactTriggerHandler {

    public static Boolean runContactTrigger = true;
    
    public static Id accountHouseholdRT = Schema.SObjectType.Account.getRecordTypeInfosByDeveloperName().get('Household').getRecordTypeId();
    public static Id accountOrganizationRT = Schema.SObjectType.Account.getRecordTypeInfosByDeveloperName().get('Organization').getRecordTypeId();
    public static Id accountVolunteerRT = Schema.SObjectType.Account.getRecordTypeInfosByDeveloperName().get('Volunteer_Household').getRecordTypeId();
    public static Id contactProviderRT = Schema.SObjectType.Contact.getRecordTypeInfosByDeveloperName().get('Provider').getRecordTypeId();
    public static Id contactClientRT = Schema.SObjectType.Contact.getRecordTypeInfosByDeveloperName().get('Client').getRecordTypeId();
    public static Id contactURMRT = Schema.SObjectType.Contact.getRecordTypeInfosByDeveloperName().get('URM').getRecordTypeId();
    
    //Method: getHouseholdAcctsForSharing
    //Desc:   When a new Provider rType Contact is created, they need to be granted access to all Household Accounts that all Agency employees from their Agency 
    //        have access to. If new provider is part of an agency, that is a parent agency to other agencies (top level account), then they should also have access
    //        to all child agency related Household Accounts 
    public static void getHouseholdAcctsForSharing(List<Contact> newContacts, Map<Id, Contact> newMap){
        
        List<AccountContactRelation> relatedHouseholdAccts = new List<AccountContactRelation>();
        Map<Id,List<Id>> householdIdAgencyAll = new Map<Id,List<Id>>();
        Set<Id> providerAgencyIds = new Set<Id>();
        Set<Id> agencyContacts = new Set<Id>();
        Map<Id, List<Id>> agencyWithEmployees = new Map<Id, List<Id>>();
        Map<Id, List<Id>> agencyEmpWithHouseholdIds = new Map<Id, List<Id>>();
                
        for(Contact c : newContacts){
            
            if(c.RecordTypeId == contactProviderRT){
                providerAgencyIds.add(c.AccountId);
            }
        }
        
        system.debug(providerAgencyIds.size());
        
        if(providerAgencyIds.size()>0){
            //Get URM & Provider contacts related to agency of new employee
            List<AccountContactRelation> relatedAgencyEmployees = [SELECT Id, AccountId, ContactId, Roles 
                                                                   FROM AccountContactRelation WHERE AccountId IN:providerAgencyIds
                                                                   AND Contact.RecordTypeId =:contactProviderRT];
            
            system.debug(relatedAgencyEmployees.size());
            
            List<Id> agencyEmpIds = null;
            
            for(AccountContactRelation acr : relatedAgencyEmployees){
                
                agencyContacts.add(acr.ContactId);
                agencyEmpIds = agencyWithEmployees.get(acr.AccountId);
                
                if(agencyEmpIds == null){
                    agencyEmpIds = new List<Id>();
                }
                agencyEmpIds.add(acr.ContactId);
                agencyWithEmployees.put(acr.AccountId, agencyEmpIds);
            }
            
            if(agencyWithEmployees.size()>0){
                
                //Get all household accts that agency contacts have access to for assignment to new employee 
                relatedHouseholdAccts = [SELECT Id, AccountId, ContactId, Roles FROM AccountContactRelation 
                                         WHERE ContactId IN:agencyContacts AND (Account.RecordTypeId =:accountHouseholdRT OR Account.RecordTypeId =:accountVolunteerRT)];

                List<Id> householdIds = null;
                
                for(AccountContactRelation acr : relatedHouseholdAccts){
                    
                    householdIds = agencyEmpWithHouseholdIds.get(acr.ContactId);
                    
                    if(householdIds == null){
                        householdIds = new List<Id>();
                    }
                    householdIds.add(acr.AccountId);
                    agencyEmpWithHouseholdIds.put(acr.ContactId, householdIds);
                }

                List<Id> hIds = null;
                //agency Id
                for(Id aId : agencyWithEmployees.keyset()){
                    //employee contact Ids
                    for(Id eId : agencyWithEmployees.get(aId)){
                        
                        if(agencyEmpWithHouseholdIds.keyset().contains(eId)){
                            
                            List<Id> relatedHIDs = agencyEmpWithHouseholdIds.get(eId);
                            system.debug(relatedHIDS.size());
                            hIds = householdIdAgencyAll.get(aId);
                            
                            if(hIds == null){
                                hIds = new List<Id>();
                            }
                            for(Id rHids : relatedHIDS){
                                hIds.add(rHids);
                            }
                            
                            system.debug(hIds.size());
                            householdIdAgencyAll.put(aId, hIds);
                        }
                        
                    }
                }

                List<AccountContactRelation> householdRelationshipsToCreate = new List<AccountContactRelation>();
                Map<Id, AccountContactRelation> householdRelationshipMap = new Map<Id, AccountContactRelation>();
                Map<Id, Set<Id>> agencyContactWithHouseholdIds = new Map<Id, Set<Id>>();
                List<Id> hhIds = null;
                Set<Id> hhSet = new Set<Id>();
                
                for(Contact c : newContacts){
                    hhIds = householdIdAgencyAll.get(c.AccountId);
                    
                    if(hhIds != null){
                        hhSet.addAll(hhIds);
                        agencyContactWithHouseholdIds.put(c.id, hhSet);     
                    }
                }
                
                if(agencyContactWithHouseholdIds.size()>0){
                    
                    for(Id cId : agencyContactWithHouseholdIds.keyset()){
                        
                        for(Id hhId : agencyContactWithHouseholdIds.get(cId)){
                            
                            AccountContactRelation acr = new AccountContactRelation();
                            acr.ContactId = cId;
                            acr.AccountId = hhId;
                            acr.IsActive = true;
                            acr.Roles = 'Agency';
                            householdRelationshipsToCreate.add(acr);
                        }
                    }
                }

                if(householdRelationshipsToCreate.size()>0){
                    insert householdRelationshipsToCreate;
                }
            }
        }
    }

    public static void validateAliedRegistrationNumbers(List<Contact> newRecords){
        
        for(Contact c : newRecords){
            
            if(c.Alien_Number__c != null && c.Alien_Registration_Number_DW__c == null){
                c.Alien_Registration_Number_DW__c = c.Alien_Number__c;
            } 
            
            else if(c.Alien_Registration_Number_DW__c != null && c.Alien_Number__c == null ){
                c.Alien_Number__c = c.Alien_Registration_Number_DW__c;
            }

            if(c.Alien_Number__c != null){
                string aliennumber = c.Alien_Number__c;
                c.Alien_Number__c = aliennumber.replaceAll('[^0-9]', '');
            }

            if(c.Alien_Registration_Number_DW__c != null ){
                string aliennumber = c.Alien_Registration_Number_DW__c;
                c.Alien_Registration_Number_DW__c = aliennumber.replaceAll('[^0-9]', '');
            }

        }
    }
    public static void validateAClientMDHHSNumbers(List<Contact> newRecords){
        
        for(Contact c : newRecords){

            if(c.MD_ID__c != null && c.Client_MD_ID__c == null){
                c.Client_MD_ID__c = c.MD_ID__c;
            } else if(c.Client_MD_ID__c != null && c.MD_ID__c == null ){
                c.MD_ID__c = c.Client_MD_ID__c;
            }
        }
    }

    public static void setContactAccountByCaseIds(List<Contact> newRecords){
        Set<String> caseIds = new Set<String>();
        Map<String,Id> caseIDMap = new Map<String,Id>();

        for(Contact c : newRecords){

            if(c.MD_ID__c != null && c.Case_ID__c != null){
                caseIds.add(c.Case_ID__c);
            } 
        }
        List<Account> accounts = [SELECT Id, Case_ID__c FROM Account WHERE Case_ID__c in: caseIDs];
        for(Account a : accounts){
            caseIDMap.put(a.Case_ID__c, a.Id);
        }
        for(Contact c : newRecords){
            if(c.MD_ID__c != null && c.Case_ID__c != null && c.AccountId == null && caseIDMap.containsKey(c.Case_ID__c)){
                c.accountId = caseIDMap.get(c.Case_ID__c);
            } 
        }
    }
    
    public static void insertSubsidiaryAccounts(List<Contact> newRecords) {
        
        for(Contact ct : newRecords) {
            if(ct.RecordTypeId == contactProviderRT) {
                AccountRelationService.insertSubsidiaries(ct);
            }
        }
        
        if(AccountRelationService.relatedContacts.size() > 0) {
            Database.insert(AccountRelationService.relatedContacts, false);
        }
    }

 
Dear Experts.

I have a requirement to extract report list of Opportunities with Orders from multiple record types and it has lookup relation between Opportunity and Order objects.
Need to extract list opportunities which has both Program type is Active from Rec 1 and Benefits is Active from Rec 1.

Example:

Object Opportunity
Object Order has Record type 1(Rec 1) and order Record Type 2(Rec 2).

Order Record type 1 has Program type picklist field.
Order Record type 2 has Benefits picklist field.

Record 1
Opportunity 1
Order A and Program type = Active
Order B and Benefits = Active

Record 2
Opportunity 2
Order C and Program type = Active
Order D and Benefits = Inactive

Record 3
Opportunity 3
Order C and Program type = Inactive
Order D and Benefits = Active

Record 4
Opportunity 4
Order E and Program type = Inactive
Order F and Benefits = Inactive

The report should extract only Record 1 and exclude Record 2,3, and 4.

Kindly help me to achieve the scenario.

Thank you very much!

 
Dear Experts,

We have a requirement to generate different numbering formats for Community Self-Registration user-related Contact Records than other person accounts in the system.

I created a Process builder with the following conditions but it is not recognizing the Community Self-Registration user-related Contact upon creating a contact created.

1. Account only when a record is created
2. IsPersonAccount = True and IsCustomerPortal = True
3. Immediate Action to update [Account].Textfield__C = "Self" & "-" &  [Account].Autonumber_field__c 

Please suggest the approach to make the unique numbering format for self-registered related user contacts.

Thank you very much for your help!
We have a requirement to generate different numbering formats for Community Self-Registration Contact Records than other person accounts in the system.

I created a Process builder with the following conditions but it is not providing a new numbering format.

1. Account only when a record is created
2. IsPersonAccount = True and IsCustomerPortal = True
3. Immediate Action to update [Account].Textfield__C = "Self" & "-" &  [Account].Autonumber_field__c 

Please suggest the approach to make the unique numbering format for self-registered contacts.

Thank you very much!
I have an interesting requirement to be able to export a list of records and print it one per page.

Kindly provide logic to meet the business need.
Dear Experts,

May I request you to help with increasing code coverage for the following highlighted missing code coverage? Appreciate your quick help.
Apex Class
public class ApexUtility {
    
    public static Boolean isCommunity() {
        if(Site.getSiteId() != null)
            return true;
        return false;
    }

    public static final String PUBLIC_USERNAME = 'Community Site Guest User';
    static User publicUser;
    public static Boolean isLoggedInUser() {
        if(publicUser == null){
            publicUser = [SELECT Id FROM User WHERE Name = :PUBLIC_USERNAME LIMIT 1];
        }
        if(publicUser != null){
            if(UserInfo.getUserId() != publicUser.Id)
                return true;
        }    
        return false;
    }
    
    public static PageReference redirectToVipForm(String recordId) {
        String returnUrl = '/apex/FormWizard?id=' + recordId;
    
        if(isCommunity()){
             returnUrl = '/mcr' + returnUrl;
        }
           
        PageReference p = new PageReference(returnUrl);
        p.setRedirect(true);
        return p;  
    }
    
}

Test Class
 
@isTest
public class btn_EnableCustomerCommunityUser_ExtTest {

    @isTest
    static void testCreateCustomerUser() {
        Account testAccount = TestDataFactory.getPersonAccount();
        insert testAccount;
        
        Test.startTest();
        ApexPages.StandardController stdController = new ApexPages.StandardController(testAccount);
        btn_EnableCustomerCommunityUser_Ext ext = new btn_EnableCustomerCommunityUser_Ext(stdController);
        
        PageReference pr = ext.CreateCustomerCommunityUser();
        Test.stopTest();
        
        testAccount = [SELECT Id, Community_User__c FROM Account WHERE Id = :testAccount.Id LIMIT 1];
        
        System.assertEquals(true, testAccount.Community_User__c);
    }

}

 
Dear Experts,

I would like to switch community with the apex logic.

SELECT GuestUserId, Name, Subdomain, UrlPathPrefix FROM Site 'abc'

If UrlPathPrefix is abc
returnurl = '/abc' + returnurl
else if UrlPathPrefix  is xyz
returnurl = '/xyz' + returnurl

anyone please help me to frame the logic to return proper community URL.
Dear Experts,

In my community, I have one Custom Lightning component and Rich Text Editor, but I would like to Restrict the lightning component visibility to the Guest Users. When I apply "Assign Audience" it is applicable to both the "Custom lightning Component" and "Rich Text Editor". Kindly advice.
Dear Integration Experts,

I have a Requirement to Integrate between Teradata to Salesforce to pull simple Data From Teradata to Salesforce. Could any able to suggest simple options with lowcost and easy maintenance?

Thank you very much for understanding!
Dear Mobile App experts,

One of my customers would like to build a mobile App with React Native, What would be the pros and cons for the following options.
  • Option1: Can we build Mobile App in Salesforce with React Native Technology?
  • Option 2: Build React Native Mobile App outside salesforce and Integrate with Salesforce? 
  • What are the other best options to build a Mobile App?
Appreciate your valuable suggestions!
I have Review(Multi-Select Picklist) field with values following.
101(Previous grant)
101(No Expectation)
101(Sufficient Income)
101(Long Term)

Based on the above values selected update Review Log (Long Text Area) field.
I tried like below, but am getting an error message like "Error  Field Review__c may not be used in this type of formula "

IF(INCLUDES( Review__c, "101(Not Unforeseen)"), "$Label.X101_Not_Unforeseen", NULL ) + BR() +
IF(INCLUDES( Review__c, "101(Previous grant)"), "$Label.Previous_grant", NULL ) + BR() +
IF(INCLUDES( Review__c, "101(No Expectation)"), "$Label.No_Expectation", NULL ) + BR() +
IF(INCLUDES( Review__c, "101(Sufficient Income)"), "$Label.X101_Sufficient_Income", NULL ) + BR() +
IF(INCLUDES( Review__c, "101(Long Term)"), "$Label.X101_Long_Term", NULL )
  
Note: Long Text referring from Label

Appreciate quick help on this!
 
Please help to write a test class for below part apex logic 

   private void populateRequesterInfo() {
        if(CommonUtil.isNotBlank(this.caseObj.isApplicantPA__c) && 'No'.equalsIgnoreCase(this.caseObj.isApplicantPA__c)) {
            this.contactObj.FirstName = trimLongText(this.caseObj.Requester_First_Name__c, 40);
            this.contactObj.LastName = this.caseObj.Requester_Last_Name__c;
            this.contactObj.Phone = this.caseObj.Requester_Home_Phone__c;
            this.contactObj.MobilePhone = this.caseObj.Requester_Cell_Phone__c;
            this.contactObj.MailingStreet = buildMailingStreet(this.caseObj.Requester_Mail_to_Address__c, this.caseObj.Requester_Apt__c);
            this.contactObj.Apt__c = this.caseObj.Requester_Apt__c;
            this.contactObj.MailingCity = this.caseObj.Requester_Mail_to_City__c;
            this.contactObj.MailingState = this.caseObj.Requester_Mail_to_State__c;
            this.contactObj.MailingPostalCode = null != this.caseObj.Requester_Mail_to_Zip_Postal_Code__c ?  String.valueOf(this.caseObj.Requester_Mail_to_Zip_Postal_Code__c) : '';
            this.contactObj.Email = this.caseObj.Requester_Email__c;
            this.contactObj.Region__c = this.caseObj.Requester_Region__c;
            this.contactObj.County__c = this.caseObj.Requester_County_of_Residence__c;
Requesting help on the below requirement.
I have 3 Picklist fields on the page.
  • Field 1 -- Values A, B C, D
  • Field 2 -- Values A, B, C, D
  • Field 3 --  Values A, B, C, D
Capture latest field value from above fields and always update "Field 4" with the latest Value.

Thank a lot in advance.

 
How to populate logitude and latitude on custome object using Google API.
Any one please help on this? Thank you!
I would like to auto-populate slashes(/) in the date field, am unable achieve with below code.
Example:
Option 1: when user move cursor into date field Slashes(/) should be constant like __/__/____(MM/DD/YYYY)
Option 2: validate user date format: User should enter Date with Slashes and specified format(MM/DD/YYY) else field should throw an error with invalid date format.
Lighting Component
<ui:inputDate aura:id="Birthdate" label="Date Of Birth" 
                                                  value="{!v.value}" 
                                                  displayDatePicker="false" blur="{!c.formatDoB}"
                                                  format="MM/dd/yyyy" />
JS Controller
formatDOB: function(component, helper, event) {
        var DOB = component.find("Birthdate");
        var Date = DoB.get('v.value');
        var s = (""+Date).replace(/\D/g, '');
        var m = s.match(/^(\d{2})(\d{2})(\d{4})$/);
        var formattedDoB = (!m) ? null : + m[1] + "/" + m[2] + "/" + m[3];
        DoB.set('v.value',formattedDoB);
    },

any one please help?
Thanks
I have a requirement to automate SSN structure.
example:
user input SSN: 123456789
automate output SSN format: 123-45-6789
with my below logic am not able to achieve the scenario, anyone please help.
Component:
<lightning:input aura:id="SSN__c" name="SSN" 
           label="SSN" 
           maxlength="9" onblur="{!c.formatSSN}"                                          
           value="{!v.newCallerModel.Ssn}" />  
JS Controller 
formatSSN: function(component, helper, event)  {   
     var patt = new RegExp("\d{3}[\-]\d{2}[\-]\d{4}");
     var x = document.getElementById("SSN__c");
     var res = patt.test(x.value);
        if(!res){
            x.value = x.value
            .match(/\d*/g).join('')
            .match(/(\d{0,3})(\d{0,2})(\d{0,4})/).slice(1).join('-')
            .replace(/-*$/g, '');
        }
    },  
Hi,

I have created below formula field to calculate total efforts and calcuating as expected, but while deployement am getting below error.

Formual field: 
TEXT(ROUND(
if ( And( TEXT(Status) <> "Completed", TEXT(Status) <> "On Hold",
ISBLANK(Task_Completion_Date__c), ISBLANK(On_Hold_Date__c )), NOW() - CreatedDate,

if( TEXT(Status) = "On Hold", On_Hold_Date__c - CreatedDate,

if( TEXT(Status) = "Completed", Task_Completion_Date__c - CreatedDate - (Not_On_Hold_Date__c - On_Hold_Date__c),

NOW() - CreatedDate - (Not_On_Hold_Date__c - On_Hold_Date__c))))*24, 2))&" "&"hours"

Deployment Error  : Incorrect parameter type for operator '-'. Expected Number, Date, received DateTime

Appreciate your help at the earliest.

Thanks,
Ramesba
Task completion email notification to task creator and Should not generate a notification to yourself when you complete the task.

trigger Taskcompletednotification on Task (after update) {
   List<Messaging.SingleEmailMessage> mails= new List<Messaging.SingleEmailMessage>(); 
   Map<Id,Id> userTaskIds = new Map<Id,Id>();
   EmailTemplate Template =  [SELECT Id,Name FROM EmailTemplate WHERE Name='Task creator email notification'];
   for(Task tsk : Trigger.New)
   {
        if(tsk.Status == 'Completed'&& tsk.OwnerId != tsk.CreatedById)
        {
           userTaskIds.put(tsk.CreatedById,tsk.Id);
        } 
   }
   
   for(User targetId : [SELECT id,Email From User where Id IN :userTaskIds.keySet()])
   {
         Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
         email.setSaveAsActivity(false);
         email.setTargetObjectId(targetId.Id); 
         email.setTemplateId(Template.Id);  
         email.setWhatId(userTaskIds.get(targetId.id));
         mails.add(email);
   }
 
   if(mails.size() > 0)
   {  
      try
      {
         System.debug('Control Came Here');
         Messaging.sendEmail(mails);
      }catch(Exception e)
      {
         System.debug('Error Message :'+e);
      }  
   }                
         
}

Test Class
========
@isTest
public class Taskcompletednotificationtest{

@isTest
public static void taskUpdateTest()
{
    Task tsk = new Task(); 
    tsk.subject='test';
    tsk.ActivityDate=Date.Today();
    tsk.Status='Not Started';
    tsk.Priority='Normal';
    tsk.OwnerId='00524000003MWO2';
    tsk.CreatedById='00524000003MWO2';
    insert tsk;
    
    Task task = [SELECT status FROM Task WHERE id=:tsk.id];
    task.status = 'Completed';
    update task;
}

}
Dear Experts,

I am getting "System Limit Exception: Apex CPU time limit exceeded" on my trigger. Kindly help me to correct the logic. Thank you very much for your quick help!

Trigger
trigger ContactTrigger on Contact (before insert, after insert, before update, after update) { 
    
    if(Trigger.isBefore && ContactTriggerHandler.runContactTrigger){
        if(Trigger.isInsert || Trigger.isUpdate){
            ContactTriggerHandler.validateAliedRegistrationNumbers(Trigger.new);
            ContactTriggerHandler.validateAClientMDHHSNumbers(Trigger.new);
            ContactTriggerHandler.setContactAccountByCaseIds(Trigger.new);
        }
    }
    if(Trigger.isAfter && ContactTriggerHandler.runContactTrigger){
        
        if(Trigger.isInsert){
            ContactTriggerHandler.getHouseholdAcctsForSharing(Trigger.new, Trigger.newMap);
            ContactTriggerHandler.runContactTrigger = false;
            ContactTriggerHandler.insertSubsidiaryAccounts(Trigger.new);
        }
        if(Trigger.isUpdate){
            ContactTriggerHandler.runContactTrigger = false;
        }
    }

Trigger Handler
 
public class ContactTriggerHandler {

    public static Boolean runContactTrigger = true;
    
    public static Id accountHouseholdRT = Schema.SObjectType.Account.getRecordTypeInfosByDeveloperName().get('Household').getRecordTypeId();
    public static Id accountOrganizationRT = Schema.SObjectType.Account.getRecordTypeInfosByDeveloperName().get('Organization').getRecordTypeId();
    public static Id accountVolunteerRT = Schema.SObjectType.Account.getRecordTypeInfosByDeveloperName().get('Volunteer_Household').getRecordTypeId();
    public static Id contactProviderRT = Schema.SObjectType.Contact.getRecordTypeInfosByDeveloperName().get('Provider').getRecordTypeId();
    public static Id contactClientRT = Schema.SObjectType.Contact.getRecordTypeInfosByDeveloperName().get('Client').getRecordTypeId();
    public static Id contactURMRT = Schema.SObjectType.Contact.getRecordTypeInfosByDeveloperName().get('URM').getRecordTypeId();
    
    //Method: getHouseholdAcctsForSharing
    //Desc:   When a new Provider rType Contact is created, they need to be granted access to all Household Accounts that all Agency employees from their Agency 
    //        have access to. If new provider is part of an agency, that is a parent agency to other agencies (top level account), then they should also have access
    //        to all child agency related Household Accounts 
    public static void getHouseholdAcctsForSharing(List<Contact> newContacts, Map<Id, Contact> newMap){
        
        List<AccountContactRelation> relatedHouseholdAccts = new List<AccountContactRelation>();
        Map<Id,List<Id>> householdIdAgencyAll = new Map<Id,List<Id>>();
        Set<Id> providerAgencyIds = new Set<Id>();
        Set<Id> agencyContacts = new Set<Id>();
        Map<Id, List<Id>> agencyWithEmployees = new Map<Id, List<Id>>();
        Map<Id, List<Id>> agencyEmpWithHouseholdIds = new Map<Id, List<Id>>();
                
        for(Contact c : newContacts){
            
            if(c.RecordTypeId == contactProviderRT){
                providerAgencyIds.add(c.AccountId);
            }
        }
        
        system.debug(providerAgencyIds.size());
        
        if(providerAgencyIds.size()>0){
            //Get URM & Provider contacts related to agency of new employee
            List<AccountContactRelation> relatedAgencyEmployees = [SELECT Id, AccountId, ContactId, Roles 
                                                                   FROM AccountContactRelation WHERE AccountId IN:providerAgencyIds
                                                                   AND Contact.RecordTypeId =:contactProviderRT];
            
            system.debug(relatedAgencyEmployees.size());
            
            List<Id> agencyEmpIds = null;
            
            for(AccountContactRelation acr : relatedAgencyEmployees){
                
                agencyContacts.add(acr.ContactId);
                agencyEmpIds = agencyWithEmployees.get(acr.AccountId);
                
                if(agencyEmpIds == null){
                    agencyEmpIds = new List<Id>();
                }
                agencyEmpIds.add(acr.ContactId);
                agencyWithEmployees.put(acr.AccountId, agencyEmpIds);
            }
            
            if(agencyWithEmployees.size()>0){
                
                //Get all household accts that agency contacts have access to for assignment to new employee 
                relatedHouseholdAccts = [SELECT Id, AccountId, ContactId, Roles FROM AccountContactRelation 
                                         WHERE ContactId IN:agencyContacts AND (Account.RecordTypeId =:accountHouseholdRT OR Account.RecordTypeId =:accountVolunteerRT)];

                List<Id> householdIds = null;
                
                for(AccountContactRelation acr : relatedHouseholdAccts){
                    
                    householdIds = agencyEmpWithHouseholdIds.get(acr.ContactId);
                    
                    if(householdIds == null){
                        householdIds = new List<Id>();
                    }
                    householdIds.add(acr.AccountId);
                    agencyEmpWithHouseholdIds.put(acr.ContactId, householdIds);
                }

                List<Id> hIds = null;
                //agency Id
                for(Id aId : agencyWithEmployees.keyset()){
                    //employee contact Ids
                    for(Id eId : agencyWithEmployees.get(aId)){
                        
                        if(agencyEmpWithHouseholdIds.keyset().contains(eId)){
                            
                            List<Id> relatedHIDs = agencyEmpWithHouseholdIds.get(eId);
                            system.debug(relatedHIDS.size());
                            hIds = householdIdAgencyAll.get(aId);
                            
                            if(hIds == null){
                                hIds = new List<Id>();
                            }
                            for(Id rHids : relatedHIDS){
                                hIds.add(rHids);
                            }
                            
                            system.debug(hIds.size());
                            householdIdAgencyAll.put(aId, hIds);
                        }
                        
                    }
                }

                List<AccountContactRelation> householdRelationshipsToCreate = new List<AccountContactRelation>();
                Map<Id, AccountContactRelation> householdRelationshipMap = new Map<Id, AccountContactRelation>();
                Map<Id, Set<Id>> agencyContactWithHouseholdIds = new Map<Id, Set<Id>>();
                List<Id> hhIds = null;
                Set<Id> hhSet = new Set<Id>();
                
                for(Contact c : newContacts){
                    hhIds = householdIdAgencyAll.get(c.AccountId);
                    
                    if(hhIds != null){
                        hhSet.addAll(hhIds);
                        agencyContactWithHouseholdIds.put(c.id, hhSet);     
                    }
                }
                
                if(agencyContactWithHouseholdIds.size()>0){
                    
                    for(Id cId : agencyContactWithHouseholdIds.keyset()){
                        
                        for(Id hhId : agencyContactWithHouseholdIds.get(cId)){
                            
                            AccountContactRelation acr = new AccountContactRelation();
                            acr.ContactId = cId;
                            acr.AccountId = hhId;
                            acr.IsActive = true;
                            acr.Roles = 'Agency';
                            householdRelationshipsToCreate.add(acr);
                        }
                    }
                }

                if(householdRelationshipsToCreate.size()>0){
                    insert householdRelationshipsToCreate;
                }
            }
        }
    }

    public static void validateAliedRegistrationNumbers(List<Contact> newRecords){
        
        for(Contact c : newRecords){
            
            if(c.Alien_Number__c != null && c.Alien_Registration_Number_DW__c == null){
                c.Alien_Registration_Number_DW__c = c.Alien_Number__c;
            } 
            
            else if(c.Alien_Registration_Number_DW__c != null && c.Alien_Number__c == null ){
                c.Alien_Number__c = c.Alien_Registration_Number_DW__c;
            }

            if(c.Alien_Number__c != null){
                string aliennumber = c.Alien_Number__c;
                c.Alien_Number__c = aliennumber.replaceAll('[^0-9]', '');
            }

            if(c.Alien_Registration_Number_DW__c != null ){
                string aliennumber = c.Alien_Registration_Number_DW__c;
                c.Alien_Registration_Number_DW__c = aliennumber.replaceAll('[^0-9]', '');
            }

        }
    }
    public static void validateAClientMDHHSNumbers(List<Contact> newRecords){
        
        for(Contact c : newRecords){

            if(c.MD_ID__c != null && c.Client_MD_ID__c == null){
                c.Client_MD_ID__c = c.MD_ID__c;
            } else if(c.Client_MD_ID__c != null && c.MD_ID__c == null ){
                c.MD_ID__c = c.Client_MD_ID__c;
            }
        }
    }

    public static void setContactAccountByCaseIds(List<Contact> newRecords){
        Set<String> caseIds = new Set<String>();
        Map<String,Id> caseIDMap = new Map<String,Id>();

        for(Contact c : newRecords){

            if(c.MD_ID__c != null && c.Case_ID__c != null){
                caseIds.add(c.Case_ID__c);
            } 
        }
        List<Account> accounts = [SELECT Id, Case_ID__c FROM Account WHERE Case_ID__c in: caseIDs];
        for(Account a : accounts){
            caseIDMap.put(a.Case_ID__c, a.Id);
        }
        for(Contact c : newRecords){
            if(c.MD_ID__c != null && c.Case_ID__c != null && c.AccountId == null && caseIDMap.containsKey(c.Case_ID__c)){
                c.accountId = caseIDMap.get(c.Case_ID__c);
            } 
        }
    }
    
    public static void insertSubsidiaryAccounts(List<Contact> newRecords) {
        
        for(Contact ct : newRecords) {
            if(ct.RecordTypeId == contactProviderRT) {
                AccountRelationService.insertSubsidiaries(ct);
            }
        }
        
        if(AccountRelationService.relatedContacts.size() > 0) {
            Database.insert(AccountRelationService.relatedContacts, false);
        }
    }

 
Dear Experts.

I have a requirement to extract report list of Opportunities with Orders from multiple record types and it has lookup relation between Opportunity and Order objects.
Need to extract list opportunities which has both Program type is Active from Rec 1 and Benefits is Active from Rec 1.

Example:

Object Opportunity
Object Order has Record type 1(Rec 1) and order Record Type 2(Rec 2).

Order Record type 1 has Program type picklist field.
Order Record type 2 has Benefits picklist field.

Record 1
Opportunity 1
Order A and Program type = Active
Order B and Benefits = Active

Record 2
Opportunity 2
Order C and Program type = Active
Order D and Benefits = Inactive

Record 3
Opportunity 3
Order C and Program type = Inactive
Order D and Benefits = Active

Record 4
Opportunity 4
Order E and Program type = Inactive
Order F and Benefits = Inactive

The report should extract only Record 1 and exclude Record 2,3, and 4.

Kindly help me to achieve the scenario.

Thank you very much!

 
Dear Experts,

May I request you to help with increasing code coverage for the following highlighted missing code coverage? Appreciate your quick help.
Apex Class
public class ApexUtility {
    
    public static Boolean isCommunity() {
        if(Site.getSiteId() != null)
            return true;
        return false;
    }

    public static final String PUBLIC_USERNAME = 'Community Site Guest User';
    static User publicUser;
    public static Boolean isLoggedInUser() {
        if(publicUser == null){
            publicUser = [SELECT Id FROM User WHERE Name = :PUBLIC_USERNAME LIMIT 1];
        }
        if(publicUser != null){
            if(UserInfo.getUserId() != publicUser.Id)
                return true;
        }    
        return false;
    }
    
    public static PageReference redirectToVipForm(String recordId) {
        String returnUrl = '/apex/FormWizard?id=' + recordId;
    
        if(isCommunity()){
             returnUrl = '/mcr' + returnUrl;
        }
           
        PageReference p = new PageReference(returnUrl);
        p.setRedirect(true);
        return p;  
    }
    
}

Test Class
 
@isTest
public class btn_EnableCustomerCommunityUser_ExtTest {

    @isTest
    static void testCreateCustomerUser() {
        Account testAccount = TestDataFactory.getPersonAccount();
        insert testAccount;
        
        Test.startTest();
        ApexPages.StandardController stdController = new ApexPages.StandardController(testAccount);
        btn_EnableCustomerCommunityUser_Ext ext = new btn_EnableCustomerCommunityUser_Ext(stdController);
        
        PageReference pr = ext.CreateCustomerCommunityUser();
        Test.stopTest();
        
        testAccount = [SELECT Id, Community_User__c FROM Account WHERE Id = :testAccount.Id LIMIT 1];
        
        System.assertEquals(true, testAccount.Community_User__c);
    }

}

 
Dear Experts,

In my community, I have one Custom Lightning component and Rich Text Editor, but I would like to Restrict the lightning component visibility to the Guest Users. When I apply "Assign Audience" it is applicable to both the "Custom lightning Component" and "Rich Text Editor". Kindly advice.
Dear Integration Experts,

I have a Requirement to Integrate between Teradata to Salesforce to pull simple Data From Teradata to Salesforce. Could any able to suggest simple options with lowcost and easy maintenance?

Thank you very much for understanding!
Dear Mobile App experts,

One of my customers would like to build a mobile App with React Native, What would be the pros and cons for the following options.
  • Option1: Can we build Mobile App in Salesforce with React Native Technology?
  • Option 2: Build React Native Mobile App outside salesforce and Integrate with Salesforce? 
  • What are the other best options to build a Mobile App?
Appreciate your valuable suggestions!
I have Review(Multi-Select Picklist) field with values following.
101(Previous grant)
101(No Expectation)
101(Sufficient Income)
101(Long Term)

Based on the above values selected update Review Log (Long Text Area) field.
I tried like below, but am getting an error message like "Error  Field Review__c may not be used in this type of formula "

IF(INCLUDES( Review__c, "101(Not Unforeseen)"), "$Label.X101_Not_Unforeseen", NULL ) + BR() +
IF(INCLUDES( Review__c, "101(Previous grant)"), "$Label.Previous_grant", NULL ) + BR() +
IF(INCLUDES( Review__c, "101(No Expectation)"), "$Label.No_Expectation", NULL ) + BR() +
IF(INCLUDES( Review__c, "101(Sufficient Income)"), "$Label.X101_Sufficient_Income", NULL ) + BR() +
IF(INCLUDES( Review__c, "101(Long Term)"), "$Label.X101_Long_Term", NULL )
  
Note: Long Text referring from Label

Appreciate quick help on this!
 
Please help to write a test class for below part apex logic 

   private void populateRequesterInfo() {
        if(CommonUtil.isNotBlank(this.caseObj.isApplicantPA__c) && 'No'.equalsIgnoreCase(this.caseObj.isApplicantPA__c)) {
            this.contactObj.FirstName = trimLongText(this.caseObj.Requester_First_Name__c, 40);
            this.contactObj.LastName = this.caseObj.Requester_Last_Name__c;
            this.contactObj.Phone = this.caseObj.Requester_Home_Phone__c;
            this.contactObj.MobilePhone = this.caseObj.Requester_Cell_Phone__c;
            this.contactObj.MailingStreet = buildMailingStreet(this.caseObj.Requester_Mail_to_Address__c, this.caseObj.Requester_Apt__c);
            this.contactObj.Apt__c = this.caseObj.Requester_Apt__c;
            this.contactObj.MailingCity = this.caseObj.Requester_Mail_to_City__c;
            this.contactObj.MailingState = this.caseObj.Requester_Mail_to_State__c;
            this.contactObj.MailingPostalCode = null != this.caseObj.Requester_Mail_to_Zip_Postal_Code__c ?  String.valueOf(this.caseObj.Requester_Mail_to_Zip_Postal_Code__c) : '';
            this.contactObj.Email = this.caseObj.Requester_Email__c;
            this.contactObj.Region__c = this.caseObj.Requester_Region__c;
            this.contactObj.County__c = this.caseObj.Requester_County_of_Residence__c;
Requesting help on the below requirement.
I have 3 Picklist fields on the page.
  • Field 1 -- Values A, B C, D
  • Field 2 -- Values A, B, C, D
  • Field 3 --  Values A, B, C, D
Capture latest field value from above fields and always update "Field 4" with the latest Value.

Thank a lot in advance.

 
How to populate logitude and latitude on custome object using Google API.
Any one please help on this? Thank you!
Hi
i m a new admin and a maybe stupid question . 
2 teams in my company (sales and support ) 
I need to create 2  differents opportunity path . Sales must be able to view (not edit) the support's opportunity and vice versa . 

is it possible ? how ? 
I have a requirement to automate SSN structure.
example:
user input SSN: 123456789
automate output SSN format: 123-45-6789
with my below logic am not able to achieve the scenario, anyone please help.
Component:
<lightning:input aura:id="SSN__c" name="SSN" 
           label="SSN" 
           maxlength="9" onblur="{!c.formatSSN}"                                          
           value="{!v.newCallerModel.Ssn}" />  
JS Controller 
formatSSN: function(component, helper, event)  {   
     var patt = new RegExp("\d{3}[\-]\d{2}[\-]\d{4}");
     var x = document.getElementById("SSN__c");
     var res = patt.test(x.value);
        if(!res){
            x.value = x.value
            .match(/\d*/g).join('')
            .match(/(\d{0,3})(\d{0,2})(\d{0,4})/).slice(1).join('-')
            .replace(/-*$/g, '');
        }
    },  
Hi,

I have created below formula field to calculate total efforts and calcuating as expected, but while deployement am getting below error.

Formual field: 
TEXT(ROUND(
if ( And( TEXT(Status) <> "Completed", TEXT(Status) <> "On Hold",
ISBLANK(Task_Completion_Date__c), ISBLANK(On_Hold_Date__c )), NOW() - CreatedDate,

if( TEXT(Status) = "On Hold", On_Hold_Date__c - CreatedDate,

if( TEXT(Status) = "Completed", Task_Completion_Date__c - CreatedDate - (Not_On_Hold_Date__c - On_Hold_Date__c),

NOW() - CreatedDate - (Not_On_Hold_Date__c - On_Hold_Date__c))))*24, 2))&" "&"hours"

Deployment Error  : Incorrect parameter type for operator '-'. Expected Number, Date, received DateTime

Appreciate your help at the earliest.

Thanks,
Ramesba
Task completion email notification to task creator and Should not generate a notification to yourself when you complete the task.

trigger Taskcompletednotification on Task (after update) {
   List<Messaging.SingleEmailMessage> mails= new List<Messaging.SingleEmailMessage>(); 
   Map<Id,Id> userTaskIds = new Map<Id,Id>();
   EmailTemplate Template =  [SELECT Id,Name FROM EmailTemplate WHERE Name='Task creator email notification'];
   for(Task tsk : Trigger.New)
   {
        if(tsk.Status == 'Completed'&& tsk.OwnerId != tsk.CreatedById)
        {
           userTaskIds.put(tsk.CreatedById,tsk.Id);
        } 
   }
   
   for(User targetId : [SELECT id,Email From User where Id IN :userTaskIds.keySet()])
   {
         Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
         email.setSaveAsActivity(false);
         email.setTargetObjectId(targetId.Id); 
         email.setTemplateId(Template.Id);  
         email.setWhatId(userTaskIds.get(targetId.id));
         mails.add(email);
   }
 
   if(mails.size() > 0)
   {  
      try
      {
         System.debug('Control Came Here');
         Messaging.sendEmail(mails);
      }catch(Exception e)
      {
         System.debug('Error Message :'+e);
      }  
   }                
         
}

Test Class
========
@isTest
public class Taskcompletednotificationtest{

@isTest
public static void taskUpdateTest()
{
    Task tsk = new Task(); 
    tsk.subject='test';
    tsk.ActivityDate=Date.Today();
    tsk.Status='Not Started';
    tsk.Priority='Normal';
    tsk.OwnerId='00524000003MWO2';
    tsk.CreatedById='00524000003MWO2';
    insert tsk;
    
    Task task = [SELECT status FROM Task WHERE id=:tsk.id];
    task.status = 'Completed';
    update task;
}

}