0

Apex Class:

public static String getOpportunityName(){

       String communityUserEmail = [SELECT Email FROM User WHERE Id = :UserInfo.getUserId()].email;
       List<Id> oppIds = new List<Id>();

       List<Contact> conts = [select name,(select name,ownerId from Opportunities) from Contact where Email = :communityUserEmail];
         for(Contact c : conts)
         for(Opportunity cts : c.opportunities){   

               oppIds.add(cts.ownerId);      
     }
     List<Opportunity>  ct = [select name,Ownerid from Opportunity 
      where id = :oppIds ];
      return ct.owner.name; //HERE SHOWS THE ERROR CALLED Variable DOESN'T OWNER
  }
2

Error is Here

List ct = [select name,Ownerid from Opportunity where id = :oppIds ];

return ct.owner.name; //HERE SHOWS THE ERROR CALLED Variable DOESN'T OWNER

Because of the wrong SOQL and return statement is list of Opportunity, & your trying to access directly without an index value.

List<Opportunity>  ct = [select Name,Owner.name from Opportunity where id = :oppIds ];
 return ct[0].owner.name;

or

 Opportunity  ct = [select Name,Owner.name from Opportunity where id = :oppIds limit 1];
     return ct.owner.name;
  • 1
    tq nithesh the error resolved – Raj Nov 20 '17 at 7:04
  • @Raj Welcome... – NITHESH K Nov 20 '17 at 7:04
0

Couple of things you should consider, besides the error, as part of apex best-practices guidelines

  1. Don't need to SOQL to get current user email address
String communityUserEmail = [SELECT Email FROM User WHERE Id = :UserInfo.getUserId()].email;

You don't need to perform SOQL here, as there is a direct method to get the current user's email using Userinfo.getUserEmail(), so optimized version of your statement would be

String communityUserEmail = Userinfo.getUserEmail();

  1. Use SOQL-for-loops - which is scalable and more efficient (refer to the best practices article for details)
List<Contact> conts = [select name,(select name,ownerId from Opportunities) from Contact where Email = :communityUserEmail];
     for(Contact c : conts)

Better approach

for(Contact c : [select name,(select name,ownerId from Opportunities) from Contact where Email = :communityUserEmail])
  1. What if your current user has no opportunities, means oppIds is null? Put a check to avoid null-pointer exception

improved version

if (oppIds.size() > 0) List<Opportunity>  ct = [select name,Ownerid from Opportunity  where id = :oppIds ];

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.