[SalesForce] How to use If Condition in Apex: pageBlockTable

I'm trying to display history of action performed on custom object 'Reservation' in VisualForce page in table using apex:pageBlockTable.

I have following method in controller:

public List<Reservation__History> getReservationHistory()
{
    Reservation__c rsv= (Reservation__c)currentcontroller.getRecord();
    List<Reservation__History> history = [SELECT ParentId, OldValue, NewValue, Field, CreatedById, CreatedDate FROM Reservation__History WHERE parentId = : rsv.Id ORDER BY CreatedDate DESC];
    return history;
}

And I'm calling this method in apex:pageBlockTable as follows:

<apex:pageBlockTable value="{!ReservationHistory}" var="history">
   <apex:column headerValue="Date" value="{!history.CreatedDate}"/>
   <apex:column headerValue="User" value="{!history.CreatedById}"/>               
   <apex:column headerValue="Action" value="!IF(history.OldValue='' AND history.NewValue='', 'Created', Changed '{!history.Field}' from '{!history.OldValue}' to '{!history.NewValue}')"/>               
</apex:pageBlockTable>

For "Action" column, if condition I tried above is not working. I want to display Action as 'Created' if both OldValue and NewValue are '' else display a sentence "Changed '{!history.Field}' from '{!history.OldValue}' to '{!history.NewValue}'".

Can anybody please let me know how to conditionally vary content in 'value' of apex:column for above scenario?

Best Answer

To use IF condition and to join conditions in Visualforce page, you should use one of the following approaches:

{!IF(AND(field1 <condition> value, field2 <condition> value), "Show on True", "Show on False")}

OR

{!IF(field1 <condition> value && field2 <condition> value, "Show on True", "Show on False")}

So in your case, to be able to get the first value to be true, your code should look like something as below (I prefer == for comparison to make it clear and not confuse with assignment)

{!IF(history.OldValue == '' && history.NewValue == '', "Created", "Changed history.Field from history.OldValue to history.NewValue}")}"

Notice few things here:

  1. You should enclose the condition within {}, which seems to be missing in your code posted
  2. You use ! with the IF and not with the field names in this case (as mentioned above)

Make necessary adjustments in case of other issues, but this should be your direction. You can refer for more details on how to construct expressions in VF page on its documentation here.

Related Topic