• Jonathan Osgood 3
  • NEWBIE
  • 120 Points
  • Member since 2014

  • Chatter
    Feed
  • 0
    Best Answers
  • 1
    Likes Received
  • 0
    Likes Given
  • 19
    Questions
  • 27
    Replies
Hi All,

Sadly I havent been writing apex for a long time and could use some help. I'm repurposing some code I have to compare two records and throw an error if there is a match on date. This is a before trigger that calls the below helper class . I'm getting a null pointer error on line 30 when I try to get the date from my Map which leads me to beleive I'm not populating my map correctly. Any help would be greatly appreciated. 
 
public class EventTriggerHelper {
    
    public static void CheckForDoubleBookedLocations(List<Event__c> locEvts){
        
        //collect ID's to reduce data calls
        List<ID> locationIds = new List<ID>();
        Map<ID,Event__c> requestedEventTime = new map<ID,Event__c>();
        
        //get all Locations related to the trigger
        
        for(Event__c newEvent : locEvts){
            if(newEvent.Event_Location__c != null){
                locationIds.add(newEvent.Event_Location__c);
            }
            //Populate Map
            List<Event__c> relatedEvents = [SELECT Event_Location__c, Start_Date_Time__c 
                                            FROM Event__c 
                                            WHERE Event_Location__c IN :locationIds];   
            
            for(Event__c relatedEvent : relatedEvents){
                requestedEventTime.put(relatedEvent.Id, relatedEvent);
                
                //get existing events to check against
                list<Event__c> existingEvents = [SELECT ID, Event_Location__c, Start_Date_Time__c 
                                                 FROM Event__c 
                                                 WHERE Event_Location__c IN :locationIDs];
                
                //check one list against the other
                for(Event__c evs : locEvts){
                    DateTime existStartTime = requestedEventTime.get(evs.Id).Start_Date_Time__c;
                    
                    for(Event__c event : existingEvents){
                       
                    ////Add location and end date range Logic  
                        if(event.Start_Date_Time__c == existStartTime){
                            event.addError('The Location is already booked at that time');
                        }          
                    }   
                }  
            } 
        }
    }
}
Hi All,

I'm a bit rusty on writing apex test code. I have a trigger that uses the .clone method to clone an opportunity and child records. Simply creating and inserting objects is not enough to test the trigger. I've tried Systems asserts to compare old opportuntiy to the new with no luck. Any advice on the best approach here?  

My trigger code (I realize I still need to pull the logic into a separate class and call that in my trigger) :  
 
trigger OpportunityTrigger on Opportunity (after insert, after update) {
    if(checkRecursive.runOnce()){
        
        
        
        
        // Interate selected opp records
        for (Opportunity opp : Trigger.new){
            if(opp.Renewable__c=='Yes' && opp.StageName=='Closed Won'){
                
                try{
                    id OpportunityId = opp.id;
                    List<Opportunity> oldOpps = [Select Accelera__c,renewable__c,RenewalCreated__c,jsImpacts__Added_from_Data_com__c,ASI_Opportunities__c,ASI_Strength__c,
                                                 ASI_Threats__c,ASI_Weakness__c,vs_Associated_eValuePrompter__c,Base_Number__c,Base_Term__c,BD_Opp__c,Big_Deal_Approved__c,vs_Business_Issue__c,vs_Business_Value__c,Capture_Opp__c,Close_Month_Try__c,Competition_Type__c,Contracting_Officer__c,Contrat_Type__c,Contract_Vehicle__c,CurrentGenerators__c,DB_Competitor__c,DealReg_Info__c,Deal_Registration_Date__c,Delivered_Services_Cost__c,Delivered_Services_Margin__c,Delivered_Services_Revenue__c,DeliveryInstallationStatus__c,Demos_Orals_BAFO__c,Differentiators__c,Discriminators__c,DRFP_RFP_Release_Date__c,Finance_Processed__c,Forecast_Category__c,Historical_Metric_1_Margin__c,Historical_Metric_2_Margin__c,Historical_Metric_3_Margin__c,Historical_Rev__c,Important_Qs_Updates_for_Opps__c,Incumbent__c,Industry_Date__c,Inside_Sales_Rep__c,Internal_Contract_Id__c,Is_Deal_Registered__c,vs_Last_Modified_eValuePrompter__c,Lowest_Line_Item_Margin__c,MainCompetitors__c,vs_Manager_Accepted__c,vs_Manager_Notes__c,
                                                 vs_Manager_Review_Request__c,Metric_1__c,Metric_2__c,Metric_3__c,Metric_4__c,MicrosoftRevenue__c,MiscRevenue__c,Mitigation__c,MSA__c,NAICS__c,NDA__c,NEW_Total_Quote_Margin_Value__c,Non_Commissionable__c,Notes_for_Processing_Order__c,Opportunity_Contains__c,Opportunity_ID__c,Option_Renewal_Period__c,Options_Number__c,Owner__c,Owner_Split_Percent__c,Partner_Commission__c,Period_of_Performance__c,TO_PoP_End__c,TO_PoP_Start__c,vs_Personal_Value__c,PM_Approach__c,PM_Assigned__c,PMO_Managed__c,Potential_Competitors__c,Pricing_Strategy__c,Prime__c,Prime_Contractor__c,vs_Problems__c,Process_Status_Valid_Since__c,ProductRevenue__c,Program_Summary__c,Project_Close_Date__c,Project_Number__c,Proposal_Lead__c,Latest_News__c,PWin__c,QB_SAP_SO__c,QuoteRenewalMargin__c,Reason_For_Stage__c,Reason_For_Stage_Notes__c,Renewable_Term__c,RenewalRevenue__c,RFI_Source__c,RFP_Opp_ID__c,RFP_Date__c,RFP_Status__c,Sales_Partner__c,SAP_Opportunity_ID__c,Service_Business_Opp_Type__c,Service_Contract_Type__c,Services_Invoiced_Through_Date__c,ServicesRevenue__c,SNACKsLead__c,vs_Solutions__c,
                                                 Solution_Type__c,SOW_Needed__c,Split_Rep__c,Split_Rep_Percent__c,Stage_Since_Date__c,Sub__c,Subcontractor__c,TCV__c,Technology_Approach__c,Total_Cloud_Margin__c,Total_Cloud_Revenue__c,Total_Enterprise_Services_Margin__c,Total_Enterprise_Services_Revenue__c,Total_Historical_Margin__c,Total_Managed_Services_Margin__c,Total_Managed_Services_Revenue__c,Total_Opportunity_Margin__c,Total_Opportunity_Revenue__c,Total_Product_Margin__c,Total_Product_Quantity__c,Total_Product_Revenue__c,TotalQuoteMargin__c,Total_Rebate_Margin__c,Total_Rebate_Revenue__c,TotalRevenue__c,
                                                 Total_Services_Margin__c,Total_Services_Revenue__c,Total_Workplace_Margin__c,Total_Workplace_Revenue__c,TrackingNumber__c,Value_Proposition__c,vs_Influencer_Role__c,vs_Vision_Match__c,Weighted_Opp_Margin__c,Weighted_Total_Margin__c,Workplace_Margin__c,AccountID,Amount,CloseDate,ContractID,CreatedByID,Description,ExpectedRevenue,ForecastCategoryName,LeadSource,NextStep,Name,OwnerID,RecordTypeID,Pricebook2ID,CampaignID,IsPrivate,Probability,TotalOpportunityQuantity,StageName,SyncedQuoteID,Type,
                                                 (Select OpportunityID,ID,Accelera_Sales_Rep__c,AccountID,AdditionalAddress,AdditionalName,AlternativeProjectManagerRate__c,ASI_Rep__c,ASI_Rep_E_Mail__c,BillingAddress,BillingName,ContactID,ContractID,ContractVehicle__c,CreatedByID,CustomProjectManagerHours__c,DefaultProjectManagerRate__c,Description,Discount,Email,EngineeringServicesDescription__c,ExpirationDate,Fax,For_End_User_del__c,GrandTotal,Internal_Comments__c,IsSyncing,Labor_Category__c,LaborDiscountPercent__c,LastModifiedByID,Name,Payment_Term__c,Payment_Terms__c,Phone,Project_Management_Hours__c,Project_Management_Rate__c,ProjectManagerActualCost__c,ProjectManagerPercentHours__c,Quote_Shipping_Handling__c,Quote_Tax__c,QuoteToAddress,QuoteToName,RecordTypeID,ShippingAddress,ShippingHandling,ShippingName,Status,Tax,TotalLaborActualCost__c,TotalLaborSalesPrice__c,TotalMicrosoftActualCost__c,TotalMicrosoftSalesPrice__c,TotalMiscActualCost__c,TotalMiscSalesPrice__c,TotalProductActualCost__c,TotalProductSalesPrice__c,TotalRenewalActualCost__c,TotalRenewalSalesPrice__c,Wrokplace__c from Quotes),
                                                 (Select PricebookEntryId,CreatedByID,ServiceDate,Discount,LastModifiedByID,Description,ListPrice,OpportunityID,Product2ID,ProductCode,Quantity,UnitPrice,Subtotal,Actual_Cost__c,Item_Margin__c,Quosal_Business_Unit__c,Quosal_Contract_Vehicle__c
                                                  from OpportunityLineItems) from Opportunity where ID = :OpportunityId AND RenewalCreated__c =False];
                    
                    if(oldOpps.size()>0){
                        List<OpportunityLineItem> olis = new List<OpportunityLineItem>();
                        List<Quote> qteList = new List<Quote>();
                        Opportunity oldOpp = oldOpps[0];
                        Opportunity newOpp = oldOpp.clone(false,true,false,false);
                        newOpp.StageName = 'Qualification';
                        newOpp.Name = oldOpp.Name + ' - RENEWAL';
                        integer months = integer.valueOf(oldOpp.Renewable_Term__c);
                        date newCloseDate = oldOpp.CloseDate;
                        newCloseDate = NewCloseDate.addMonths(months);
                        newOpp.CloseDate = newCloseDate;
                        newOpp.Reason_For_Stage__c = null;
                        newOpp.Probability = 5;
                        NewOpp.RenewalCreated__c = True;
                        OldOpp.RenewalCreated__c = True;
                        insert newOpp;
                        update oldOpp;
                        for(OpportunityLineItem oli : oldOpp.OpportunityLineItems){
                            
                            OpportunityLineItem oliNew = oli.clone(false,true,false,false);
                            oliNew.OpportunityId = newOpp.id;
                            
                            olis.add(oliNew);
                        }
                        for(Quote qte : oldOpp.quotes){
                            
                            quote qteNew = qte.clone(false,true,false,false);
                            qteNew.OpportunityId = newOpp.id;
                            
                            qteList.add(qteNew);
                        }
                        
                        if(olis.size() > 0)
                            insert olis;
                        if(qteList.size() > 0)
                            insert qteList;
                    }
                } catch (Exception e){            
                            system.debug(e.getMessage() + e.getStackTraceString()); 
                            
                        }
                    
                }
                
            }
        }
    }

My Test Code: 
@isTest
public class OpportunityCloneTriggerTest {
    
   @isTest
    public static void TestMethod1(){
        
        //Create Account
        Account newAccount = new Account(
            Name='TestAccount',
            Phone='3035551212');
        insert newAccount;
        
        //Create Product
        Product2 newProduct = new Product2(
            Name='NewProd',
            ProductCode = 'VSC24B100',
            isActive = true);
        insert newProduct;
        
        
        //Create your pricebook entry
        Id pricebookId = Test.getStandardPricebookId();
        PricebookEntry newPBE = new PricebookEntry(
            Pricebook2Id = pricebookId,
            Product2Id = newProduct.Id,
            UnitPrice = 500.00,
            IsActive = true
        );
        insert newPBE;
        
        //Create Opportunity
        Opportunity newOpportunity = new Opportunity(
            Name='NewOpp', 
            AccountId = newAccount.Id,
            StageName='Payment Processing',
            CloseDate=date.newInstance(2016, 1, 1));
        insert newOpportunity;
        
        
        //Validate single insert
        for(Opportunity o:[SELECT id FROM Opportunity 
                           WHERE id = :newOpportunity.id]) {
             System.assertEquals(o.id, newOpportunity.id);
            }
        
        
        
        //Create Opportunity Product
        OpportunityLineItem newOppLineItem = new OpportunityLineItem(
            OpportunityId = newOpportunity.Id, 
            PricebookEntryId = newPBE.Id,Quantity = 1, 
            TotalPrice = newPBE.UnitPrice
            );
       
            insert newOppLineItem;  
        
        
        //Create Opportunity Quote
        Quote newQuote = new Quote(
            name = 'testquote',
            OpportunityId = newOpportunity.Id, 
            ExpirationDate = date.newInstance(2016, 1, 1)
            );
        insert newQuote;
        
        //Update the stage
        newOpportunity.StageName='Closed Won';
        update newOpportunity;
    }
}

Lines not covered:

User-added image

User-added image
 
Hi All,

I could use some guidance on how to properly parse my JSON into a custom object. I am able to get all of my deserialized results in the debug log, but I am not able to access individual variables to create a new object and populate the fields. I can get top level object results, but not individual member data like myMap.get('specificVariable');

Full code:
public class NPIcalloutHelper {
    
    public static String getDocById(Integer NPIid){
        
        Http http = new Http();
        HttpRequest request = new HttpRequest();
        request.setEndpoint('https://npiregistry.cms.hhs.gov/api/?number='+NPIid);
        request.setMethod('GET');
        HttpResponse response = http.send(request);
        String strResp = '';
        
           system.debug('******response '+response.getStatusCode());
           system.debug('******response '+response.getBody());
        
        // If the request is successful, parse the JSON response.
        if (response.getStatusCode() == 200) 
        {
            // Deserializes the JSON string into collections of primitive data types.
           Map<String, Object> npiResults = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
            // Cast the values in the 'results' key as a list
            List<Object> allresults =(List<Object>)npiResults.get('results');
            System.debug('allresults' + allresults );
                   }
        return strResp ;
   }

}

 
Hi All,

Formula syntax time. Here's the attempt:

AND(NOT(ISPICKVAL(StageName, 'Closed Won'))),
(NOT(ISPICKVAL(StageName, 'Closed Lost'))),
DATEVALUE([Opportunity].CloseDate) -Today() >30 )

The error: The formula expression is invalid: Syntax error. Extra ','

Also, I feel like this criteria should be easier to setup in process builder. The oppprtunity stage criteria is easy enough, but not the "30 days past created date part". Am I missing something there?

Thanks!
Hi All,

Getting Null pointer exception on If Statement Only if field is not populated, after update. Added null check to avoid but it didnt work. What is wroing with my Null check?
 
if(l.Website_Inquiry_Type__c.containsIgnoreCase('Buy Generator') 
           ||l.Website_Inquiry_Type__c.containsIgnoreCase('Sell Generator')
            &&  l.Website_Inquiry_Type__c != null  ) 

               { rest of my code that works fine}

 
Hi All,

I'm getting an invalid id error when I call userAccounts.get(p.Ownerid).AccountId; I think I may be populating my userAccounts map incorrectly?
 
list<ID> pubIds = new list<ID>();
        
        for(Publication__c p: pubList){ 
            pubIds.add(p.id);                      
        }
        
        list<ID> UserIds = new list<ID>();
        
        for(Publication__c p: pubList){ 
            UserIds.add(p.ownerid);                      
        }
        map<id,user> userAccounts = new map <id, user>([SELECT Id, Name, AccountId
                                                                                           FROM User 
                                                                                           WHERE Id IN :UserIds 
                                                                                           AND IsActive = true]);
        
        
        list<Publication__c> pubsToUpdate = [SELECT ID, ownerId
                               					     FROM Publication__c 
                               					      WHERE ID in: pubIds];
        
        for(Publication__c p: pubsToUpdate){
            
            p.Next_Object__c      = stepOneMap.get(p.Id).id;
            
 	          	if(userAccounts.get(p.OwnerId).AccountId !=''){
              
             	  	 p.Account__c = userAccounts.get(p.Ownerid).AccountId;
           			
            }
                             
                              }
        Update pubsToUpdate;

 
Hi,

I am unable to access certain owner fields on the user object. I'm trying to reach the standard AccountID field and a custom field with no luck. I can reach Owner.name without a problem though. 

This works: 
SELECT ID, owner.Name FROM Publication__c

 and this works:
SELECT ID, owner.email FROM Publication__c

BUT this will NOT work:

SELECT ID, owner.AccountID FROM Publication__c

Is this a known limitation?
Hi All,

Can't seem to get my WHERE clause correct. Getting Invalid bind expression type of Object for column of type Id error. Here is the full class:
 
public class SubmitPublicationController {
    @AuraEnabled
    public static sObject getObjectById(ID anId) {
        
        system.debug('Entering controller');
        // Get the sObject token from the first ID
        Schema.SObjectType token = anId.getSObjectType();
        
        // Using the token, do a describe 
        // and construct a query dynamically. 
        Schema.DescribeSObjectResult dr = token.getDescribe();
        String queryString = 'SELECT Id, Name, Publication__c, Next_Object__r.Id, Previous_Object__r.Id FROM ' + dr.getName() + 
            ' WHERE Id = :anId Limit 1 ';
        
        system.debug('describe object result' + dr.getName());
        
        sObject objDBResult = Database.query(queryString);
       
      	List <Publication__c> pubsList = [SELECT ID, Publication_Submitted__c
                          	   FROM Publication__c
                               WHERE ID = :objDBResult.get('Publication__c')
                                         ];
        
        pubsList[0].Publication_Submitted__c = true;
        
        system.debug('pub ID='+pubsList);
    
        upsert pubsList;
        
        System.debug('ID is: ' + anId);  
        System.debug('objDBResult: ' + objDBResult); 
        
        return objDBResult;
       
    }
    
    

}

 
Hello,

Test coverage at 80% and I cant figure out why. Red highlight on Line 11 "return result;" GET request is working fine in workbench.

Account manager class:
 
@RestResource(urlMapping='/Accounts/*/contacts')
global with sharing class AccountManager {

    @HttpGet
    global static Account getAccount() {
        RestRequest request = RestContext.request;
        // grab the accountId from the end of the URL
        String accountId = request.requestURI.substringBetween('Accounts/', '/contacts');
        Account result = [SELECT ID,Name,(SELECT ID,Name FROM Contacts) FROM Account WHERE Id = :accountId ];
        system.debug(result);
        return result;
        
    }
}
Test Class:
 
@IsTest
private class AccountManagerTest {

    @isTest static void testGetAccount() {
        Id recordId = createTestRecord();
        // Set up a test request
        RestRequest request = new RestRequest();
        request.requestUri =
            'https://na1.salesforce.com/services/apexrest/Accounts/'+ recordId+'/Contacts';
        request.httpMethod = 'GET';
        RestContext.request = request;
        // Call the method to test
        Account thisAccount = AccountManager.getAccount();
        // Verify results
        System.assert(thisAccount != null);
        System.assertEquals('Test record', thisAccount.Name);
    }

   

    // Helper method
    static Id createTestRecord() {
        // Create test record
        Account accountTest = new Account(
        Name='Test record');
        insert accountTest;
       
        Contact con1 = new Contact(
        AccountId = accountTest.Id,
        firstName = 'test',
        lastName  =  'tester');
        insert con1;
        return accountTest.Id;
    }          

}


 
Hi Everyone,

Trying to complete the Rest Callouts challenge and getting this error on the last line: return strResponse;. Here is my code:
public class AnimalLocator {

    public static HttpResponse getAnimalNameById(Integer ID){
        Http http           = new Http();
        HttpRequest request = new HttpRequest();
        request.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals/'+ID);
        request.setMethod('GET');
        HttpResponse response = http.send(request);
        
        String strResponse = '';
        
        if(response.getStatusCode()==200){
        
            Map<String,Object> results = (Map<String,Object>) JSON.deserializeUntyped(response.getBody());
            
            Map<String,Object> animals = (Map<String,Object>) results.get('animals');
           
            system.debug('These are the animals:');
            
            strResponse = string.valueOf(animals.get('name'));
            
        }
        return strResponse;
    }
}

Thank you!
Want my soql query to find records with specific record types. OR stement returning error: expecting right square bracket, found 'OR'

Do I need to create additional soql queries to first obtain record types, then reference in existig soql?

Thanks!

Existing soql
List<AggregateResult> results = [SELECT Account__c, 
                                         SUM(X2_1_a_Total_of_jobs_Year_0__c) mysum0,
                                         FROM Form__c 
                                         WHERE Account__c IN:accountIds
                                         AND (RecordType.DeveloperName ='Baseline Report')
                                         OR  (RecordType.DeveloperName ='Annual Report')
                                         GROUP BY Account__c]  ;

 
Is this possible (with the correct syntax)?
 
if(AggregateResult results = [SELECT SUM(X2_1_a_Total_of_jobs_Year_2__c) FROM Form__c] > results.size(0)){
    
    System.debug('sum of year 2 greater than 0');
}else{
    system.debug('sum of year 2 NOT greater than 0');
}

I know you can use Count() in an expression like this (according to this jeff douglass post (http://blog.jeffdouglas.com/2010/04/12/using-aggregateresult-in-salesforce-com-soql/)) because it returns the number of rows, not an object. But can I cast into an integer or something else?
Hi all,

I have a trigger that calculates the difference of values from year to year on account child records (form__c). Everything is working except for scenarios where a given year = 0. I've added an IF statement to handle this scenario, but what I really need is the SUM of ALL X2_1_a_Total_of_jobs_Year_2__c values under an account. Example, IF(f.X2_1_a_Total_of_jobs_Year_2__c:SUM > 0). 

Do I need to use aggregateResult here? 
 
if(f.X2_1_a_Total_of_jobs_Year_2__c > 0){
               calculated += f.X2_1_a_Total_of_jobs_Year_2__c - f.X2_1_a_Total_of_jobs_Year_1__c;
            }else {
               calculated = f.X2_1_a_Total_of_jobs_Year_1__c;


The full trigger:
 
trigger JobsIncomeCalc on Form__c (after insert, after update, after delete) {
    
    //Forms List
    List <Form__c> FormsList = New List <Form__c>();
    
    //Distinguish whether the list should act on insert, update or delete
    
    if(trigger.isInsert || trigger.isUpdate){
        FormsList = Trigger.New;
    }
    if(trigger.isDelete){
        FormsList = Trigger.Old;
    }
    
    //Account Ids Set 
    Set <id> accountIds = New Set <id>();
    
    //Add form account ids to set
    for(Form__c form: FormsList){
        
        accountIds.add(form.Account__c);
        
        System.debug('account id'+form.Account__c);
        
        accountIds.remove(null);

    }
    
    //Account Map
    
    If(!accountIds.IsEmpty()){
        Map<Id, Decimal> accountMap = New Map <Id, Decimal>();
        
        for(form__c f: [
            select Account__c,
            X2_1_a_Total_of_jobs_Year_1__c,
            X2_1_a_Total_of_jobs_Year_2__c,
            X2_1_a_Total_of_jobs_Year_3__c,
            X2_1_a_Total_of_jobs_Year_4__c,
            X2_1_a_Total_of_jobs_Year_5__c,
            X2_1_a_Total_of_jobs_Year_6__c,
            X2_1_a_Total_of_jobs_Year_7__c,
            X2_1_a_Total_of_jobs_Year_8__c,
            X2_1_a_Total_of_jobs_Year_9__c,
            X2_1_a_Total_of_jobs_Year_10__c
            from Form__c
            where Account__c in :accountIds
        ]){
            if(!accountMap.containsKey(f.Account__c)){
                accountMap.put(f.Account__c, 0);
            }

              
            Double calculated = accountMap.get(f.Account__c);
            
            if(f.X2_1_a_Total_of_jobs_Year_2__c > 0){
               calculated += f.X2_1_a_Total_of_jobs_Year_2__c - f.X2_1_a_Total_of_jobs_Year_1__c;
            }else {
               calculated = f.X2_1_a_Total_of_jobs_Year_1__c;
            }
            
            accountMap.put(f.account__c, calculated);    
        }
        
        if(!accountMap.isEmpty()){
            List<Account> acctsToUpdate = new List<Account>();
            
            for(Id id : accountMap.keySet()){
                acctsToUpdate.add( new Account (
                Id = id,
                X2_1_a_Total_of_Jobs_Hist_Cumulative__c = accountMap.get(id)
                ));
                
            }
            
           update acctsToUpdate;
 
        }  
    }
}

Thank you!
 
Hi All,

I'm working on a trigger and could use some help. I've hit a report formula limitation and am trying to recreate the same logic in a trigger. The basic requirement is to collect a field value from child objects, run a simple calculation, then assign that value to a field on the parent account. From the debug statemtents, it seems that things seem to fall apart at line 55. Any feedback would be appreciated! 

Thank you!
 
trigger JobsIncomeCalc on Form__c (after insert, after update, after delete) {
    
    //Forms List
    List <Form__c> FormsList = [SELECT id,
                                Account__c,
                                Account__r.id,
                                X2_1_a_Total_of_jobs_Year_1__c, 
                                X2_1_a_Total_of_jobs_Year_2__c
                                FROM form__c];
    
    
    //Distinguish whether the list should act on insert, update or delete
    
    if(trigger.isInsert || trigger.isUpdate){
        FormsList = Trigger.New;
    }
    if(trigger.isDelete){
        FormsList = Trigger.Old;
    }
    
    //Account Ids Set 
    Set <id> accountIds = New Set <id>();
    
    //Add form account ids to set
    for(Form__c F: FormsList){
        
        accountIds.add(f.Account__c);
        System.debug('account id'+f.Account__c);
    }
    
    //Map to pair accounts and forms
    Map<id,Double> formAccountMap= New Map<id,Double>();
    
    for(form__c f: [SELECT id,
                    Account__r.id,
                    Account__r.X2_1_a_Total_of_Jobs_Hist_Cumulative__c
                    FROM Form__c 
                    WHERE Account__r.id IN: accountIds]){
                        
                        Double AccTotalJobsHist = f.Account__r.X2_1_a_Total_of_Jobs_Hist_Cumulative__c;                   
                        formAccountMap.put(f.Account__r.ID, AccTotalJobsHist);                
                        
                        system.debug('AccTotalJobsHist='+ AccTotalJobsHist);
                        system.debug('Account total jobs from form map='+ formAccountMap.get(f.Account__r.ID));
                        
                        
                    }
    
    //Accounts to update list
    List<Account> AcctsToUpdate = new List<Account>();
    
    system.debug('AcctsToUpdate='+AcctsToUpdate);
    //Apply calculation to all forms in FormList
    
    for(Account a: AcctsToUpdate){
        
        Double AccTotalJobsHist = formAccountMap.get(a.ID);
        system.debug('AccTotalJobsHist='+AccTotalJobsHist);
        system.debug('AccTotalJobsHist='+formAccountMap.get(a.ID));
        
        Double TotalJobsY1 = a.form__r.X2_1_a_Total_of_jobs_Year_1__c;
        Double TotalJobsY2 = a.form__r.X2_1_a_Total_of_jobs_Year_2__c;
        system.debug('TotalJobsY1='+TotalJobsY1);
        system.debug('TotalJobsY2='+TotalJobsY2);
        
        
        Double CalculatedTotalJobs = (TotalJobsY2 - TotalJobsY1);
        system.debug('CalculatedTotalJobs='+CalculatedTotalJobs);
        
        //Set calculated value in account field    
        
        AccTotalJobsHist = CalculatedTotalJobs; 
        
        AcctsToUpdate.add(a);
    }
    
    Update AcctsToUpdate;
    
}

 
Hi All,

I'm trying to run a simple (ish) calculation. For all Account child records (form__c), I have 2 fields: Year and Total Jobs. My calculation is as follows: Sum of differences between each year:
i.e.
(Total Jobs Year 2 - Total Jobs Year 1) + (Total Jobs Year 3 - Total Jobs Year 2) + (Total Jobs Year 4 - Total Jobs Year 3)

So, I need to iterate through each Form__c record, parse out year 1 = total jobs, etc. Return the Sum of Differences (X2_1_a_Total_of_Jobs_Hist_Cumulative__c = CalculatedTotalJobs) in the parent account field. Here's what I have so far. I'm thinking I'm going to have to use Maps instead? Any feedback appreciated!
 
trigger TotalNumberOfJobsTrigger on Account (after insert, after update, after delete) {
    
    //Accounts list
    List<Account> AcctsList = new List <Account>();
   
    
    //Distinguish whether the list should act on inseret, update or delete
    
    if(trigger.isInsert || trigger.isUpdate){
        AcctsList = Trigger.New;
    }
    if(trigger.isDelete){
        acctsList = Trigger.old;
    }
    
    //iterate through and find related form records    
    for(List<Form__c> formsList: [SELECT id, Name, X2_1_a_Total_of_Jobs_Hist_Cumulative__c,(SELECT Account__c, X1a_EcOps_Total_number_of_jobs__c, Name FROM Forms__r) 
                                  FROM Account WHERE id IN :Trigger.new]){
                                      
                                      if(form__c.Report_Year__c='Year 1'){
                                          Integer TotalJobsY1 = form__c.X1a_EcOps_Total_number_of_jobs__c;
                                      }
                                      
                                      if(form__c.Report_Year__c='Year 2'){
                                          Integer TotalJobsY2 = form__c.X1a_EcOps_Total_number_of_jobs__c;
                                      }
                                      if(form__c.Report_Year__c='Year 3'){
                                          Integer TotalJobsY3 = form__c.X1a_EcOps_Total_number_of_jobs__c;
                                      }
                                      if(form__c.Report_Year__c='Year 4'){
                                          Integer TotalJobsY4 = form__c.X1a_EcOps_Total_number_of_jobs__c;
                                      }
                                      
                                      for(Account acc: [SELECT id, Name, X2_1_a_Total_of_Jobs_Hist_Cumulative__c,(SELECT Account__c, Name FROM Forms__r) 
                                                        FROM Account WHERE id IN :formsList]){
                                                            
                                                            //Formula to Calculate difference in year/records.   
                                                            
                                                            Integer CalculatedTotalJobs = (TotalJobsY2 - TotalJobsY1) +
                                                                (TotalJobsY3 - TotalJobsY2) +
                                                                (TotalJobsY4 - TotalJobsY3);
                                                            
                                                            //Set  calculated value in account field    
                                                            acc.X2_1_a_Total_of_Jobs_Hist_Cumulative__c = CalculatedTotalJobs; 
                                                            AcctsList.add(acc);
                                                        }
                                      
                                  }
    
    Update AcctsList;
    
    
}
Hi All,

I have a simple trigger to roll up the count of child records (product__c) on the parent record (Person__c). Record count landed on a field on the person__c record called Total_Number_of_Products__c. Everything was working great, but I'm trying update the trigger to only roll up those records of a specific record type.

Here is my original working trigger code:
trigger PersonRollUpProducts on Product__c (after delete, after insert, after update) {
 
  //Limit the size of list by using Sets which do not contain duplicate elements
  
  set<id> PersonIds = new set<id>();
  
  List<Product__c> lstProducts = new List<Product__c>();
  
  //When adding new products or updating existing products
  if(trigger.isInsert || trigger.isUpdate){
    lstProducts = trigger.new;
    /*
    for(Product__c pr : trigger.new){
      PersonIds.add(pr.Person__c);
    }*/
  }
 
  //When deleting payments
  if(trigger.isDelete){
    lstProducts = trigger.old;
    /*
    for(Product__c pr : trigger.old){
      PersonIds.add(pr.Person__c);
    }*/
  }
  
  for(Product__c pr : lstProducts){
      PersonIds.add(pr.Person__c);
    }
 
  //Map will contain one Person Id to one sum value
  map<id, Double> PersonMap = new map<id, Double> ();
 
  //Produce a sum of Products__c and add them to the map
  //use group by to have a single Person__c Id with a single sum value
  for(AggregateResult q : [select Person__c,count(id)
    from Product__c where Person__c IN :PersonIds group by Person__c]){
      PersonMap.put((Id)q.get('Person__c'),(Double)q.get('expr0'));
  }
 
  List<Person__c> PersonsToUpdate = new List<Person__c>();
 
  //Run the for loop on person using the non-duplicate set of person Ids
  //Get the sum value from the map and create a list of persons to update
  for(Person__c pe : [Select Id, Total_Number_of_Products__c from Person__c where Id IN :PersonIds]){
    
    Double ProductSum = PersonMap.get(pe.Id);
    pe.Total_Number_of_Products__c = ProductSum;
    PersonsToUpdate.add(pe);
  }
 
  update PersonsToUpdate;
}

I added the following (bold, underlined) code to my SOQL query with no luck:

[select Person__c,count(id) from Product__c where RecordTypeId ='012d0000000SnGM' and Person__c IN :PersonIds group by Person__c]

What am I missing here?

Thanks!
 
Hi All,

I have a custom form_c object which creates a new contact from the form_c.Name fields. Thats working fine, but I can't seem to link the two records via lookup. I'm trying to populate a lookup field to contact on my form object. form.Student__c;

Here is my controller so far:
public class MeritusSignupController {


 public Form__c form {get;set;}
 public String formId {get;set;}
 public Account a {get;set;}
 public Contact c {get;set;}
 public String is_new {get;set;}


 public MeritusSignupController()
    {
    
     form= new Form__c();
     form.Applicant_First_Name__c = UserInfo.getFirstName();
     form.Applicant_Last_Name__c = UserInfo.getLastName();
     form.Email__c = UserInfo.getUserEmail();
     a= new account();
     is_new = ApexPages.CurrentPage().getParameters().get('newform');
     formId = ApexPages.CurrentPage().getParameters().get('formid');
     String userId= UserInfo.getUserId();
     c= new contact();
      
     List<Form__c> formList = new List<form__c>();
        if (is_new == 'true')  
        {
            form = new form__c();
            form.Applicant_First_Name__c = UserInfo.getFirstName();
            form.Applicant_Last_Name__c = UserInfo.getLastName();
            form.Email__c = UserInfo.getUserEmail();
        }
    
        else if (formId != null)
        {
            formList = [Select id, Student__r.Name, Student__c, Read_understand_requirements__c, Applicant_First_Name__c,Applicant_Last_Name__c, 
            Address__c, Applicant_City__c,Applicant_State__c,Applicant_Zip_Code__c, Primary_Phone__c, Secondary_Phone__c, Secondary_Contact_First_Name__c, 
            Secondary_Contact_Last_Name__c,Relationship_to_Student__c,Secondary_Contact_Phone_Number__c,Gender__c,Country_of_Origin__c,Race_Ethnicity__c,Birthdate__c,
            Languages_Spoken__c,High_School_Attended__c,Planning_on_Completing_FAFSA_or_DreamAct__c,Did_either_or_both_of_your_parents_gradu__c, 
            Email__c from form__c where id =: formid];
        }
        
        else 
        {
            formList = [Select id, Student__r.Name, Student__c, Read_understand_requirements__c, Applicant_First_Name__c,Applicant_Last_Name__c, 
            Address__c, Applicant_City__c,Applicant_State__c,Applicant_Zip_Code__c, Primary_Phone__c, Secondary_Phone__c, Secondary_Contact_First_Name__c, 
            Secondary_Contact_Last_Name__c,Relationship_to_Student__c,Secondary_Contact_Phone_Number__c,Gender__c,Country_of_Origin__c,Race_Ethnicity__c,Birthdate__c,
            Languages_Spoken__c,High_School_Attended__c,Planning_on_Completing_FAFSA_or_DreamAct__c,Did_either_or_both_of_your_parents_gradu__c, 
            Email__c from form__c where CreatedById =: userId order by lastmodifieddate desc limit 1];
        
        }
        
         if (formlist.size() >0)
        {                
                form = formlist[0];
                if (form.applicant_first_name__c == null || form.applicant_first_name__c == '')
                    form.applicant_first_name__c = UserInfo.getFirstName();
                if (form.applicant_last_name__c == null || form.applicant_last_name__c == '')
                    form.applicant_last_name__c = UserInfo.getLastName();
                if (form.email__c == null || form.email__c == '')
                    form.email__c = UserInfo.getUserEmail();
                if (form.Student__c != null)
                {
                    String conId = form.Student__c;
                    List<Contact> conList = [select id from contact where id =: conId limit 1];   
                    if (conList.size() >0)
                        c= conList[0]; 
                 }
         }                  
             
        
    }
    
 void savefunc()
     {
     Boolean flag = false;
      if (form.Applicant_First_Name__c == null)  {
           form.Applicant_First_Name__c.addError('Required field.');
           flag = true;
          } 
        
                             
                                        
     if (flag == false)     
      {            
    
        c.FirstName = form.Applicant_First_Name__c;
        c.LastName= form.Applicant_Last_Name__c;
        c.id = form.Student__c;
        
        
        upsert form;        
        upsert c;
       } 
       
     } 
     public PageReference saveForm() {
        
        try
        {
        savefunc();
        }
        catch (Exception e)
        {
            ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR, e.getmessage()));
            ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR, String.valueOf(e.getLineNumber())));
            
        }
        return null;
}

     
}

 
public class MeritusSignupController {


 public Form__c form {get;set;}
 public String formId {get;set;}
 public Account a {get;set;}
 public Contact c {get;set;}
 public String is_new {get;set;}


 public MeritusSignupController()
    {
    
     form= new Form__c();
     form.Applicant_First_Name__c = UserInfo.getFirstName();
     form.Applicant_Last_Name__c = UserInfo.getLastName();
     form.Email__c = UserInfo.getUserEmail();
     a= new account();
     is_new = ApexPages.CurrentPage().getParameters().get('newform');
     formId = ApexPages.CurrentPage().getParameters().get('formid');
     String userId= UserInfo.getUserId();
     c= new contact();
      
     List<Form__c> formList = new List<form__c>();
        if (is_new == 'true')  
        {
            form = new form__c();
            form.Applicant_First_Name__c = UserInfo.getFirstName();
            form.Applicant_Last_Name__c = UserInfo.getLastName();
            form.Email__c = UserInfo.getUserEmail();
        }
    
        else if (formId != null)
        {
            formList = [Select id, Student__r.Name, Student__c, Applicant_First_Name__c,Applicant_Last_Name__c,Email__c from form__c where id =: formid];
        }
        
    }
    
 void savefunc()
     {
     Boolean flag = false;
      if (form.Applicant_First_Name__c == null)  {
           form.Applicant_First_Name__c.addError('Required field.');
           flag = true;
          } 
        }
                             
                                        
     if (flag == false)     
      {            
    
        c.FirstName = form.Applicant_First_Name__c;
        c.LastName= form.Applicant_Last_Name__c;
        
        upsert form;        
        upsert c;
       }  
}
The property and method are public so not sure why I'm getting this error:

User-added image

My Custom Controller:
 
public class MeritusSignupController {


 public Form__c form {get;set;}
 public String formId {get;set;}
 public Account a {get;set;}
 public Contact c {get;set;}
 public String is_new {get;set;}


 public MeritusSignupController()
    {
    
     form= new Form__c();
     form.Applicant_First_Name__c = UserInfo.getFirstName();
     form.Applicant_Last_Name__c = UserInfo.getLastName();
     form.Email__c = UserInfo.getUserEmail();
     a= new account();
     is_new = ApexPages.CurrentPage().getParameters().get('newform');
     formId = ApexPages.CurrentPage().getParameters().get('formid');
     String userId= UserInfo.getUserId();
     c= new contact();
      
     List<Form__c> formList = new List<form__c>();
        if (is_new == 'true')  
        {
            form = new form__c();
            form.Applicant_First_Name__c = UserInfo.getFirstName();
            form.Applicant_Last_Name__c = UserInfo.getLastName();
            form.Email__c = UserInfo.getUserEmail();
        }
    
        else if (formId != null)
        {
            formList = [Select id, Student__r.Name, Student__c, Applicant_First_Name__c,Applicant_Last_Name__c,Email__c from form__c where id =: formid];
        }
    
     upsert form; 
     upsert c;
    }

My VisualForce :
 
<apex:page Controller="SignupController" showHeader="false" sidebar="false" >
<apex:stylesheet value="{!URLFOR($Resource.AppCss)}" />

<body>

<apex:form>

    <div>
      <apex:inputtext value="{!Form__c.Applicant_First_Name__c}" />
    </div>  

    <div>
      <apex:inputtext value="{!Form__c.Applicant_Last_Name__c}" />
    </div>  
    
<apex:commandButton value="Save" action="{!save}" />
 

</apex:form>
</body> 
  
</apex:page>


 
Hello,

Test coverage at 80% and I cant figure out why. Red highlight on Line 11 "return result;" GET request is working fine in workbench.

Account manager class:
 
@RestResource(urlMapping='/Accounts/*/contacts')
global with sharing class AccountManager {

    @HttpGet
    global static Account getAccount() {
        RestRequest request = RestContext.request;
        // grab the accountId from the end of the URL
        String accountId = request.requestURI.substringBetween('Accounts/', '/contacts');
        Account result = [SELECT ID,Name,(SELECT ID,Name FROM Contacts) FROM Account WHERE Id = :accountId ];
        system.debug(result);
        return result;
        
    }
}
Test Class:
 
@IsTest
private class AccountManagerTest {

    @isTest static void testGetAccount() {
        Id recordId = createTestRecord();
        // Set up a test request
        RestRequest request = new RestRequest();
        request.requestUri =
            'https://na1.salesforce.com/services/apexrest/Accounts/'+ recordId+'/Contacts';
        request.httpMethod = 'GET';
        RestContext.request = request;
        // Call the method to test
        Account thisAccount = AccountManager.getAccount();
        // Verify results
        System.assert(thisAccount != null);
        System.assertEquals('Test record', thisAccount.Name);
    }

   

    // Helper method
    static Id createTestRecord() {
        // Create test record
        Account accountTest = new Account(
        Name='Test record');
        insert accountTest;
       
        Contact con1 = new Contact(
        AccountId = accountTest.Id,
        firstName = 'test',
        lastName  =  'tester');
        insert con1;
        return accountTest.Id;
    }          

}


 
Hi All,

I'm a bit rusty on writing apex test code. I have a trigger that uses the .clone method to clone an opportunity and child records. Simply creating and inserting objects is not enough to test the trigger. I've tried Systems asserts to compare old opportuntiy to the new with no luck. Any advice on the best approach here?  

My trigger code (I realize I still need to pull the logic into a separate class and call that in my trigger) :  
 
trigger OpportunityTrigger on Opportunity (after insert, after update) {
    if(checkRecursive.runOnce()){
        
        
        
        
        // Interate selected opp records
        for (Opportunity opp : Trigger.new){
            if(opp.Renewable__c=='Yes' && opp.StageName=='Closed Won'){
                
                try{
                    id OpportunityId = opp.id;
                    List<Opportunity> oldOpps = [Select Accelera__c,renewable__c,RenewalCreated__c,jsImpacts__Added_from_Data_com__c,ASI_Opportunities__c,ASI_Strength__c,
                                                 ASI_Threats__c,ASI_Weakness__c,vs_Associated_eValuePrompter__c,Base_Number__c,Base_Term__c,BD_Opp__c,Big_Deal_Approved__c,vs_Business_Issue__c,vs_Business_Value__c,Capture_Opp__c,Close_Month_Try__c,Competition_Type__c,Contracting_Officer__c,Contrat_Type__c,Contract_Vehicle__c,CurrentGenerators__c,DB_Competitor__c,DealReg_Info__c,Deal_Registration_Date__c,Delivered_Services_Cost__c,Delivered_Services_Margin__c,Delivered_Services_Revenue__c,DeliveryInstallationStatus__c,Demos_Orals_BAFO__c,Differentiators__c,Discriminators__c,DRFP_RFP_Release_Date__c,Finance_Processed__c,Forecast_Category__c,Historical_Metric_1_Margin__c,Historical_Metric_2_Margin__c,Historical_Metric_3_Margin__c,Historical_Rev__c,Important_Qs_Updates_for_Opps__c,Incumbent__c,Industry_Date__c,Inside_Sales_Rep__c,Internal_Contract_Id__c,Is_Deal_Registered__c,vs_Last_Modified_eValuePrompter__c,Lowest_Line_Item_Margin__c,MainCompetitors__c,vs_Manager_Accepted__c,vs_Manager_Notes__c,
                                                 vs_Manager_Review_Request__c,Metric_1__c,Metric_2__c,Metric_3__c,Metric_4__c,MicrosoftRevenue__c,MiscRevenue__c,Mitigation__c,MSA__c,NAICS__c,NDA__c,NEW_Total_Quote_Margin_Value__c,Non_Commissionable__c,Notes_for_Processing_Order__c,Opportunity_Contains__c,Opportunity_ID__c,Option_Renewal_Period__c,Options_Number__c,Owner__c,Owner_Split_Percent__c,Partner_Commission__c,Period_of_Performance__c,TO_PoP_End__c,TO_PoP_Start__c,vs_Personal_Value__c,PM_Approach__c,PM_Assigned__c,PMO_Managed__c,Potential_Competitors__c,Pricing_Strategy__c,Prime__c,Prime_Contractor__c,vs_Problems__c,Process_Status_Valid_Since__c,ProductRevenue__c,Program_Summary__c,Project_Close_Date__c,Project_Number__c,Proposal_Lead__c,Latest_News__c,PWin__c,QB_SAP_SO__c,QuoteRenewalMargin__c,Reason_For_Stage__c,Reason_For_Stage_Notes__c,Renewable_Term__c,RenewalRevenue__c,RFI_Source__c,RFP_Opp_ID__c,RFP_Date__c,RFP_Status__c,Sales_Partner__c,SAP_Opportunity_ID__c,Service_Business_Opp_Type__c,Service_Contract_Type__c,Services_Invoiced_Through_Date__c,ServicesRevenue__c,SNACKsLead__c,vs_Solutions__c,
                                                 Solution_Type__c,SOW_Needed__c,Split_Rep__c,Split_Rep_Percent__c,Stage_Since_Date__c,Sub__c,Subcontractor__c,TCV__c,Technology_Approach__c,Total_Cloud_Margin__c,Total_Cloud_Revenue__c,Total_Enterprise_Services_Margin__c,Total_Enterprise_Services_Revenue__c,Total_Historical_Margin__c,Total_Managed_Services_Margin__c,Total_Managed_Services_Revenue__c,Total_Opportunity_Margin__c,Total_Opportunity_Revenue__c,Total_Product_Margin__c,Total_Product_Quantity__c,Total_Product_Revenue__c,TotalQuoteMargin__c,Total_Rebate_Margin__c,Total_Rebate_Revenue__c,TotalRevenue__c,
                                                 Total_Services_Margin__c,Total_Services_Revenue__c,Total_Workplace_Margin__c,Total_Workplace_Revenue__c,TrackingNumber__c,Value_Proposition__c,vs_Influencer_Role__c,vs_Vision_Match__c,Weighted_Opp_Margin__c,Weighted_Total_Margin__c,Workplace_Margin__c,AccountID,Amount,CloseDate,ContractID,CreatedByID,Description,ExpectedRevenue,ForecastCategoryName,LeadSource,NextStep,Name,OwnerID,RecordTypeID,Pricebook2ID,CampaignID,IsPrivate,Probability,TotalOpportunityQuantity,StageName,SyncedQuoteID,Type,
                                                 (Select OpportunityID,ID,Accelera_Sales_Rep__c,AccountID,AdditionalAddress,AdditionalName,AlternativeProjectManagerRate__c,ASI_Rep__c,ASI_Rep_E_Mail__c,BillingAddress,BillingName,ContactID,ContractID,ContractVehicle__c,CreatedByID,CustomProjectManagerHours__c,DefaultProjectManagerRate__c,Description,Discount,Email,EngineeringServicesDescription__c,ExpirationDate,Fax,For_End_User_del__c,GrandTotal,Internal_Comments__c,IsSyncing,Labor_Category__c,LaborDiscountPercent__c,LastModifiedByID,Name,Payment_Term__c,Payment_Terms__c,Phone,Project_Management_Hours__c,Project_Management_Rate__c,ProjectManagerActualCost__c,ProjectManagerPercentHours__c,Quote_Shipping_Handling__c,Quote_Tax__c,QuoteToAddress,QuoteToName,RecordTypeID,ShippingAddress,ShippingHandling,ShippingName,Status,Tax,TotalLaborActualCost__c,TotalLaborSalesPrice__c,TotalMicrosoftActualCost__c,TotalMicrosoftSalesPrice__c,TotalMiscActualCost__c,TotalMiscSalesPrice__c,TotalProductActualCost__c,TotalProductSalesPrice__c,TotalRenewalActualCost__c,TotalRenewalSalesPrice__c,Wrokplace__c from Quotes),
                                                 (Select PricebookEntryId,CreatedByID,ServiceDate,Discount,LastModifiedByID,Description,ListPrice,OpportunityID,Product2ID,ProductCode,Quantity,UnitPrice,Subtotal,Actual_Cost__c,Item_Margin__c,Quosal_Business_Unit__c,Quosal_Contract_Vehicle__c
                                                  from OpportunityLineItems) from Opportunity where ID = :OpportunityId AND RenewalCreated__c =False];
                    
                    if(oldOpps.size()>0){
                        List<OpportunityLineItem> olis = new List<OpportunityLineItem>();
                        List<Quote> qteList = new List<Quote>();
                        Opportunity oldOpp = oldOpps[0];
                        Opportunity newOpp = oldOpp.clone(false,true,false,false);
                        newOpp.StageName = 'Qualification';
                        newOpp.Name = oldOpp.Name + ' - RENEWAL';
                        integer months = integer.valueOf(oldOpp.Renewable_Term__c);
                        date newCloseDate = oldOpp.CloseDate;
                        newCloseDate = NewCloseDate.addMonths(months);
                        newOpp.CloseDate = newCloseDate;
                        newOpp.Reason_For_Stage__c = null;
                        newOpp.Probability = 5;
                        NewOpp.RenewalCreated__c = True;
                        OldOpp.RenewalCreated__c = True;
                        insert newOpp;
                        update oldOpp;
                        for(OpportunityLineItem oli : oldOpp.OpportunityLineItems){
                            
                            OpportunityLineItem oliNew = oli.clone(false,true,false,false);
                            oliNew.OpportunityId = newOpp.id;
                            
                            olis.add(oliNew);
                        }
                        for(Quote qte : oldOpp.quotes){
                            
                            quote qteNew = qte.clone(false,true,false,false);
                            qteNew.OpportunityId = newOpp.id;
                            
                            qteList.add(qteNew);
                        }
                        
                        if(olis.size() > 0)
                            insert olis;
                        if(qteList.size() > 0)
                            insert qteList;
                    }
                } catch (Exception e){            
                            system.debug(e.getMessage() + e.getStackTraceString()); 
                            
                        }
                    
                }
                
            }
        }
    }

My Test Code: 
@isTest
public class OpportunityCloneTriggerTest {
    
   @isTest
    public static void TestMethod1(){
        
        //Create Account
        Account newAccount = new Account(
            Name='TestAccount',
            Phone='3035551212');
        insert newAccount;
        
        //Create Product
        Product2 newProduct = new Product2(
            Name='NewProd',
            ProductCode = 'VSC24B100',
            isActive = true);
        insert newProduct;
        
        
        //Create your pricebook entry
        Id pricebookId = Test.getStandardPricebookId();
        PricebookEntry newPBE = new PricebookEntry(
            Pricebook2Id = pricebookId,
            Product2Id = newProduct.Id,
            UnitPrice = 500.00,
            IsActive = true
        );
        insert newPBE;
        
        //Create Opportunity
        Opportunity newOpportunity = new Opportunity(
            Name='NewOpp', 
            AccountId = newAccount.Id,
            StageName='Payment Processing',
            CloseDate=date.newInstance(2016, 1, 1));
        insert newOpportunity;
        
        
        //Validate single insert
        for(Opportunity o:[SELECT id FROM Opportunity 
                           WHERE id = :newOpportunity.id]) {
             System.assertEquals(o.id, newOpportunity.id);
            }
        
        
        
        //Create Opportunity Product
        OpportunityLineItem newOppLineItem = new OpportunityLineItem(
            OpportunityId = newOpportunity.Id, 
            PricebookEntryId = newPBE.Id,Quantity = 1, 
            TotalPrice = newPBE.UnitPrice
            );
       
            insert newOppLineItem;  
        
        
        //Create Opportunity Quote
        Quote newQuote = new Quote(
            name = 'testquote',
            OpportunityId = newOpportunity.Id, 
            ExpirationDate = date.newInstance(2016, 1, 1)
            );
        insert newQuote;
        
        //Update the stage
        newOpportunity.StageName='Closed Won';
        update newOpportunity;
    }
}

Lines not covered:

User-added image

User-added image
 
Hi All,

Getting Null pointer exception on If Statement Only if field is not populated, after update. Added null check to avoid but it didnt work. What is wroing with my Null check?
 
if(l.Website_Inquiry_Type__c.containsIgnoreCase('Buy Generator') 
           ||l.Website_Inquiry_Type__c.containsIgnoreCase('Sell Generator')
            &&  l.Website_Inquiry_Type__c != null  ) 

               { rest of my code that works fine}

 
Hi All,

I'm getting an invalid id error when I call userAccounts.get(p.Ownerid).AccountId; I think I may be populating my userAccounts map incorrectly?
 
list<ID> pubIds = new list<ID>();
        
        for(Publication__c p: pubList){ 
            pubIds.add(p.id);                      
        }
        
        list<ID> UserIds = new list<ID>();
        
        for(Publication__c p: pubList){ 
            UserIds.add(p.ownerid);                      
        }
        map<id,user> userAccounts = new map <id, user>([SELECT Id, Name, AccountId
                                                                                           FROM User 
                                                                                           WHERE Id IN :UserIds 
                                                                                           AND IsActive = true]);
        
        
        list<Publication__c> pubsToUpdate = [SELECT ID, ownerId
                               					     FROM Publication__c 
                               					      WHERE ID in: pubIds];
        
        for(Publication__c p: pubsToUpdate){
            
            p.Next_Object__c      = stepOneMap.get(p.Id).id;
            
 	          	if(userAccounts.get(p.OwnerId).AccountId !=''){
              
             	  	 p.Account__c = userAccounts.get(p.Ownerid).AccountId;
           			
            }
                             
                              }
        Update pubsToUpdate;

 
Hi,

I am unable to access certain owner fields on the user object. I'm trying to reach the standard AccountID field and a custom field with no luck. I can reach Owner.name without a problem though. 

This works: 
SELECT ID, owner.Name FROM Publication__c

 and this works:
SELECT ID, owner.email FROM Publication__c

BUT this will NOT work:

SELECT ID, owner.AccountID FROM Publication__c

Is this a known limitation?
Hi All,

Can't seem to get my WHERE clause correct. Getting Invalid bind expression type of Object for column of type Id error. Here is the full class:
 
public class SubmitPublicationController {
    @AuraEnabled
    public static sObject getObjectById(ID anId) {
        
        system.debug('Entering controller');
        // Get the sObject token from the first ID
        Schema.SObjectType token = anId.getSObjectType();
        
        // Using the token, do a describe 
        // and construct a query dynamically. 
        Schema.DescribeSObjectResult dr = token.getDescribe();
        String queryString = 'SELECT Id, Name, Publication__c, Next_Object__r.Id, Previous_Object__r.Id FROM ' + dr.getName() + 
            ' WHERE Id = :anId Limit 1 ';
        
        system.debug('describe object result' + dr.getName());
        
        sObject objDBResult = Database.query(queryString);
       
      	List <Publication__c> pubsList = [SELECT ID, Publication_Submitted__c
                          	   FROM Publication__c
                               WHERE ID = :objDBResult.get('Publication__c')
                                         ];
        
        pubsList[0].Publication_Submitted__c = true;
        
        system.debug('pub ID='+pubsList);
    
        upsert pubsList;
        
        System.debug('ID is: ' + anId);  
        System.debug('objDBResult: ' + objDBResult); 
        
        return objDBResult;
       
    }
    
    

}

 
Hello,

Test coverage at 80% and I cant figure out why. Red highlight on Line 11 "return result;" GET request is working fine in workbench.

Account manager class:
 
@RestResource(urlMapping='/Accounts/*/contacts')
global with sharing class AccountManager {

    @HttpGet
    global static Account getAccount() {
        RestRequest request = RestContext.request;
        // grab the accountId from the end of the URL
        String accountId = request.requestURI.substringBetween('Accounts/', '/contacts');
        Account result = [SELECT ID,Name,(SELECT ID,Name FROM Contacts) FROM Account WHERE Id = :accountId ];
        system.debug(result);
        return result;
        
    }
}
Test Class:
 
@IsTest
private class AccountManagerTest {

    @isTest static void testGetAccount() {
        Id recordId = createTestRecord();
        // Set up a test request
        RestRequest request = new RestRequest();
        request.requestUri =
            'https://na1.salesforce.com/services/apexrest/Accounts/'+ recordId+'/Contacts';
        request.httpMethod = 'GET';
        RestContext.request = request;
        // Call the method to test
        Account thisAccount = AccountManager.getAccount();
        // Verify results
        System.assert(thisAccount != null);
        System.assertEquals('Test record', thisAccount.Name);
    }

   

    // Helper method
    static Id createTestRecord() {
        // Create test record
        Account accountTest = new Account(
        Name='Test record');
        insert accountTest;
       
        Contact con1 = new Contact(
        AccountId = accountTest.Id,
        firstName = 'test',
        lastName  =  'tester');
        insert con1;
        return accountTest.Id;
    }          

}


 
Hi Everyone,

Trying to complete the Rest Callouts challenge and getting this error on the last line: return strResponse;. Here is my code:
public class AnimalLocator {

    public static HttpResponse getAnimalNameById(Integer ID){
        Http http           = new Http();
        HttpRequest request = new HttpRequest();
        request.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals/'+ID);
        request.setMethod('GET');
        HttpResponse response = http.send(request);
        
        String strResponse = '';
        
        if(response.getStatusCode()==200){
        
            Map<String,Object> results = (Map<String,Object>) JSON.deserializeUntyped(response.getBody());
            
            Map<String,Object> animals = (Map<String,Object>) results.get('animals');
           
            system.debug('These are the animals:');
            
            strResponse = string.valueOf(animals.get('name'));
            
        }
        return strResponse;
    }
}

Thank you!
Want my soql query to find records with specific record types. OR stement returning error: expecting right square bracket, found 'OR'

Do I need to create additional soql queries to first obtain record types, then reference in existig soql?

Thanks!

Existing soql
List<AggregateResult> results = [SELECT Account__c, 
                                         SUM(X2_1_a_Total_of_jobs_Year_0__c) mysum0,
                                         FROM Form__c 
                                         WHERE Account__c IN:accountIds
                                         AND (RecordType.DeveloperName ='Baseline Report')
                                         OR  (RecordType.DeveloperName ='Annual Report')
                                         GROUP BY Account__c]  ;

 
Is this possible (with the correct syntax)?
 
if(AggregateResult results = [SELECT SUM(X2_1_a_Total_of_jobs_Year_2__c) FROM Form__c] > results.size(0)){
    
    System.debug('sum of year 2 greater than 0');
}else{
    system.debug('sum of year 2 NOT greater than 0');
}

I know you can use Count() in an expression like this (according to this jeff douglass post (http://blog.jeffdouglas.com/2010/04/12/using-aggregateresult-in-salesforce-com-soql/)) because it returns the number of rows, not an object. But can I cast into an integer or something else?
Hi all,

I have a trigger that calculates the difference of values from year to year on account child records (form__c). Everything is working except for scenarios where a given year = 0. I've added an IF statement to handle this scenario, but what I really need is the SUM of ALL X2_1_a_Total_of_jobs_Year_2__c values under an account. Example, IF(f.X2_1_a_Total_of_jobs_Year_2__c:SUM > 0). 

Do I need to use aggregateResult here? 
 
if(f.X2_1_a_Total_of_jobs_Year_2__c > 0){
               calculated += f.X2_1_a_Total_of_jobs_Year_2__c - f.X2_1_a_Total_of_jobs_Year_1__c;
            }else {
               calculated = f.X2_1_a_Total_of_jobs_Year_1__c;


The full trigger:
 
trigger JobsIncomeCalc on Form__c (after insert, after update, after delete) {
    
    //Forms List
    List <Form__c> FormsList = New List <Form__c>();
    
    //Distinguish whether the list should act on insert, update or delete
    
    if(trigger.isInsert || trigger.isUpdate){
        FormsList = Trigger.New;
    }
    if(trigger.isDelete){
        FormsList = Trigger.Old;
    }
    
    //Account Ids Set 
    Set <id> accountIds = New Set <id>();
    
    //Add form account ids to set
    for(Form__c form: FormsList){
        
        accountIds.add(form.Account__c);
        
        System.debug('account id'+form.Account__c);
        
        accountIds.remove(null);

    }
    
    //Account Map
    
    If(!accountIds.IsEmpty()){
        Map<Id, Decimal> accountMap = New Map <Id, Decimal>();
        
        for(form__c f: [
            select Account__c,
            X2_1_a_Total_of_jobs_Year_1__c,
            X2_1_a_Total_of_jobs_Year_2__c,
            X2_1_a_Total_of_jobs_Year_3__c,
            X2_1_a_Total_of_jobs_Year_4__c,
            X2_1_a_Total_of_jobs_Year_5__c,
            X2_1_a_Total_of_jobs_Year_6__c,
            X2_1_a_Total_of_jobs_Year_7__c,
            X2_1_a_Total_of_jobs_Year_8__c,
            X2_1_a_Total_of_jobs_Year_9__c,
            X2_1_a_Total_of_jobs_Year_10__c
            from Form__c
            where Account__c in :accountIds
        ]){
            if(!accountMap.containsKey(f.Account__c)){
                accountMap.put(f.Account__c, 0);
            }

              
            Double calculated = accountMap.get(f.Account__c);
            
            if(f.X2_1_a_Total_of_jobs_Year_2__c > 0){
               calculated += f.X2_1_a_Total_of_jobs_Year_2__c - f.X2_1_a_Total_of_jobs_Year_1__c;
            }else {
               calculated = f.X2_1_a_Total_of_jobs_Year_1__c;
            }
            
            accountMap.put(f.account__c, calculated);    
        }
        
        if(!accountMap.isEmpty()){
            List<Account> acctsToUpdate = new List<Account>();
            
            for(Id id : accountMap.keySet()){
                acctsToUpdate.add( new Account (
                Id = id,
                X2_1_a_Total_of_Jobs_Hist_Cumulative__c = accountMap.get(id)
                ));
                
            }
            
           update acctsToUpdate;
 
        }  
    }
}

Thank you!
 
Hi All,

I'm working on a trigger and could use some help. I've hit a report formula limitation and am trying to recreate the same logic in a trigger. The basic requirement is to collect a field value from child objects, run a simple calculation, then assign that value to a field on the parent account. From the debug statemtents, it seems that things seem to fall apart at line 55. Any feedback would be appreciated! 

Thank you!
 
trigger JobsIncomeCalc on Form__c (after insert, after update, after delete) {
    
    //Forms List
    List <Form__c> FormsList = [SELECT id,
                                Account__c,
                                Account__r.id,
                                X2_1_a_Total_of_jobs_Year_1__c, 
                                X2_1_a_Total_of_jobs_Year_2__c
                                FROM form__c];
    
    
    //Distinguish whether the list should act on insert, update or delete
    
    if(trigger.isInsert || trigger.isUpdate){
        FormsList = Trigger.New;
    }
    if(trigger.isDelete){
        FormsList = Trigger.Old;
    }
    
    //Account Ids Set 
    Set <id> accountIds = New Set <id>();
    
    //Add form account ids to set
    for(Form__c F: FormsList){
        
        accountIds.add(f.Account__c);
        System.debug('account id'+f.Account__c);
    }
    
    //Map to pair accounts and forms
    Map<id,Double> formAccountMap= New Map<id,Double>();
    
    for(form__c f: [SELECT id,
                    Account__r.id,
                    Account__r.X2_1_a_Total_of_Jobs_Hist_Cumulative__c
                    FROM Form__c 
                    WHERE Account__r.id IN: accountIds]){
                        
                        Double AccTotalJobsHist = f.Account__r.X2_1_a_Total_of_Jobs_Hist_Cumulative__c;                   
                        formAccountMap.put(f.Account__r.ID, AccTotalJobsHist);                
                        
                        system.debug('AccTotalJobsHist='+ AccTotalJobsHist);
                        system.debug('Account total jobs from form map='+ formAccountMap.get(f.Account__r.ID));
                        
                        
                    }
    
    //Accounts to update list
    List<Account> AcctsToUpdate = new List<Account>();
    
    system.debug('AcctsToUpdate='+AcctsToUpdate);
    //Apply calculation to all forms in FormList
    
    for(Account a: AcctsToUpdate){
        
        Double AccTotalJobsHist = formAccountMap.get(a.ID);
        system.debug('AccTotalJobsHist='+AccTotalJobsHist);
        system.debug('AccTotalJobsHist='+formAccountMap.get(a.ID));
        
        Double TotalJobsY1 = a.form__r.X2_1_a_Total_of_jobs_Year_1__c;
        Double TotalJobsY2 = a.form__r.X2_1_a_Total_of_jobs_Year_2__c;
        system.debug('TotalJobsY1='+TotalJobsY1);
        system.debug('TotalJobsY2='+TotalJobsY2);
        
        
        Double CalculatedTotalJobs = (TotalJobsY2 - TotalJobsY1);
        system.debug('CalculatedTotalJobs='+CalculatedTotalJobs);
        
        //Set calculated value in account field    
        
        AccTotalJobsHist = CalculatedTotalJobs; 
        
        AcctsToUpdate.add(a);
    }
    
    Update AcctsToUpdate;
    
}