0

I'm trying to get a list, mlcs, of a custom objects "my last call date", which has a related contact, and add all of these contacts to a list of contacts, cs.

To use the .add() method, I need to use the contact__r suffix for the lookup field, Contact__c, or else I get an error. But, I have to query this field using the contact__c suffix, or else it will tell me that no row was found for contact__r. But if I do this, then it says I didn't query contact__r and cannot use it.

apex:

public class MyLastCallListView2{


public String currentUser = UserInfo.getUserId();


public list <My_Last_Call__c> mlcs {get;set;}
public list <contact> cs {get;set;}

   public void search(){  

       string callsList='select name,id, Contact__c, Contact_name__c, User__c from My_Last_Call__c WHERE User__c=\''+currentUser+'\'';  
 system.debug(callsList);
 mlcs= Database.query(callsList);  

 for (My_Last_Call__c m : mlcs){
 cs.add(m.Contact__r);
 }


   public MyLastCallListView2(ApexPages.StandardController controller){}





}

Error: SObject row was retrieved via SOQL without querying the requested field: My_Last_Call__c.Contact__r

If I change cs.add(m.Contact__r); to cs.add(m.Contact__c); or cs.add(m.Contact__c.id);, the code will not compile, with this error: Error: Compile Error: Incompatible element type Id for collection of Contact at line 22 column 2

2
  • 1
    Why are you even using dynamic soql?
    – Adrian Larson
    Mar 9, 2016 at 23:43
  • contact is child of My_Last_Call__c ?
    – Ratan Paul
    Mar 10, 2016 at 1:34

1 Answer 1

1

You don't use cross reference properly, you need to call at least one field of contact by using "Contact__r." Try to change :

string callsList='select name,id, Contact__c, Contact_name__c, User__c from My_Last_Call__c WHERE User__c=\''+currentUser+'\'';  

by

string callsList='select name,id, Contact__c, Contact__r.Name, User__c from My_Last_Call__c WHERE User__c=\''+currentUser+'\''; 
6
  • I tried this, fixed my original problem, but now I am getting a Attempt to de-reference a null object error at cs.add
    – MRG
    Mar 14, 2016 at 21:42
  • you probably need to check if you Contact__c is not null before to add
    – brovasi
    Mar 14, 2016 at 22:24
  • It's not null, but you're right, I should add that to my code
    – MRG
    Mar 14, 2016 at 22:25
  • Confusingly, when I look at my debug log, it shows that a Contact is returned: 15:29:26.0 (33552960)|USER_DEBUG|[22]|DEBUG|contact: Contact:{Name=Dr. Moneybags, Id=00363000003xhDVAAY, RecordTypeId=012j00000010G5jAAE}
    – MRG
    Mar 14, 2016 at 22:30
  • 1
    You don't init cs list at the start, you need to create a new instance, cs = new list<contact>();
    – brovasi
    Mar 14, 2016 at 22:45

You must log in to answer this question.

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