• Nikhil Suthar
  • NEWBIE
  • 60 Points
  • Member since 2019

  • Chatter
    Feed
  • 1
    Best Answers
  • 0
    Likes Received
  • 1
    Likes Given
  • 0
    Questions
  • 22
    Replies
I am trying to use VS Code for my two different dev org.
I am using Create project with Manifest option.
If i create Create project with Manifest option for first org and executes authorize and retrieve command, it works fine and i am able to retrieve all components,
now if i create 2nd new project with manifest option  and after authorizing the second org, when i open package.xml for second project and try to retrieve components,
it is not retrieving components for second org, later i realize it has retrieve all the component first projects directory
Whenever I change the language of trailhead from the bottom page, I login and everything, I open trailhead again once I restart browser, and it's always back to the locale language. How come this is not at least saved through profile? I am used to doing trailheads, and everything in english, spanish does not help me.
Dear friends,

How can i cover following line in test class.

public boolean Checked{get;set;}  //  This line is not covering in the test class.

if(att.Body != null) {
                        newBody = EncodingUtil.base64Encode(att.Body);
                    }

If anyBody Have idea please help me.

Thanks in advance.
 
I am trying to send SMS via Marketing Cloud APIs from clicking a custom list button on contact and getting error. Could you please help what is wrong in my code. 
Apex Controller:
Error

public class selectDefaulterSMS{
    @TestVisible
    private String smsSentVal;
    private static String className = selectDefaulterSMS.Class.getName();
    public Boolean unableToSendsms { get; private set; }
    private final Contact contactRecord;
    private transient String mobileWithCountryCode;
    
    public selectDefaulterSMS(ApexPages.StandardController controller) {
        contactRecord = (Contact)controller.getRecord();
    }
    public selectDefaulterSMS() {
    }
    
    public selectDefaulterSMS(ApexPages.StandardSetController controller) {
    }
    
    //Our collection of the class/wrapper objects cContact 
    public List<cContact> contactList {get; set;}
    //This method uses a simple SOQL query to return a List of Contacts
    public List<cContact> getContacts() {
        if(contactList == null) {
            contactList = new List<cContact>();
            for(Contact c: [select Id, Name, Email, Phone, MobilePhone, Default_SMS_Sent__c,Status__c from Contact limit 10]) {
                // As each contact is processed we create a new cContact object and add it to the contactList
                contactList.add(new cContact(c));
                
            }
        }
        return contactList;
    }
    
    public PageReference processSelected() {
        
        //We create a new list of Contacts that we be populated only with Contacts if they are selected
        List<Contact> selectedContacts = new List<Contact>();
        
        //We will cycle through our list of cContacts and will check to see if the selected property is set to true, if it is we add the Contact to the selectedContacts list
        for(cContact cCon: getContacts()) {
            if(cCon.selected == true) {
                selectedContacts.add(cCon.con);
            }
        }
        
        // Now we have our list of selected contacts and can perform any type of logic we want, sending emails, updating a field on the Contact, etc
        System.debug('+++++++ These are the selected Contacts... +++++++');
        for(Contact con: selectedContacts) {
            system.debug(con);
            /**********************/
            List<Log__c> errorLogs = new List<Log__c>();
            /*********** SendSMS API Call ************/
            // 1. Get Access token
            String accessToken = obtainAccessToken(errorLogs);
            
            if( accessToken != null) 
            {
                // 2.Make Send SMS API call
                if(sendSMSViaAPI(accessToken, smsSentVal, errorLogs) != 'success')
                {
                    // Display unable to verify message
                    unableToSendsms = true;
                }
            }
            else{
                // Display unable to verify message
                unableToSendsms = true;
            }        
            
            ///// Create Logs for Errors
            if(!errorLogs.isEmpty()) {
                try{
                    insert errorLogs;
                }catch(Exception ex)
                {
                    System.debug('Exception :' + ex.getMessage() + ' Stacktrace :' + ex.getStackTraceString());
                }
            }
            
            //smsDisabled = false;  
            //verified = false;   
            
            /**********************/
        }
        contactList=null; // we need this line if we performed a write operation  because getContacts gets a fresh list now
        return null;
    }
    
    // This is our wrapper/container class. A container class is a class, a data structure, or an abstract data type whose instances are collections of other objects. In this example a wrapper class contains both the standard salesforce object Contact and a Boolean value
    public class cContact {
        public Contact con {get; set;}
        public Boolean selected {get; set;}
        
        //This is the contructor method. When we create a new cContact object we pass a Contact that is set to the con property. We also set the selected value to false
        public cContact(Contact c) {
            con = c;
            selected = false;
        }
    }
    //methods for API calls
    private String obtainAccessToken(List<Log__c> errorLogs)
    {
        String accessToken = (cache.Org.get('MCAccessToken')!= null) ? (String) cache.Org.get('MCAccessToken') : null;  
        Integer expiresSeconds;     
        
        if(accessToken == null)
        {
            String accessEndpointURL = Label.SMSAccessTokenEndpoint;
            
            HttpRequest accessReq = new HttpRequest();
            Http accesshttp = new Http();
            accessReq.setEndpoint(accessEndpointURL);
            accessReq.setMethod('POST');
            
            accessReq.setBody('{  "clientId": "'+ Label.MarketingCloudClientId + '" ,"clientSecret": "' + Label.MarketingCloudClientSecret + '" }' );         
            accessReq.setHeader('Content-Type' , 'application/json');
            
            HTTPResponse accessRes;
            String accessResponseBody;      
            
            try{             
                accessRes = accesshttp.send(accessReq); 
                accessResponseBody = accessRes.getBody(); 
                
                System.debug('accessResponseBody :' + accessResponseBody); 
            }catch(Exception ex){
                System.debug('Exception :' +  ex);
                errorLogs.add(LoggerUtility.createLog(className, 'sendSMS:obtainAccessToken', ex, 'Message :' + ex.getMessage() + ' Cause :' + ex.getCause() , UserInfo.getUserId()));
            }
            
            if(accessRes != null && accessRes.getStatusCode() == 200)
            {
                JSONParser parser = JSON.createParser(accessResponseBody);
                parser.nextToken();
                parser.nextValue();
                accessToken = parser.getText();
                
                parser.nextToken();
                parser.nextValue();
                expiresSeconds = parser.getIntegerValue();
                
                cache.Org.put('MCAccessToken', accessToken, expiresSeconds - 20, cache.Visibility.ALL, false);
                return accessToken;
            }else
            {
                System.debug('Exception :' );
                errorLogs.add(LoggerUtility.createLog(className, 'sendSMS:obtainAccessToken', null, 'accessResponseBody :' + accessResponseBody, UserInfo.getUserId()));
            }
            
            return null;
        }  
        //Cached access token not expired        
        return accessToken;         
        
    }
    
    // Send SMS API call
    private String sendSMSViaAPI(String accessToken, String smsSentVal,List<Log__c> errorLogs){
        
        String endpointURL = Label.SMSSendEndpoint; // This is for the first and only supported country which was AU
        String mobileNumber = contactRecord.MobilePhone.startswith('0') ? contactRecord.MobilePhone.substring(1) : contactRecord.MobilePhone;
        mobileNumber = mobileNumber.replaceAll(' ',''); // remove any spaces
        
        Map<String, Mobile_Country_Code__c> mobileCountryCodesMap = Mobile_Country_Code__c.getAll();
        
        Integer countryCode; String keyWordSuffix;
        Mobile_Country_Code__c ccode;
        
        if(mobileCountryCodesMap.containsKey(contactRecord.et4ae5__Mobile_Country_Code__c)) { 
            ccode = mobileCountryCodesMap.get(contactRecord.et4ae5__Mobile_Country_Code__c);
            
            countryCode =  (Integer)ccode.Numerical_Code__c;
            keyWordSuffix = ccode.Name;
        }  
        
        if(countryCode !=  null) {
            
            //SMS support has now been extended for few countries , each country uses it's own SFMC message Id i.e it's customised end point
            //For international numbers
            if(countryCode != 61 && ccode.Is_SMS_Supported__c){
                endpointURL = Label.SMSSendEndpoint_BaseUrl + ccode.MessageId__c + '/send';                         
            }
            
            mobileWithCountryCode = String.valueOf(countryCode) + mobileNumber;
            
            List<String> phoneNumber = new List<String>{ mobileWithCountryCode };
                System.debug('JSON.serialize(phoneNumber) :' + JSON.serialize(phoneNumber));
            
            Map<String, Object> objMap = new Map<String, Object>();         
            
            objMap.put('SendTime', '2018-10-10 20:01');
            objMap.put('messageText', 'Please verify your mobile number using the following code:'+ smsSentVal);
            objMap.put( 'Override', true);
            objMap.put('keyword',  (countryCode == 61) ? 'SYSTEM' : 'SYSTEM_' + keyWordSuffix);
            objMap.put( 'Resubscribe', true);
            objMap.put( 'Subscribe', true);
            objMap.put('mobileNumbers',phoneNumber);        
            
            String bodyMsg = JSON.serialize(objMap);
            
            System.debug('bodyMsg :' + bodyMsg);
            
            HttpRequest req = new HttpRequest();
            Http http = new Http();
            req.setEndpoint(endpointURL);
            req.setMethod('POST');
            
            req.setBody(bodyMsg);  
            req.setHeader('Authorization', 'Bearer '+ accessToken);
            req.setHeader('Content-Type' , 'application/json');
            
            HTTPResponse res;
            String responseBody;
            
            try{  
                res = http.send(req); 
                responseBody = res.getBody(); 
                System.debug('responseBody :' + responseBody);
            }catch(Exception ex){
                System.debug('Exception :' +  ex);
                errorLogs.add(LoggerUtility.createLog(className, 'sendSMS:sendSMSViaAPI', ex, 'Message :' + ex.getMessage() + ' Cause :' + ex.getCause() , UserInfo.getUserId()));
            }
            
            if(res != null && res.getStatusCode() == 202)
            {             
                return 'success';
            }
            else
            {
                errorLogs.add(LoggerUtility.createLog(className, 'sendSMS:sendSMSViaAPI', null, 'responseBody :' + responseBody, UserInfo.getUserId()));
            } 
            return 'failed';
        }
        
        return null;
        
    }
}
Visualforce Page:
<apex:page standardController="Contact"
    recordSetVar="Contact"
    extensions="selectDefaulterSMS"
    showHeader="true"
    sidebar="true"
    id="mucon"
>
    <apex:form id="muform">
        
        <apex:pageBlock title="SMS Defaulters Communication" mode="edit" id="mub1">
            <apex:pageMessages />
           <!-- <apex:pageBlockSection id="mus1">
                <apex:inputField value="{!contact.Default_SMS_Sent__c}" id="defaultSMS">
                    <apex:actionSupport event="onchange" rerender="muselectedlist"/>
                </apex:inputField>
            </apex:pageBlockSection> -->
            <apex:pageBlockButtons location="bottom" id="mubut">
                <apex:commandButton value="Send SMS" action="{!processSelected}" id="butsav"/>
                <apex:commandButton value="Cancel" action="{!cancel}" id="butcan"/>
            </apex:pageBlockButtons>

        <!-- get all the Ids for the contacts that needs to be sent with the SMS -->
        <apex:pageBlockTable value="{!contacts}" var="c" id="table">
                <apex:column >
                    <!-- This is our selected Boolean property in our wrapper class -->
                    <apex:inputCheckbox value="{!c.selected}"/>
                </apex:column>
                <!-- This is how we access the contact values within our cContact container/wrapper -->
                <apex:column value="{!c.con.Name}" />
                <apex:column value="{!c.con.MobilePhone}" />
                <apex:column value="{!c.con.Email}" />
                <apex:column value="{!c.con.Phone}" />
                <apex:column value="{!c.con.Default_SMS_Sent__c}" />
                <apex:column value="{!c.con.Status__c}" headerValue="Contact Status"/>
        </apex:pageBlockTable>
        </apex:pageBlock>
    </apex:form>
</apex:page>
I am trying to use VS Code for my two different dev org.
I am using Create project with Manifest option.
If i create Create project with Manifest option for first org and executes authorize and retrieve command, it works fine and i am able to retrieve all components,
now if i create 2nd new project with manifest option  and after authorizing the second org, when i open package.xml for second project and try to retrieve components,
it is not retrieving components for second org, later i realize it has retrieve all the component first projects directory
Hi all,
Can anyone tell me how to convert Excel file to Csv file into apex ?

TIA
Hi all,

We are trying to deploy selective components using SFDX (force:source:deploy -x package.xml). The package.xml only contains about 50 components, but it is trying to deploy 300 components (there are more than 300 components in the force-app folder, so it's not trying to deploy everything). There are three errors occuring on components not in the package.xml. Anyone undetstand why it is trying to deploy more than we have stated?

Thanks in advance.
Account IT = new Account();
String integrationtransactionId= '0016F00001y5mQW';
List<String> fields = new List<String>(Account.SObjectType.getDescribe().fields.getMap().keySet());
String soql='';
soql=soql+' select ';
soql=soql+String.join(fields, ',');
System.debug('checking'+soql);
soql=soql+' from Account where id=:integrationtransactionid';
System.debug('soqq'+soql);
IT=database.query(soql);
System.debug('itt'+IT);
String ack=IT.Request__c;  
System.debug('acksss--'+ack);

 
  • September 20, 2019
  • Like
  • 1
Here is my class:

public with sharing class BusinessUnitTriggerHandler 
{
    public static void checkDuplicate(List<BusinessUnits__c> units, Map<Id, BusinessUnits__c> oldMap, Boolean isInsert ) 
    {
      Map<String, Integer> businessUnitMap = new Map<String, Integer>();
      Set<String> lineOfBusiness = new Set<String>();
      Set<Id> contactIds = new Set<Id>();
      List<BusinessUnits__c> unitsToProcess = new List<BusinessUnits__c>();

      // Get System Admin profile Id
      Id profileId = [SELECT Id FROM Profile WHERE Name = 'System Administrator' LIMIT 1].Id;
      System.debug('UAC: profileId' + profileId);

      //Get current User Profile ID
      Id userProfileId = UserInfo.getProfileId() ;
    System.debug('UAC: userProfileId' + userProfileId);

    // Iterate over all business records 
        for( BusinessUnits__c bu : units )
        {  
          // When current user Non-Admin OR these fields are updated 
          if(  profileId != userProfileId &&
            ( isInsert || ( !isInsert && ( bu.LineOfBusiness__c != oldMap.get(bu.Id).LineOfBusiness__c || bu.Contact__c != oldMap.get(bu.Id).Contact__c))) ) 
          {
            lineOfBusiness.add(bu.LineOfBusiness__c);
            contactIds.add(bu.Contact__c);
            unitsToProcess.add(bu);
            businessUnitMap.put(bu.LineOfBusiness__c+bu.Contact__c, 0);
          }
        }
        System.debug('UAC: businessUnitMap' + businessUnitMap );
        if( businessUnitMap.size() == 0 ) return ;

        // Get existing Business records 
        for( BusinessUnits__c bu : [SELECT Id, LineOfBusiness__c, Contact__c FROM BusinessUnits__c 
                      WHERE Contact__c IN :contactIds AND LineOfBusiness__c IN :lineOfBusiness AND ID NOT IN :units ])
        {
          String key = bu.LineOfBusiness__c+bu.Contact__c;
          businessUnitMap.put( key, (businessUnitMap.get(key)+1) ) ;
        }
        System.debug('UAC: businessUnitMap' + businessUnitMap );
        if( businessUnitMap.size() == 0 ) return ;

        // Iterate again over inserted/updated records 
        for( BusinessUnits__c bu : unitsToProcess )
        {
          String key = bu.LineOfBusiness__c+bu.Contact__c;
          // When Already exists then show error
          if( businessUnitMap.containsKey(key) && businessUnitMap.get(key) > 0 ) bu.addError('Sorry. A Business Relationship for this Business Unit already exists for this Contact.');
        }
    }

    public static void changeOwner(List<BusinessUnits__c> units )
    {
        for(BusinessUnits__c bu : units )
        {
            if( bu.Sales_Rep__c != null && bu.OwnerId != bu.Sales_Rep__c  ) bu.OwnerId = bu.Sales_Rep__c ; 
        }
    }

    public static Map<String, BusinessUnitRulesManagement__c> lobAndUserRoleToBusinessUnitCS
    {
        get
        {
            if(lobAndUserRoleToBusinessUnitCS == null )
            {
                lobAndUserRoleToBusinessUnitCS = new Map<String, BusinessUnitRulesManagement__c>();
                for(BusinessUnitRulesManagement__c cs : BusinessUnitRulesManagement__c.getAll().values()) 
                {
                    lobAndUserRoleToBusinessUnitCS.put( cs.LineofBusiness__c + '' + cs.RoleDeveloperName__c, cs);
                }
            }
            //for(String key : lobAndUserRoleToBusinessUnitCS.keySet() ) System.debug('UAC: key ' + key  + ' value ' + lobAndUserRoleToBusinessUnitCS.get(key) );
            return lobAndUserRoleToBusinessUnitCS ;
        }
        private set ;
    }

    /**
    *   @Method:    updateContactFromCS()
    *   @Purpose:   When BusinessUnit is Updated then update SalesRep and EscrowOfficer fields from Contact based on Custom Setting fields 
    *   @Param:     List<BusinessUnits__c> units : List of new records - Trigger.new
    *               Map<Id,BusinessUnit__c> oldMap : map of old values - Trigger.oldMap
    *   @Return:    void : No return value
    *   @Date:      05/15/2017
    *
    *   @Updates: 
    */
    public static Boolean RUN_ONCE_UCFCS = true ; 
    public static void updateContactFromCS(List<BusinessUnits__c> units, Map<Id,BusinessUnits__c> oldMap, Boolean isInsert )
    {
        System.debug('UAC: BU updateContactFromCS START ' );
        Map<BusinessUnits__c, Id> businessUnitToContactId = new Map<BusinessUnits__c, Id>();
        Map<Id,Contact> existingContacts = new Map<Id,Contact>();
        Set<Id> contactIdsAddedForUpdate = new Set<Id>();
        List<Contact> contactsToUpdate = new List<Contact>();
        Set<Id> contactIds = new Set<Id>();
        Set<Id> userIds = new Set<Id>();
        Map<Id, String> userIdToUserRole = new Map<Id, String>();

        for(BusinessUnits__c bu : units)
        {
            BusinessUnits__c old =  !isInsert ? oldMap.get(bu.Id) : NULL ; 
            if( isInsert || ( !isInsert && (bu.Sales_Rep__c != old.Sales_Rep__c || bu.Escrow_Officer__c != old.Escrow_Officer__c)) ) 
            {
                if(bu.Sales_Rep__c != null ) userIds.add(bu.Sales_Rep__c);
                if(bu.Escrow_Officer__c != null && bu.Sales_Rep__c != bu.Escrow_Officer__c ) userIds.add(bu.Escrow_Officer__c);
                businessUnitToContactId.put(bu, bu.Contact__c);
                contactIds.add(bu.Contact__c);
            }
        }
        System.debug('UAC: businessUnitToContactId ' + businessUnitToContactId );

        for(User u : [SELECT Id, UserRole.DeveloperName FROM User WHERE ID IN :userIds ])
        {
            userIdToUserRole.put(u.Id, u.UserRole.DeveloperName );
        }
        System.debug('UAC: userIdToUserRole ' + userIdToUserRole );
        
        for(Contact con : Database.query( 'SELECT ' + getFields('Contact') + ' FROM Contact WHERE ID IN :contactIds ') )
        {
            existingContacts.put(con.Id, con);
        }

        for(BusinessUnits__c bu : businessUnitToContactId.keyset() )
        {
            String validUserRole = 
                //ContactTriggerHandler.currentUserRole == 'Administration' && 
                userIdToUserRole.containsKey(bu.Sales_Rep__c) ? userIdToUserRole.get(bu.Sales_Rep__c) : ContactTriggerHandler.currentUserRole ;

            // When no custom setting found for current User Role then Go Back
            if(!lobAndUserRoleToBusinessUnitCS.containsKey(bu.LineOfBusiness__c + '' + validUserRole)) continue ; 

            // Get Custom setting record
            BusinessUnitRulesManagement__c cs = lobAndUserRoleToBusinessUnitCS.get(bu.LineOfBusiness__c + '' + validUserRole);
            System.debug('UAC: cs ' + cs );

            if(cs == null ) continue ; 
            
            // Get related Contact 
            Contact con = existingContacts.get(businessUnitToContactId.get(bu));

            // When SalesRep or EscrowOfficer changed 
            if((bu.Sales_Rep__c != con.get(cs.SalesRepFieldonContactAPIName__c) || bu.Escrow_Officer__c != con.get(cs.EscrowOfficerFieldonContactAPIName__c) ) 
                    && !contactIdsAddedForUpdate.contains(con.Id) )
            {
                contactIdsAddedForUpdate.add(con.Id);
                Contact newContact = new Contact();
                newContact.Id = con.Id;
                System.debug('UAC: bu.Sales_Rep__c ' + bu.Sales_Rep__c );
                System.debug('UAC: bu.Escrow_Officer__c ' + bu.Escrow_Officer__c );
                if( !String.isBlank(cs.SalesRepFieldonContactAPIName__c)) newContact.put(cs.SalesRepFieldonContactAPIName__c, bu.Sales_Rep__c);
                if( !String.isBlank(cs.EscrowOfficerFieldonContactAPIName__c)) newContact.put(cs.EscrowOfficerFieldonContactAPIName__c, bu.Escrow_Officer__c);
                contactsToUpdate.add(newContact);
            } 
        }

        System.debug('UAC: contactsToUpdate ' + contactsToUpdate );

        // Update Contacts 
        if(contactsToUpdate.size() > 0 ) 
        {
            ContactTriggerHandler.RUN_ONCE_UBUFCS = false ;  
            BusinessUnitTriggerHandler.RUN_ONCE_UCFCS = false ;
            update contactsToUpdate ;
            ContactTriggerHandler.RUN_ONCE_UBUFCS = true ;  
            BusinessUnitTriggerHandler.RUN_ONCE_UCFCS = true ;
        }

        System.debug('UAC: BU updateContactFromCS END ' );
    
    }

    /**
    *   @Method:    getFields()
    *   @Purpose:   Use to get all fields of passing object  
    *   @Param:     String objName for which you want to get fields
    *   @Return:    Comma seprated fields
    *   @Date:      05/18/2017
    *
    *   @Updates: 
    */
    private static String getFields(String objectName)
    {
        //Broke this out of formatQuery because it could be used separately
        String fields = '';
        
        // Get All Objects List
        Map<String, Schema.SObjectType> gd = Schema.getGlobalDescribe();
        
        // Get object detail which passed as argument
        SObjectType objectType = gd.get(objectName);

        // Get passed object detail
        Schema.DescribeSObjectResult r = objectType.getDescribe();

        //Get all fields for passed object 
        Map<String, Schema.SObjectField> fieldMap = r.fields.getMap();

        // Itterate over all fields and check one by one 
        for (String f: fieldMap.keySet())
        { 
            // Get current field 
            Schema.SObjectField sof = fieldMap.get(f);
            // Get current field detail
            Schema.DescribeFieldResult dfr = sof.getDescribe();

            // when current field is accessible, creatable and defaultonCreare then concatinate in field string
            if( dfr.isAccessible() )
            {
                String fname = dfr.getName(); 
                fields += fname + ', '; 
            }
        }
        
        // remove last comma
        fields = fields.substring(0, fields.length() - 2);
        return fields;
    }


    public static Map<String, BusinessUnitRulesManagement__c> lobToBusinessUnitCS
    {
        get
        {
            if(lobToBusinessUnitCS == null )
            {
                lobToBusinessUnitCS = new Map<String, BusinessUnitRulesManagement__c>();
                for(BusinessUnitRulesManagement__c cs : BusinessUnitRulesManagement__c.getAll().values()) 
                {
                    if(!lobToBusinessUnitCS.containsKey(cs.LineofBusiness__c)) lobToBusinessUnitCS.put( cs.LineofBusiness__c, cs);
                }
            }
            //for(String key : lobToBusinessUnitCS.keySet() ) System.debug('UAC: key ' + key  + ' value ' + lobToBusinessUnitCS.get(key) );
            return lobToBusinessUnitCS ;
        }
        private set ;
    }

    /**
    *   @Method:    clearValueOnContact()
    *   @Purpose:   When BusinessUnit is Updated then update and clearOut SalesRep and EscrowOfficer fields from Contact based on Custom Setting fields 
    *   @Param:     List<BusinessUnits__c> units : List of new records - Trigger.new
    *               Map<Id,BusinessUnit__c> oldMap : map of old values - Trigger.oldMap
    *   @Return:    void : No return value
    *   @Date:      05/15/2017
    *
    *   @Updates: 
    */
    public static void clearValueOnContact(List<BusinessUnits__c> units)
    {
        System.debug('UAC: BU clearValueOnContact START ' );
     
        
     
        Map<Id, String> contactIdToLOB = new Map<Id, String>();
        Map<Id,Contact> contacts = new Map<Id,Contact>();

        // Iterate over BusinessUnit 
        for(BusinessUnits__c bu : units )
        {
            if(bu.Contact__c != null) contactIdToLOB.put(bu.Contact__c, bu.LineOfBusiness__c);
        }
        System.debug('UAC: BU contactIdToLOB ' + contactIdToLOB );
        if(contactIdToLOB.size() == 0) 
           return ; 

        // Get related Contacts 
        contacts = new Map<Id, Contact>( [SELECT Id FROM Contact WHERE ID IN :contactIdToLOB.keyset() ]);

        // Iterate over ContactIds 
        for(Id contactId : contactIdToLOB.keyset() )
        {   
            // Get Custom Setting Business Unit
            BusinessUnitRulesManagement__c cs = lobToBusinessUnitCS.get(contactIdToLOB.get(contactId));
            System.debug('UAC: cs ' + cs );

            if(cs == null ) continue ; 

            // Get Contact 
            Contact con = contacts.get(contactId);

            // Clear Out Values on Contact 
            if( !String.isBlank(cs.SalesRepFieldonContactAPIName__c)) con.put(cs.SalesRepFieldonContactAPIName__c, null);
            if( !String.isBlank(cs.EscrowOfficerFieldonContactAPIName__c)) con.put(cs.EscrowOfficerFieldonContactAPIName__c, null);
            System.debug('UAC: con ' + con );
        }

        // Update Contact
        ContactTriggerHandler.RUN_ONCE_UBUFCS = false ;
        update contacts.values() ;
        ContactTriggerHandler.RUN_ONCE_UBUFCS = true ; 

        System.debug('UAC: BU clearValueOnContact End ' );
    }

}

Test class:

@isTest
private class BusinessUnitTriggerHandlerTest 
{
      Map<String, Integer> businessUnitMap = new Map<String, Integer>();
      Set<String> lineOfBusiness = new Set<String>();
      Set<Id> contactIds = new Set<Id>();
      List<BusinessUnits__c> unitsToProcess = new List<BusinessUnits__c>();
      Set<Id> userIds = new Set<Id>();
      Map<Id, String> userIdToUserRole = new Map<Id, String>();
     Map<BusinessUnits__c, Id> businessUnitToContactId = new Map<BusinessUnits__c, Id>();
     Map<Id,Contact> existingContacts = new Map<Id,Contact>();
     Map<String, BusinessUnitRulesManagement__c> lobToBusinessUnitCS;
       Map<Id, String> contactIdToLOB = new Map<Id, String>();
        Map<Id,Contact> contacts = new Map<Id,Contact>();
    static testMethod void testCheckDuplicate() 
    {
         
   
        Profile profile = [Select Id from Profile where name = 'ORT Direct Sales User'];
        //UserRole ur = [Select Id from UserRole where UserRole.DeveloperName = 'Central_Direct_Agency'];

        User nonAdminUser = new User( ProfileId = profile.Id, Username = System.now().millisecond() + 'test2@test.com.dev',UserRoleId = '00E1G000000IWzyUAG',
                                    Alias = 'batman', Email='bruce.wayne@wayneenterprises.com', EmailEncodingKey='UTF-8',Firstname='Bruce',
                                    Lastname='Wayne',LanguageLocaleKey='en_US',LocaleSidKey='en_US',TimeZoneSidKey='America/Chicago' );
        System.runAs(new User( Id = UserInfo.getUserId() ))
        {
            Database.insert(nonAdminUser);
        }

        Account acc = TestUtility.createAccount( TestUtility.default_account_rt, false );
        acc.Name = 'sfdcpoint';
        acc.Account_Status__c = 'Active';
        acc.AccountNumber = '001';
        insert acc; 
    
        System.runAs(nonAdminUser)
        {
            Contact cont = TestUtility.createContact( TestUtility.default_contact_rt , acc, false ); 
            cont.MailingStreet = 'Test Street' ;
            cont.MailingCity = 'Minneapolis';
            cont.MailingState = 'MN';
            cont.MailingPostalCode = '55347';
            cont.MailingCountry = 'United States' ; 
            insert cont;
            
            
            BusinessUnitRulesManagement__c cs = new BusinessUnitRulesManagement__c();
            cs.Name = 'AgencyManager';
            cs.EscrowOfficerFieldonContactAPIName__c = 'Text';
            cs.LineofBusiness__c = 'testlob';
            cs.RoleDeveloperName__c = 'uniquetest';
            cs.SalesRepFieldonContactAPIName__c = 'conttext';
            cs.Status__c = 'alltext';
            insert cs;
            Id userId = UserInfo.getUserId() ;
          

            BusinessUnits__c bu = new BusinessUnits__c( Contact__c = cont.Id, LineOfBusiness__c = ' Agency',Sales_Rep__c = UserId );
          
            insert bu ; 
  
            try
            {
                BusinessUnits__c bu1 = new BusinessUnits__c( Contact__c = cont.Id,LineOfBusiness__c = 'Western Title Division',Sales_Rep__c = UserId  );
                insert bu1 ;  
            }
            catch(DmlException de )
            {

            } 
  

        }
    

    }
 
Hi All,

I ahve created one input form where users can fill in their details and save records.The input form is a VF page and save record logic implemented in controller and everything works fine.
Now my issue is when the record is saved then an email should go to the email id specified in input form.This email id can be external also(not a salesforce user). If its a Salesforce user I can go with PB,Workflow rules/email alerts etc.
Below is my VF page
<apex:page standardController="Driver_Survey__c" extensions="GrabSurveyForDriverController" sidebar="false" lightningStylesheets="true">
    
    
    <apex:form > 
        
        <apex:pageBlock mode="edit" >
            <apex:pageBlockSection columns="1" collapsible="false" title="Driver Information"  >
                <apex:inputField label="Name" value="{!survey.Name__c}" required="true"/>
                <apex:inputField label="Mobile" value="{!survey.Mobile__c}" required="true" />
                <apex:inputField label="Email" value="{!survey.Email__c}" required="true" />
            </apex:pageBlockSection>

           
            <apex:pageBlockButtons >
             
                <apex:commandButton value="Save" action="{!doFullSave}"/>
                <apex:commandButton value="Cancel" action="{!doCancel}" immediate="true"/>
        
            </apex:pageBlockButtons> 
        </apex:pageBlock>
      
    </apex:form>
</apex:page>

Below is my controller
public class SurveyForDriverController{

    public Grab_Driver_Survey__c survey{get;set;}
     
    public SurveyForDriverController(ApexPages.StandardController controller){
         survey=new Driver_Survey__c();
       
    }
    
    public PageReference doFullSave(){
    
       	insert survey; 
        system.debug('message110>>'+survey );
        
      
        system.debug('message2>>'+survey );
        PageReference pageRef = new PageReference('/'+survey.Id);
        pageRef.setRedirect(true);
        return pageRef;
    }
    public PageReference doCancel(){
        PageReference pageRef = new PageReference('/');
            pageRef.setRedirect(true);
            return pageRef;
    }    
}

Below is screenshot of the vf page
User-added imageSo whatever email id specified in the Email field above will receive an email upon the record save.
On VF Page I am using input field for Email and at object level I have Text field as "Email" to store the value from VF page to object

Kindly help

Many thanks in advance​​​​​​​
Account IT = new Account();
String integrationtransactionId= '0016F00001y5mQW';
List<String> fields = new List<String>(Account.SObjectType.getDescribe().fields.getMap().keySet());
String soql='';
soql=soql+' select ';
soql=soql+String.join(fields, ',');
System.debug('checking'+soql);
soql=soql+' from Account where id=:integrationtransactionid';
System.debug('soqq'+soql);
IT=database.query(soql);
System.debug('itt'+IT);
String ack=IT.Request__c;  
System.debug('acksss--'+ack);

 
  • September 20, 2019
  • Like
  • 1