How can I write && in Apex if statement?

374    Asked by DianeCarr in Salesforce , Asked on Aug 29, 2023

I want to know the proper way to write && condition in Apex and to check whether the condition if(days Difference < 14 xss=removed>

The code is as follows:


List ptoevents = new List();
List ptorequest = Trigger.new;
for(Thrive_HR_PTO_Request__c ptr : ptorequest) {
    datetime StartDate = ptr.Start_Date__c;
    datetime EndDate = ptr.End_Date__c;
    date StartDateOnly = StartDate.date(); 
    date EndDateOnly = EndDate.date();
    Integer daysDifference = StartDateOnly.daysBetween(EndDateOnly);
    if(daysDifference < 14 xss=removed>        Event evt = new Event(
            Ownerid=ptr.CreatedById,
            WhatId=ptr.Id,
            Subject='Sicktastic' + ' on ' + ptr.Start_Date__c.date() + ' to ' + ptr.End_Date__c.date(),
            StartDateTime=ptr.Start_Date__c,
            EndDateTime=ptr.End_Date__c,
            ActivityDateTime=ptr.Start_Date__c,
            ActivityDate=ptr.Start_Date__c.date(),
            IsAllDayEvent = ptr.All_Day_Event__c
        );
        // add events to record
        ptoevents.add(evt);
    }
    else if (daysDifference >= 14) {
        ptr.End_Date__c.addError('You can not exceed more than 14 days');
        }
  }
     insert ptoevents;
 }
Answered by Buffy Heaton

There is a problem with ptr.All_Day_Event__c = true because you assign a value to your variable using =, whereas you have to compare the value using ==, but the logical operator && is okay. All you need to do is improve the code a bit.




There is no need to have prt.All_Day_Event__c == true if All_Day_Event__c is a Boolean field. The if block will run if both the conditions return true.



Your Answer

Interviews

Parent Categories