[SalesForce] How to write && in apex if statement

In apex, what is a proper way to write && condition?

 trigger CreatePTOEvent on Thrive_HR_PTO_Request__c (after insert) {
// Event is created when PTO Request record is created
List<Event> ptoevents = new List<Event>();
List<Thrive_HR_PTO_Request__c> 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 && ptr.All_Day_Event__c = true) {
        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;
 }

Basically, I want to check if(daysDifference < 14 && ptr.All_Day_Event__c = true) these two conditions to trigger something.

Best Answer

You have an error with ptr.All_Day_Event__c = true. Instead of comparing using == you're assigning a value to your variable using =. The logical operator && is fine. This is very common problem and it happens quite often.

Related Topic