+ Start a Discussion
loneboatloneboat 

How to "get" a child object (not just the ID!) into a variable?

I have two custom object types, call them [Type_A__c] and [Type_B__c].  A has a lookup field to B.

 

I have a controller extension I'm writing for type A.  The basic class looks like this:

 

 

public with sharing class Type_A_Extension {

    public Type_A__c objA { get; private set; }
    public Type_B__c objB { get; private set; }
    
    public Type_A_Extension(ApexPages.StandardController stdController) {
        objA = (Type_A__c)stdController.getRecord();
        
        //  objB = objA.Lookup_To_B__c;
    }
}

 

 

The last line is throwing an error in the IDE, and from what I can gather, it's because objB is actually of type [Type_B__c], whereas objA.Lookup_To_B__c is of type [ID].

 

I know that I could do a SOQL query like

 

List<Type_B__c> objB_list = [SELECT fieldA, fieldB, fieldC ... FROM Type_B__c WHERE Id = :objA.Lookup_To_B__c ];
objB = objB_list[0];  //  only if I'm sure there is a result!

 But this seems pretty verbose, especially if there are a lot of fields on type B.  Is there any way to just grab a record and cast it to a known type if I have the ID via a lookup field from another object?  Like a cast or some Database method?

 

Something like:

//  I know this won't really work; it's just what I WISH would work;
Database.getRecord(objA.Lookup_To_B__c);

 or even:

objB = (Type_B__c)objA.Lookup_To_B__c;

 

Starz26Starz26

You have two options:

 

1. The first option using the SOQL Query. Although you do not need a list since you are restricting the result to a particular ID:

 

Type_B__c objB = [SELECT fieldA__c, fieldB__c, fieldC__c ... FROM Type_B__c WHERE Id = :objA.Lookup_To_B__c ];

Then use objB.fieldA__c etc

 

 

2. Change the standardController of the page to the child record, when loading the page, use the child record ID as a paramater, as well as the parent record id. Use the ID of the parent to grab the fields you want from the parent. The entire record of the child will then be avalilable to you on the page.

 

#2 only works if you do not need much from the parent.

craigmhcraigmh

Read up on relationship queries, they're pretty flexible for not allowing JOINs:

 

http://www.salesforce.com/us/developer/docs/api/Content/sforce_api_calls_soql_relationships.htm

loneboatloneboat

Thanks for the reply.  I've seen relationship queries, but I don't see how they would enable me to accomplish what my original question was about (obtaining an entire object without having to specify every field).

 

Thanks!

craigmhcraigmh

Yeah, that's one of the rough parts of SFDC. You struggle to do that even with parent objects, since you can't do a SELECT *.