5

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.

3
  • That's exactly how to write logical AND, there is no other way, you're on the right track. Do you have any problems with the current code or you're just making sure? Commented Sep 11, 2014 at 6:27
  • Well, apparently I am getting an error in my developer console "Expression cannot be assigned". Commented Sep 11, 2014 at 6:30
  • 1
    Thats because of you are having single =` mark here in ptr.All_Day_Event__c = true. You no need of having it if the field is a boolean
    – highfive
    Commented Sep 11, 2014 at 6:34

2 Answers 2

5

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.

0
1

It's the same as in any other language. What you have in your code is ok if you can improve a little.

if(daysDifference < 14 && ptr.All_Day_Event__c)


You no need of having prt.All_Day_Event__c == true if All_Day_Event__c is a Boolean field. Your if block will execute if both the conditions return true

2
  • Thanks highfive! I can't believe I didn't catch that. Commented Sep 11, 2014 at 6:34
  • It's ok if you are checking with the == as well in case of field is having null values
    – highfive
    Commented Sep 11, 2014 at 6:36

You must log in to answer this question.

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