How to create an apex class that returns contacts based on incoming parameters?

471    Asked by DavidEDWARDS in Salesforce , Asked on Mar 1, 2023
 public class ContactSearch {
    public static list searchForContacts(string lastname,string MailingPostalCode)
    { 
        listContactList=[select id,name,lastname,mailingpostalcode from contact where lastname=:'lastname' and mailingpostalcode=:'MailingPostalcode'];
        return contactlist;
    }
}

Challenge not yet complete in venkat@gynanvruksh.com Executing the 'searchForContacts' method failed. Either the method does not exist, is not static, or does not return the expected contacts.

Answered by David Edmunds

To create an apex class that returns contacts based on incoming parameters - The parameters you have passed to the method are not getting utilized in the logic of the method. In the below line of code, You have passed the value as a static string in the where clause of your query and not as a variable.

list ContactList=[select id,name,lastname,mailingpostalcode from contact where lastname=:'lastname' and mailingpostalcode=:'MailingPostalcode'];
Instead you need to remove the single quotes from lastname and mailingpostalcode in where clause and it will solve your problem.
list ContactList=[select id,name,lastname,mailingpostalcode from contact where lastname=:lastname and mailingpostalcode=:MailingPostalcode];

You should know about using a bind variable in a soql query. SOQL and SOSL statements in Apex can reference Apex code variables and expressions if they’re preceded by a colon (:). This use of a local code variable within a SOQL or SOSL statement is called a bind. The Apex parser first evaluates the local variable in code context before executing the SOQL or SOSL statement.



Your Answer

Interviews

Parent Categories