Wednesday, April 9, 2014

Troubleshooting of Set's with sObjects in an apex:repeat


Below is the troubleshooting steps/thought process I took to figure out why my Set wasn't working when it contained sObjects in an apex:repeat. Long story short, its just not possible, it seems that since sets are unordered lists, it cant iterate over sObjects.. I think it still should be able to :-P


I have some code that creates a set (using set so it will be unique) of sObjects and then on the page it iterates over the set using an apex:repeat. The problem is that it wont save. If I change the Set to a List it saves and works fine. Here is the code (simplified) and the errors:

    public class CreateOrders {

      public Set<Item__c> selectedItems {get; set;}
      
      public CreateOrders() {
        selectedItems = new Set<Item__c>();
        for (Item__c i : findItems()) {
          selectedItems.add(i);
        }
      }
    }

then on the page:
    
    <apex:repeat value="{!selectedItems}" var="itm">
      <apex:outputfield value="{!itm.Name}" />
    </apex:repeat>

and the resulting error is: 

Save error: Could not resolve the entity from apex:outputField value binding '{!itm.Name}'.  apex:outputField can only be used with SObjects, or objects that are Visualforce field component resolvable. 

When I try removing the apex:outputfield by using apex:outputtext or nothing like so:

    <apex:repeat value="{!selectedItems}" var="itm">
      <apex:outputtext value="{!itm.Name}" />
    </apex:repeat>

OR

    <apex:repeat value="{!selectedItems}" var="itm">
      {!itm.Name}
    </apex:repeat>

I get this error: 

Save error: Unknown property 'SetValue.Name' 

Its the same with any field/object. But when I switch the Set over to a List it works without any issues... So on a hunch I checked the version, and it was on 28. When I upgraded it to 29, it allowed me to save with apex:outputfield only, but on refresh of the page I still got the same errors:

Could not resolve the entity from apex:outputField value binding '{!itm.Name}'. apex:outputField can only be used with SObjects, or objects that are Visualforce field component resolvable.

It still wouldn't let me save if I changed the apex:outputfield to apex:outputtext or used no apex tags it would still not save and give me the error:

Save error: Unknown property 'SetValue.Name'

On versions older than 29 (20-28 that I have tested) they all error like 28, 29 is the only one with a slightly different behavior. Also when saving with just {!itm} it allows the save to happen, and the page just shows the Id of the Item.


Here is the original stackexchange post with comments from other sfdc users as we tried to figure out this problem, along with the answer :-P I'll be posting more on sets/maps soon :-P

No comments:

Post a Comment