1

I have the below Apex code show a sectionBlock when a user selection contains 'Answering the Door' or 'Wandering' from a VisualForce intake page. The Apex should also set the Custom_Products__c checkbox on the submitted object to 'true', if the code to show the sectionblock renders true.

The issue I'm having is, when testing on the Intake page, I make sure the user selection does NOT contain 'Answering the Door' or 'Wandering'. I can tell this does not evaluate to true, because the sectionblock does not render, as it does when user selection contains 'Answering the Door' or 'Wandering'.

However, when the intake form is submitted, the created object sets the Custom_Products__c checkbox to 'true'. I thought, based on my below code, this should only be set to true if getShouldShowRingSection renders true (which, in my testing did not, since the sectionblock did not appear).

What am I missing?


public with sharing class ShouldShowRingSection{
    public ShouldShowRingSection(ApexPages.StandardController paramController) {
       standardController = paramController;}
    public ApexPages.StandardController standardController {get; set;}
    public Boolean getShouldShowRingSection() {
       Opportunity record = (Opportunity)standardController.getRecord();
        
          if(
            (record.Safety_Concerns__c != null && record.Safety_Concerns__c.contains('Answering the Door')) || (record.Safety_Concerns__c != null && record.Safety_Concerns__c.contains('Wandering'))
            ) 
            {
            return true;
            }
      
          if (true) {
            record.Custom_Products__c = true;
                    }  
        
          return false;
        }
        
        }

1 Answer 1

3

You don't write code exactly as you would in English. if(true) is always true, and code executes from top to bottom, so a return statement immediately ends a method, even if you don't reach the last line of code in the method.

Also, checking for null is (mostly) outdated in modern code. You can use the Safe Navigation Operator to make it slightly more legible.

As such, your code should look like:

if(record.Safety_Concerns__c?.contains('Answering the Door') == true || record.Safety_Concerns__c?.contains('Wandering') == true) {
    record.Custom_Products__c = true;
    return true;
}
return false;
        
1
  • Ahhhh this is exactly what I needed - Thank you so much! Apr 26, 2021 at 19:28

You must log in to answer this question.

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