[SalesForce] Query CustomObject with Attachment

I want to select the fields name__c and description__c from my CustomObject along with the attachments from the attachment object.

Can I do this with my query below? What should i write in my inner select clause ParentId = Id?

public List <CustomObject__c> getTestList() {        
List <CustomObject__c> TestMSList = [SELECT Name__c, Desrciption__c, (SELECT Name FROM Attachment WHERE ParentId = Id) FROM CustomObject__c];
return TestList;        
}

Best Answer

There are two methods to achieve your task.

  1. Utilize StandardController controller provided by salesforce. This allows you to <apex:relatedList> which displays the relatedlist of any particular record. For example, if you're implementing standardcontroller for Account then for a particular record of Account it will display it's related list such as Contacts, Opportunities etc.

  2. Fetch the record along with it's related list. Just the way as @AlexanderBerehovskiy highlighted.

Method 1

<apex:page standardController="Account" extensions="Acc">   
    <apex:form>
        <apex:relatedList list="CombinedAttachments" >
             <apex:facet name="header">Notes and Attachments</apex:facet>
         </apex:relatedList>
    </apex:form>    
</apex:page>

Method 2

VF Page:

<apex:page standardController="Account" extensions="Acc">
    <apex:form> 
        <apex:pageblock >
            <apex:pageBlockSection >
                <apex:inputField value="{!myAcc.name}"/>
                <apex:inputField value="{!myAcc.id}"/>
            </apex:pageBlockSection>
            <apex:pageBlockTable value="{!myacc.attachments}" var="attach">
                <apex:outputField value="{!attach.Id}"/>
                <apex:outputField value="{!attach.Name}"/>
            </apex:pageBlockTable>
        </apex:pageblock>
    </apex:form>    
</apex:page>

Apex Controller:

public Account myAcc{get;set;}

    public Acc(ApexPages.StandardController controller) {
        myAcc= [SELECT id, name, (Select id,name from Attachments) FROM Account WHERE id = '0012800000EK4iY'];
    }
Related Topic