2

I am running into an issue with my method for test where I insert contact records that are in a list and then try to pull the id's to associate it with a different list.

When I do my debug for the Contact__c which should be updated with sr.Contact__c = conts[i].id; it is pulling in a null value.

If I insert the list for contacts the id's should be associated with the list that I am then pulling the id's from correct?

    public with sharing class CC_UnitTestUtil {

    static Database.DMLOptions dml = new Database.DMLOptions();

    public static void createCustomSetting(String Area) {
        // P Sutherland Area Added for Trigger 
        CC_Area_to_Process__c cca = new CC_Area_to_Process__c(Name=Area,TimeZoneSidKey__c='America/Phoenix');
        upsert cca;
    }

    public static list<Sale_Related_Contact__c> createSaleRelatedContact(Id saleId,  list<String> types){
        boolean dmActive = Utils.duplicateMgmtActive('Contact');        
        dml.DuplicateRuleHeader.allowSave = true;
        Account a = new Account(Name = 'TestAcct');
        if (dmActive)
            database.insert(a, dml);
        else
            insert a;
        SuperUserAccount__c sua = new SuperUserAccount__c(AccountID__c = a.Id, Name='Contact1');
        try{insert sua;}catch(Exception e){}
        list<Contact> conts = new list<Contact>();
        for(Integer i=0;i<types.size();i++){
            Contact c = new Contact(LastName=types[i], FirstName=types[i], Email='[email protected]', AccountId= a.id, Related_Company__c= a.Id);
            if ( types[i] == 'Design Studio' || types[i] == 'Additional Meritage Employee')    
                c.User_ID__c = UserInfo.getUserId();
            conts.add(c);
            system.debug('@-@ User id '+ c.User_ID__c);
        }

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

        List<Database.SaveResult> res = Database.insert(conts, false);

        // Iterate through each returned result
        for (Database.SaveResult sr : res) {
            if (sr.isSuccess()) {
                // Operation was successful, so get the ID of the record that was processed
                System.debug('@-@ Successfully inserted contact. Contact ID: ' + sr.getId());
            }
            else {
                // Operation failed, so get all errors                
                for(Database.Error err : sr.getErrors()) {
                    System.debug('@-@ The following error has occurred.');                    
                    System.debug(err.getStatusCode() + ':@-@  ' + err.getMessage());
                    System.debug('@-@ Contact fields that affected this error: ' + err.getFields());
                }
            }
        }

        system.debug('@-@ dmActive before insert ' + dmActive);
        system.debug('@-@ contact List after insert ' + conts);
        system.debug('@-@ contact id after insert ' + conts[0].id);

        list<Sale_Related_Contact__c>  src = new list<Sale_Related_Contact__c> ();

        for(Integer i=0;i<types.size();i++){
            Sale_Related_Contact__c sr = new Sale_Related_Contact__c();
            sr.Sale__c = saleId;
            sr.Type__c = types[i];
            sr.Company_Name__c = a.id;
            sr.Contact__c = conts[i].Id;
            src.add(sr);
            system.debug('@-@ ids for SRC ' + sr.Contact__c);
        }

        system.debug('@-@ size = ' + src.size());
        if(src.size()>0){
            insert src;
        }
        return src;
    }
    public static List<Sale_Related_Contact__c> createSaleRelatedContactMonterey(Id saleId,  List<String> types){
        boolean dmActive = Utils.duplicateMgmtActive('Contact');        
        dml.DuplicateRuleHeader.allowSave = true;        
        Account a = new Account(Name = 'TestAcct');
        if (dmActive)
            database.insert(a, dml);
        else
            insert a;
        SuperUserAccount__c sua = new SuperUserAccount__c(AccountID__c = a.Id, Name='Contact1M');
        insert sua;
        list<Contact> conts = new list<Contact>();
        for(Integer i=0;i<types.size();i++){
            Contact c = new Contact(LastName=types[0], FirstName='John', Email='[email protected]', AccountId= a.id, Related_Company__c= a.Id);    
            conts.add(c);
        }
        if (dmActive)
            database.insert(conts, dml);
        else
            insert conts;
        list<Sale_Related_Contact__c>  src = new list<Sale_Related_Contact__c> ();

        for(Integer i=0;i<types.size();i++){
            Sale_Related_Contact__c sr = new Sale_Related_Contact__c();
            sr.Sale__c = saleId;
            sr.Type__c = types[i];
            sr.Company_Name__c = a.id;
            sr.Contact__c = conts[i].Id;
            src.add(sr);
        }
        if(src.size()>0){
            insert src;
        }
        return src;
    }
    // create sale
    public static list<Sale__c> createSale(List<Lot__c> lots, List<Plan__c> plans, Id primarySalesAssociate,  List<Opportunity__c> opps) {

        list<Sale__c> sales = new list<Sale__c>();

        for ( Integer i=0; i < opps.size(); i++ ) {
            Sale__c s = new Sale__c();
            s.Opportunity__c = opps[i].Id;
            s.Plan__c = plans[i].Id;
            s.Lot__c = lots[i].id;
            s.Swing__c ='Right';
            s.Customer_Contract_First_Name__c = opps[i].Customer_Name__r.FirstName;
            s.Customer_Contract_Last_Name__c = opps[i].Customer_Name__r.LastName;
            s.Customer_Home_Phone_Number__c = opps[i].Customer_Name__r.Phone;
            s.Customer_Email_Address__c = opps[i].Customer_Name__r.PersonEmail;
            s.Customer_Name_Lookup__c = opps[i].Customer_Name__c;
           // s.Approval_Status__c = 'Submitted';
            s.Approval_Type__c = 'Sale';
            s.Primary_Sales_Associate__c = primarySalesAssociate;
            sales.add(s);
        }
        insert sales;
        return sales;
    }
    // create lot
    public static list<Lot__c> createLot(String comId, Integer howMany) {
        list<Lot__c> lots = new list<Lot__c>();
        for ( Integer i = 0; i < howMany; i++ ) {
             Lot__c li = new Lot__c();
             li.Community__c = comID;
             li.Lot_Number__c = string.valueof(i);
             li.Lot_Address__c = '300 Chicago';
             li.City__c = 'Chicago';
             li.State__c = 'IL';
             li.Postal_Zip_Code__c = '60657';
             li.Status__c = 'Available';
             li.Base_House_Price__c = i;
             li.Lot_Premium__c = i; 
             lots.add(li);
        }
        insert lots;
        return lots;
    }
    // create oppotunities
    public static list<Opportunity__c> createOpportunity(String comId, List<Account> accts) {

        list<Opportunity__c> opps = new list<Opportunity__c>();

        Opportunity__c opp = new Opportunity__c();
        for ( Integer i=0; i < accts.size(); i++ ) {
            opp = new Opportunity__c();
            opp.Community__c = comid;
            opp.Customer_Name__c = accts[i].Id;
            opp.Opportunity_Status__c = 'Active';
            opp.Customer_Status__c = 'A-Prospect';
            opp.Realtor_Representing__c = 'No'; 
            opp.How_did_you_learn_about_Meritage_Homes__c = 'Realtor';
            opp.Web_Lead__c = true;
            opps.add(opp);
        }
        insert opps;
        return opps;
    }
    public static Id personAccountRecTypeId; 
    // create accounts
    public static list<Account> createAccount(Integer howMany)  {
        list<Account> accts = new list<Account>();
        for ( Integer i=0; i < howMany; i++ ) {
            Account a = new Account();
            a.FirstName = 'Tester';
            a.LastName = 'TestCust'+ String.valueOf(i);
            a.PersonEmail = String.valueOf(i)+'[email protected]';
            accts.add(a);
        }
        insert accts;
        return accts;
    }
    // create accounts monterey
    public static list<Account> createAccountMonterey(Integer howMany)  {
        list<Account> accts = new list<Account>();
        for ( Integer i=0; i < howMany; i++ ) {
            Account a = new Account();
            a.FirstName = 'Tester';
            a.LastName = 'Monterey'+ String.valueOf(i);
            a.PersonEmail = String.valueOf(i)+'[email protected]';
            accts.add(a);
        }
        insert accts;
        return accts;
    }
    // create plan
    public static list<Plan__c> createPlan(String comId, Integer howMany, String status) {
        list<Plan__c> complans = new list<Plan__c>();
        for ( Integer i = 0; i < howMany; i++ ) {
             Plan__c pi = new Plan__c();
             pi.Community__c = comId;
             pi.Amount_Base_Price__c = i;
             pi.Square_Feet__c = i;
             pi.Plan_Number__c = '900' + string.valueof(i);
             pi.Elevation__c = string.valueof(i);
             pi.Status__c = status;
             complans.add(pi);
        }
        insert complans;
        return complans;
    } 


    // create community 
    public static Community__c createCommunity(String dId) {

        Community_Sheet__c cs = createCommunitySheet(dID);

        Community__c comm = new Community__c();
        comm.Name = 'Test Comm';
        comm.Status__c = 'Active';
        comm.Division__c = dID;
        comm.Maximum_Incentive__c = 0;
        comm.Area__c = '900';
        comm.Community_Number__c = 'Tes';
        comm.Phase__c = '000';
        comm.Community_Demographic_Information__c = cs.id;
        insert comm;
        return comm;
    }

    // create monterey community 
    public static Community__c createCommunityMonterey(String dId) {

        Community_Sheet__c cs = createCommunitySheet(dID);

        Community__c comm = new Community__c();
        comm.Brand__c = 'Monterey Homes';
        comm.Name = 'Test Monterey Comm';
        comm.Status__c = 'Active';
        comm.Division__c = dID;
        comm.Maximum_Incentive__c = 0;
        comm.Area__c = '900';
        comm.Community_Number__c = 'TestM';
        comm.Phase__c = '000';
        comm.Community_Demographic_Information__c = cs.id;
        insert comm;
        return comm;
    }

    // create community sheet
    public static Community_Sheet__c createCommunitySheet(String dId){
        Community_Sheet__c cs = new Community_Sheet__c();
        cs.Division__c = dId;
        cs.Status__c = 'Active';
        cs.Marketing_Name__c = 'Tes Com S';
        insert cs;
        return cs;
    }    
    // create division
     public static Division__c createDivision() {
        Division__c div = new Division__c(Name='test div',JDE_Division_Key__c = 'Tes',status__c='Active');
        insert div;
        return div;
    }

    // create division monterey
     public static Division__c createDivisionMonterey() {
        Division__c div = new Division__c(Name='test div 1',JDE_Division_Key__c = 'Tee',status__c='Active');
        insert div;
        return div;
    }

    public static Id profileId;
    // create buyer users
    public static List<User> createUsers(Integer howMany,String profileName){
         String type; 
         if(profileId == null){
            profileId = CC_Constants.BuyersProfileId;
            type = 'com';
         } 

         list<User> listOfUsers = new list<User>();

         for (Integer i = 0; i < howMany; i++){
             User u = new User(alias = 'u' + type +i , email='[email protected]',
                emailencodingkey='UTF-8', lastname='Test' + type +i, languagelocalekey='en_US',
                localesidkey='en_US', profileid = profileId, 
                timezonesidkey='America/Los_Angeles', username='[email protected].' + type + i);

             listOfUsers.add(u);
         }
         insert listOfUsers;
     return listOfUsers;
    }

    public static List<User> createDesignerUsers(Integer howMany, String profileName) {

        Profile p = [SELECT Id, Name FROM Profile WHERE Name = :profileName LIMIT 1];

        list<User> listOfUsers = new list<User>();

        for (Integer i = 0; i < howMany; i++){
             User u = new User(alias = 'u'  +i , email='[email protected]',
                emailencodingkey='UTF-8', lastname='Test' +i, languagelocalekey='en_US',
                localesidkey='en_US', profileid = p.Id, dsfs__DSProSFUsername__c = 'testing',
                timezonesidkey='America/Los_Angeles', username='[email protected].' + i);     

             listOfUsers.add(u);
        }
        insert listOfUsers;
        return listOfUsers;
    }
    }
public with sharing class ContactFunctions {

public static void UpdateParentAccountID (Contact[] records){
    //List<User> usrLst; // to assign OSC
    //User oscUsr;
    // Get the Contact AccountId from the custom setting vs the hard coded way 360vantage did it.
    System.debug('XXXXXXX Contact records equals   ' + records);
    String AccountId = SuperUserAccount__c.getValues('Contact').AccountID__c;
    for ( Contact c: records) {
        if ( !c.IsPersonAccount ) {
            if ( c.Related_Company__c != null )
                c.AccountID = c.Related_Company__c;
            else
                c.AccountID = AccountId;                    
        }
    }   
}
}
4
  • I'm assuming Database.insert() isn't populating the ids as you would expect. Also, I don't see a @isTest on the method so this doesn't look like a normal unit test environment Commented Jan 25, 2020 at 19:40
  • This is part of a bigger test class. is Database.insert() not the correct way to accomplish this?
    – SoleHack
    Commented Jan 25, 2020 at 19:58
  • I updated the post to show the entire class. This method is just a creation method for test. When I debug the list it gives me the list for contacts after the database.insert() is followed. Then when I debug for the id's after the insert if gives me null values for them.
    – SoleHack
    Commented Jan 25, 2020 at 20:41
  • Are duplicate rules active in your org for Contact? Commented Jan 26, 2020 at 5:32

1 Answer 1

3

This is happening because you are using the Database.insert() method with DMLOptions. The DMLOptions object contains a property called optAllOrNone. By default which is set to false.

According to documentation.

If optAllOrNone is set to true, all changes are rolled back if any record causes errors. The default for this property is false and successfully processed records are committed while records with errors aren't.

So as by default optAllOrNone is false, your transaction will not fail if one or a few records from your contact list conts is failed to insert due to some validation or a duplication rule. All the records that do not have any issues will be saved to the database others are not. So when you are referring them in a list, the records failed to save to the database will not have the 'Id'.

Let us see an example here.

Contact con = new Contact(lastname = 'test');
Contact con2 = new Contact();// fails to insert
Database.DMLOptions dml = new Database.DMLOptions();
Database.SaveResult[] sr= database.insert(new List<contact>{con, con2}, dml);
system.debug('con ' + con.Id);
system.debug('con2 ' + con2.Id);

This gives me null for con2.Id because I have missed the required field here, which causes DML to fail. See the debug logs below.

enter image description here

So, you need to handle this condition, by adding a null check to the contact Id field.

DMLOptions

Database.insert

11
  • Thanks @rahul gawale for the information on this. So are you referring to me putting an if null on 'sr.Contact__c = conts[i].Id;'? I ask because our validation is that the sales related contact needs to have a contact associated with it.
    – SoleHack
    Commented Jan 26, 2020 at 23:38
  • I also ran the debug logs on this for my org. USER_DEBUG [44]|DEBUG|@-@ contact id after insert (Contact:{LastName=Lender, FirstName=Lender, [email protected], AccountId=0010v00000UH719AAD, Related_Company__c=0010v00000UH719AAD, Relationship__c=Referral}, Contact:{LastName=Primary Title Company, FirstName=Primary Title Company, [email protected], AccountId=0010v00000UH719AAD, Related_Company__c=0010v00000UH719AAD, Relationship__c=Referral}, Contact:{LastName=Design Studio, FirstName=Design Studio, [email protected], AccountId=0010v00000UH719AAD, Related_Com
    – SoleHack
    Commented Jan 26, 2020 at 23:40
  • USER_DEBUG [45]|DEBUG|@-@ contact id 1 after insert null USER_DEBUG [45]|DEBUG|@-@ contact id 2 after insert null USER_DEBUG [45]|DEBUG|@-@ contact id 3 after insert null USER_DEBUG [58]|DEBUG|@-@ ids for SRC null USER_DEBUG [58]|DEBUG|@-@ ids for SRC null USER_DEBUG [58]|DEBUG|@-@ ids for SRC null USER_DEBUG [61]|DEBUG|@-@ size = 3
    – SoleHack
    Commented Jan 26, 2020 at 23:40
  • try debugging database.saveresult, may be you need to resolve the issues for contacts. Commented Jan 27, 2020 at 2:39
  • I updated the insert for conts with adding a size NPE check and I get an error
    – SoleHack
    Commented Jan 27, 2020 at 6:17

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .