You need to sign in to do that
Don't have an account?
jsacpt24
id's on list are not pulling into new list
I am running into an issue with my data building class that we are using for test methods. I have a method that is supposed to 'createSaleRelatedContact'. It inserts the account then creates a user account. Once it has created those it will then create the contact record. After it creates those contact records it is supposed to create the sale related contact records and use the contact records from the previous list. and insert those new records. We have a validation rule set that it cannot create these records with Null contact values. When we set the debugs it is pulling null values into this list for SRC. Not sure why it is pulling a null id if we are inserting this list prior to? Am I doing something wrong here?
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){} system.debug('@-@ SuperUserAccount__c '+ sua.id); 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='test@test.com', 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 (dmActive) database.insert(conts, dml); else insert conts; 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='test2346234@test.com', 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)+'7s@mh.com'; 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)+'7s@mh.com'; 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='testtest@test.com', emailencodingkey='UTF-8', lastname='Test' + type +i, languagelocalekey='en_US', localesidkey='en_US', profileid = profileId, timezonesidkey='America/Los_Angeles', username='test@testtest.com.' + 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='testtest@test.com', emailencodingkey='UTF-8', lastname='Test' +i, languagelocalekey='en_US', localesidkey='en_US', profileid = p.Id, dsfs__DSProSFUsername__c = 'testing', timezonesidkey='America/Los_Angeles', username='test@testtest.com.' + i); listOfUsers.add(u); } insert listOfUsers; return listOfUsers; } }
public with sharing class Utils { private static map<Schema.SObjectType,map<String,ID>> rtypesCache; static { rtypesCache = new map<Schema.SObjectType,map<String,ID>>(); } public static map<String, ID> getRecordTypes( Schema.SObjectType token) { map<String, ID> mapRecTypes = new map<String, ID>(); mapRecTypes = getRecordTypes(token, true); return mapRecTypes; } public static map<String, ID> getRecordTypes( Schema.SObjectType token, Boolean dname) { // Do we already have a result? map<String, ID> mapRecordTypes = rtypesCache.get(token); if (mapRecordTypes != null) return mapRecordTypes; // Not Cached so build it out mapRecordTypes = new map<String, ID>(); Schema.DescribeSObjectResult obj = token.getDescribe(); String soql = 'SELECT Id, Name, DeveloperName ' + 'FROM RecordType ' + 'WHERE SObjectType = \'' + String.escapeSingleQuotes(obj.getName()) + '\' ' + 'AND IsActive = TRUE'; list<SObject> results; try { results = Database.query(soql); } catch (Exception ex) { results = new list<SObject>(); } map<ID,Schema.RecordTypeInfo> recordTypeInfos = obj.getRecordTypeInfosByID(); for (SObject rt : results) { if (recordTypeInfos.get(rt.Id).isAvailable()) { if (dname) mapRecordTypes.put(String.valueOf(rt.get('DeveloperName')),rt.Id); else mapRecordTypes.put(String.valueOf(rt.get('Name')),rt.Id); } } rtypesCache.put(token,mapRecordTypes); return mapRecordTypes; } public class CloneChildrenResult { public sObject[] oldObjs; public sObject[] newObjs; } // returns two lists: the list of original values and list of clones public static CloneChildrenResult cloneChildrenAndAdopt(String objectName, String parentField, String parentId, String newParentId) { CloneChildrenResult result = cloneChildren(objectName, parentField, parentId); for ( sObject obj: result.newObjs ) { obj.put(parentField, newParentId); } insert result.newObjs; return result; } // returns two lists: the list of original values and list of clones public static CloneChildrenResult cloneChildren(String objectName, String parentField, String parentId) { String soql = getCreatableFieldsSOQL(objectName, parentField +' = \''+ parentId +'\''); sObject[] oldObjs = Database.query(soql); sObject[] newObjs = new list<sObject>(); for ( sObject obj: oldObjs ) { sObject newObj = obj.clone(false); newObjs.add(newObj); } CloneChildrenResult retval = new CloneChildrenResult(); retval.oldObjs = oldObjs; retval.newObjs = newObjs; return retval; } // Returns a dynamic SOQL statement for the whole object, includes only creatable fields since we will be inserting a cloned result of this query public static string getCreatableFieldsSOQL(String objectName, String whereClause) { String selects = ''; if (whereClause == null || whereClause == '') { return null; } // Get a map of field name and field token map<String, Schema.SObjectField> fMap = Schema.getGlobalDescribe().get(objectName.toLowerCase()).getDescribe().Fields.getMap(); list<string> selectFields = new list<string>(); if (fMap != null){ for ( Schema.SObjectField ft : fMap.values() ){ // loop through all field tokens (ft) Schema.DescribeFieldResult fd = ft.getDescribe(); if ( fd.isCreateable() && fd.getName() != 'Location__c'){ // field is creatable selectFields.add(fd.getName()); } } } if ( !selectFields.isEmpty() ) { selects = String.join(selectFields,','); //for ( string s:selectFields ) { // selects += s + ','; //} //if ( selects.endsWith(',') ){selects = selects.substring(0,selects.lastIndexOf(','));} } String retval = 'SELECT ' + selects + ' FROM ' + objectName + ' WHERE ' + whereClause; //System.Debug(LoggingLevel.DEBUG, '>>> getCreatableFieldsSOQL SOQL: ' + retval); return retval; } // Emil: overload public static string getAllFieldsSOQL(String objectName, String whereClause) { return getAllFieldsSOQL(objectName, whereClause, null); } // Emil: overload public static string getAllFieldsSOQL(String objectName, String whereClause, String orderBy) { return getAllFieldsSOQL(objectName, whereClause, orderBy, null); } // Mohan // Emil: added orderBy and ExtraFields public static string getAllFieldsSOQL(String objectName, String whereClause, String orderBy, String extraFields) { String selects = ''; if (whereClause == null || whereClause == '') { return null; } // Get a map of field name and field token map<String, Schema.SObjectField> fMap = Schema.getGlobalDescribe().get(objectName.toLowerCase()).getDescribe().Fields.getMap(); list<string> selectFields = new list<string>(); if ( fMap != null ){ for ( Schema.SObjectField ft : fMap.values() ){ // loop through all field tokens (ft) Schema.DescribeFieldResult fd = ft.getDescribe(); // describe each field (fd) if ( fd.getName() != 'Location__c' ) selectFields.add(fd.getName()); } } if ( !selectFields.isEmpty() ) { selects = String.join(selectFields,','); //for ( string s:selectFields ) { // selects += s + ','; //} //if ( selects.endsWith(',') ){selects = selects.substring(0,selects.lastIndexOf(','));} if ( extraFields != null && extraFields != '' ) selects += ', ' + extraFields; } String retval = 'SELECT ' + selects + ' FROM ' + objectName + ' WHERE ' + whereClause; if ( orderBy != null && orderBy != '' ) retval += ' ORDER BY ' + orderBy; //System.Debug(LoggingLevel.DEBUG, '>>> getAllFieldsSOQLv2 SOQL: ' + retval); return retval; } public static void deleteChildren(String objectName, String parentField, String parentId) { objectName = String.escapeSingleQuotes(objectName); parentField = String.escapeSingleQuotes(parentField); SObject[] delThese = Database.query('SELECT Id FROM ' + objectName + ' WHERE ' + parentField + ' = :parentId'); Database.delete(delThese); } // P. Sutherland Relocate this code for use everywhere public static list<selectOption> getPickValues(Sobject object_name, String field_name, String first_val) { list<selectOption> options = new list<selectOption>(); //new list for holding all of the picklist options if ( first_val != null) {//if there is a first value being provided options.add(new selectOption(first_val, first_val)); //add the first option } Schema.sObjectType sobject_type = object_name.getSObjectType(); //grab the sobject that was passed Schema.DescribeSObjectResult sobject_describe = sobject_type.getDescribe(); //describe the sobject map<String, Schema.SObjectField> field_map = sobject_describe.fields.getMap(); //get a map of fields for the passed sobject list<Schema.PicklistEntry> pick_list_values = field_map.get(field_name).getDescribe().getPickListValues(); //grab the list of picklist values for the passed field on the sobject for ( Schema.PicklistEntry a : pick_list_values ) { //for all values in the picklist list options.add(new selectOption(a.getLabel(), a.getValue())); //add the value and label to our final list } return options; //return the List } // Public Function to Strip Characters out of text public static String stripSpecialCharsHTML(String txt){ String retstr = ''; if ( txt != null ) { //first replace all <BR> tag system.debug('Text A: '+txt); txt = txt.replaceAll('(?i)<br>','\n').replaceAll('(?i)<br/>','\n').replaceAll('(?i)<br />','\n').replaceAll('\'','''); //regular expression to match all HTML/XML tags ( keeps injected JS and CSS out ) string HTML_TAG_PATTERN = '<.*?>'; pattern strPattern = pattern.compile(HTML_TAG_PATTERN); matcher strMatcher = strPattern.matcher(txt); txt = strMatcher.replaceAll(''); txt = txt.replaceAll('<','(').replaceAll('>',')').replaceAll('”','"').replaceAll('–','-'); //remove the White Space //string WHITESPACE_PATTERN = '\\s'; //pattern strPattern2 = pattern.compile(WHITESPACE_PATTERN); //matcher strMatcher2 = strPattern2.matcher(txt); //txt = strMatcher2.replaceAll(' '); system.debug('Text B: '+txt); txt = txt.replaceAll('\n','<br>').replaceAll('\r\n','<br>').replaceAll('\r','<br>').replaceAll('\t','<br>'); system.debug('Text C: '+txt); //txt = txt.replaceAll('\n',' '); } else return ''; retstr = txt; return retstr; } // Public Function to Strip Characters out of text public static String replaceIllegalCharsHTML(String txt){ String retstr = ''; if ( txt != null ) { //first replace all ' tags and the <br> txt = txt.replaceAll(''','\'').replaceAll('<br>','\n'); } else return ''; retstr = txt; return retstr; } // Phone Number Validation public static Boolean validateUSPhone(String phoneNumber) { if( phoneNumber != null ) { phoneNumber = phoneNumber.replaceAll('[^\\d]', ''); if ( phoneNumber.length() == 10 ) return true; //return true - if success return false; //else return false } else return false ; //if Phone field is empty return false } // returns a map of all the Object prefixes and Names public static map<String,String> getgdObjectTypeMap() { map<String, Schema.SObjectType> gd = Schema.getGlobalDescribe(); map<String,String> keyPrefixMap = new map<String,String>{}; for ( String sObj : gd.keySet()){ Schema.DescribeSObjectResult r = gd.get(sObj).getDescribe(); String tempName = r.getName(); String tempPrefix = r.getKeyPrefix(); keyPrefixMap.put(tempPrefix,tempName); } return keyPrefixMap; } // scrub an address to remove leading verbage public static String scrubAddress(String address) { String addstr = ''; list<String> ls = address.splitByCharacterTypeCamelCase(); for ( integer i=0; i < ls.size(); i++ ) { if ( ls[i].substring(1) > '0' && ls[i].substring(1) <= '9' ) { while ( i < ls.size() ) { addstr += ls[i]; i++; } } } return addstr; } // get Callout Keys Custom Setting record public static CalloutKeys__c getCalloutKeys(String key) { system.debug('@@@ Key: '+ key); CalloutKeys__c c = CalloutKeys__c.getInstance(key); system.debug('@@@ Call Out Keys Utils: '+c); return(c); } // determine if sandbox or production public static Boolean runningInASandbox() { return [select id,issandbox from organization].issandbox; } public static Boolean duplicateMgmtActive(String type) { String qstr = Utils.getAllFieldsSOQL('DuplicateRule','isactive = true and sobjecttype = :type'); list <duplicateRule> drlst = database.query(qstr); if (drlst.size() == 0) return false; else return true; } // end of duplicateMgmtActive }
Christan G 4
I suggest declaring all the collection variables you used throughout that method at the very beginning to ensure that all conditional code blocks afterwards have access to them. I am getting the sense that at some point, the values of a list are declared within a code block and thus, can only be referenced within that code block. As result, when you try to reference it somewhere, null values are being returned.