How can I pass a list of custom objects to my component controller?

I want to assign a list of custom objects to my component controller. If I don’t assign it I get the list into the component but as soon as it try to assign the list of objects to the controller it fails:

Cannot convert the value of ‘{!MyItemList}’ to the expected type.

Page:

<apex:page standardController="MyObject__c">
    <c:CustomComponent myItemList="{!MyObject__c.MyItems__r}">
    </c:CustomComponent>
</apex:page>

Component:

<apex:component controller="CustomComponentController">
    <apex:attribute name="myItemList" type="MyItem__c[]" description="" assignTo="{!MyItemList}"/>
</apex:component>

Controller:

public with sharing class CustomComponentController {
    public MyItem__c[] MyItemList { get; set; }
}

Why does it fail? How can I pass a list of my objects?

Answer

That is strange indeed. A workaround is to add a layer of indirection when passing in the relationship list MyObject__c.MyItems__r to the component attribute. Rather than access the relationship list directly from the record in visualforce, use a custom controller method for your visualforce page that exposes the record’s related list property that way.

Page:

<apex:page standardController="MyObject__c" extensions="MyObjectController">
    <c:CustomComponent myItemList="{!myItems}">
    </c:CustomComponent>
</apex:page>

Controller:

public with sharing class MyObjectController {

    public MyObject__c myObject { get; set; }

    public MyObjectController( ApexPages.StandardController stdController ) {
        this.myObject = [ select id, ( select id from MyItems__r ) from MyObject__c where id = :stdController.getId() ];
    }

    // workaround: rather than reference the relationship list
    // directly within visualforce, instead reference it indirectly
    // through this controller method
    public List<MyItem__c> getMyItems() {
        return myObject.MyItems__r;
    }
}

Attribution
Source : Link , Question Author : Semmel , Answer Author : Doug Ayers

Leave a Comment