1

Hi I am new to Apex coding and I was wondering if there was any way to get access to a parent Custom object from the Lead.

My Custom Obj has the field : Lead (Lookup(Lead))

In Apex I tried :

  global TestController(ApexPages.StandardController stdController)
  {
    ShouldRender = false;
    SObject entity = stdController.getRecord();
    Object test = entity.getSObject('Test_Object__c');
    System.debug('This is test ' + test);
  }

and it keeps on saying there is no relationship from lead to Test_Object__c

1 Answer 1

1

You will need to query to get the related object. You can also cast the standard controller reference to your type so you can directly reference its named fields:

global TestController(ApexPages.StandardController stdController)
{
    ShouldRender = false;
    Test_Object__c t = (Test_Object__c) stdController.getRecord();
    if (t.Lead__c != null) {
        Lead l = [select Id, Name, ... from Lead where Id = :t.Lead__c];
        System.debug('t=' + t + ' l=' + l);
    }
}

(I'm assuming that the Lead is the "Parent" object as your custom object - I'm assuming that is Test_Object__c - has the lookup field but your question is a bit contradictory in that area. You can reverse Lead/Test_Object__c in the above code if the relationship is actually the other way round.)

PS

Based on the comment thread it is the Lead object that the standard controller is working with meaning that there can be zero to many Test_Object__c that reference that Lead so the code would look like this:

global TestController(ApexPages.StandardController stdController)
{
    ShouldRender = false;
    Lead l = (Lead) stdController.getRecord();
    Test_Object__c[] ts = [
            select Id, Name, ...
            from Test_Object__c
            where Lead__c = :l.Id
            order by Name
            ];
    System.debug('l=' + l + ' ts=' + ts);
}

and in this case you are referencing the child objects from the parent.

3
  • Thank you for your answer it really clarifies things. The Test_Object__c has a lookup field for Lead.
    – James
    Sep 2, 2015 at 20:57
  • Can you explain the casting you did? It did not work for me because the controller is the context of a lead. I got the error Invalid conversion from runtime type Lead to Test_Object__c
    – James
    Sep 2, 2015 at 21:04
  • @James My misunderstanding. You can cast providing the type is right i.e. matches the standardController attribute in the apex:page. See the PS.
    – Keith C
    Sep 2, 2015 at 21:24

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .