function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Arun ChaubeyArun Chaubey 

Create an Apex class that returns contacts based on incoming parameters

Hi,
I am not able to understand the below question correctly Please help me out. - 
Create a class that has a method accepting two strings. The method searches for contacts that have a last name matching the first string and a mailing postal code (API name: MailingPostalCode) matching the second. It gets the ID and Name of those contacts and returns them.The Apex class must be called 'ContactSearch' and be in the public scope.
The Apex class must have a public static method called 'searchForContacts'.
The 'searchForContacts' method must accept two incoming strings as parameters, find any contact that has a last name matching the first, and mailing postal code matching the second string. The method should return a list of Contact records with at least the ID and Name fields.
The return type for 'searchForContacts' must be 'List<Contact>'.
KaranrajKaranraj
Hi Arun,

1. You have to creat a public class with the Name 'ContactSearch'
2. Then create a method in the class with the name 'searchForContacts' which should accepts two string parameters and the return type of the method should be List<contact>. Check the below sample method structure
public returnType methodName(Parameter,Parameter,parameter,...){
//Logic
return
}
3. Write a SOQL query in the method which will fetch the Id,Name from the contact method and in the where condition of SOQL query check the first parameter with the field 'Last Name' and the second method parameter with the field the 'MailingPostlCode'  

Thanks,
http://karanrajs.com
Arun ChaubeyArun Chaubey
Thanks karanraj, 
I am not able to understand this line " find any contact that has a last name matching the first ". what does it mean by " last name matching the first ". Does it mean the last name should be matching the first name?

Thanks,
Arun
KaranrajKaranraj
Arun - The LastName must be match with first parameter of your method, its not the first name.
Something similar to the below sample structure.
public returnType methodName(firstParameter,secondParameter){
con = [Select ..... from Contact where LastName = :firstParameter and etc..];
}

 
Arun ChaubeyArun Chaubey
Thanks Karanraj, Got it..
Ghanshyam Yadav01Ghanshyam Yadav01
Hi Everyone, 
Below code is working fine, if anyone got error, can refer this code

public class ContactSearch{
public static List<Contact> searchForContacts(String s,String sh){
return [select LastName,MailingPostalCode from Contact order by LastName,MailingPostalCode desc];
}
}

Regards,
Ghanshyam
Satyanarayana PusuluriSatyanarayana Pusuluri
Hi,

Below code working fine for this challenge

public class ContactSearch{
    public static List<Contact> searchForContacts(String s,String sh){
        return [select LastName,MailingPostalCode from Contact order by LastName,MailingPostalCode desc];
    }
}

Thanks & Regards,
Satya P
KaranrajKaranraj
@Satyanarayana - Please don't post the answers of Trailhead challenges here or anywhere. I encourage you to help by making them to understand the problem and guide them solve the problem instead of posting answer that's benifits more to them
sagar shah 18sagar shah 18

public class ContactSearch {
    public static List<Contact> searchForContacts(String lastname, String Postalcode){ 
        List<Contact> con = [select ID,Name FROM contact WHERE LastName=:lastname AND MailingPostalCode=:Postalcode];
        return Con;
    }
    }

 

Above is the working code if you want can refer this code

Jeremy GaisieJeremy Gaisie
I've been a little confused by how I can view debug logs. I have been using the following command for this task: System.debug(contactQuery[0].LastName + contactQuery[0].Id);
where contactQuery is my list, however I'm unable to find this printout in the debug log?

My reason for the search (as i've completed the challenge) is I wish to see if i'm printing everything or just the relevant fields LastName and Id
Mandodari RawatMandodari Rawat
public class ContactSearch {
    public static List<Contact> searchForContacts(String lstname, String mpcode){
        List<Contact> ctc = new List<Contact>();
        ctc = [SELECT FirstName FROM Contact WHERE LastName=:lstname AND MailingPostalCode=:mpcode];
        return ctc;
       }
}
Verma, ManishVerma, Manish
Hi,

Use the below code:
 
public class ContactSearch {
    public static List<Contact> searchForContacts (String lName, String mailPostalCode){
        try{
            List<Contact> contacts = [SELECT Name FROM Contact WHERE (LastName = :lName AND MailingPostalCode = :mailPostalCode)];
            return contacts;
        }catch(DmlException e){
            System.debug('An error occurred: ' + e.getMessage());
            return null;
        }
        
    }
}

Hope this helps!!
Muhammad AlaaMuhammad Alaa
HYG
public class ContactSearch {
	public static List<Contact> searchForContacts(String sName, String sPCode) {
        List<Contact> lContacts = [SELECT Name FROM Contact WHERE (LastName = :sNAME AND MailingPostalCode = :sPCode)];
        return lContacts;
    }
}

Lacks a TryCatch, though
 
Matthew Solomon 802Matthew Solomon 802
Why does the WHERE statement need to contain an AND? Doesn't that mean the query will only return contacts where the last name = the lastname of the contact AND the MailingPostalCode = the MailingPostalCode of a Contact; meaning that both parameters must be true on a single contact? This list should return 2 contacts and this potentially means only one would be returned. Maybe I am thinking incorrectly?
Verma, ManishVerma, Manish
Hi Matthew,

As the question says:
‘Create a class that has a method accepting two strings. The method searches for contacts that have a last name matching the first string and a mailing postal code (API name: MailingPostalCode) matching the second.’

It specifies that the result must contain all the records which satisfy BOTH the conditions SIMULTANEOUSLY. Therefore to fetch all records which meet this criteria we need to have an ‘AND’ in the ‘WHERE’ clause.

Hope this makes sense. Let me know if you have any doubt about it.
Matthew Solomon 802Matthew Solomon 802
Okay that makes sense so we are looking for contacts that meet both criteria. However, I passed the challenge by setting two variables each equal to the queries defined in question and then added them to a list. In theory should I have not passed because the conditions were exclusive and only referenced one condition in each of the where statement?
Verma, ManishVerma, Manish

Matthew

Could you please provide your code here so that I can better understand and provide a theorytical solution. 

Thanks

Matthew Solomon 802Matthew Solomon 802
public class ContactSearch {
    public static List<Contact> searchForContacts(String str1, String str2){
        Contact query1 = [SELECT ID, FirstName, LastName FROM Contact WHERE LastName = :str1];
        Contact query2 = [SELECT ID, FirstName, LastName FROM Contact WHERE MailingPostalCode = :str2];
        List<Contact>querys = new List<Contact>{query1,query2};
        return querys; 
    }
}

I was able to pass with the above. However, these two queries search for different things which would mean there should be an OR instead of an AND
Verma, ManishVerma, Manish
Hello Matthew,

Using two queries (which you have used) might return duplicate data since contacts return by query1 and query2 can have common contacts since both queries are different.
 
Contact query1 = [SELECT ID, FirstName, LastName FROM Contact WHERE LastName = :str1];
Contact query2 = [SELECT ID, FirstName, LastName FROM Contact WHERE MailingPostalCode =:str2];
List<Contact>querys = new List<Contact>{query1,query2};

*querys can contain duplicate data.

But when we use a single query, the condition we specify will return only those contacts which satisfy both the conditions.
List<Contact> contacts = [SELECT Name FROM Contact WHERE (LastName = :lName AND MailingPostalCode = :mailPostalCode)];

*contacts - will contain unique records.
nagamalli tadikondanagamalli tadikonda
i am getting this excetption

Challenge Not yet complete... here's what's wrong: 
There was an unexpected error in your org which is preventing this assessment check from completing: System.DmlException: Insert failed. First exception on row 0; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, EMAIL ALREADY TAKEN...ENTER NEW ONE: [Email]

please help me out
Ken SeaneyKen Seaney
I am trying to understand this challenge and the logic a bit better.
I played with the code and was able to satisfy the challenge a couple of different ways. I guess what I am not understanding is the string(s) and how they are compared to what is in the SOQL query. 
public class ContactSearch {
    public static List<Contact> searchForContacts(String lastName, String postalCode){
   	return [SELECT Name from Contact WHERE LastName = :lastName
           AND MailingPostalCode = :postalCode];
    
	}    
}
Correct my if I am wrong..the above says: Make a list on Contact with the (string variable 'lastName', and String variable 'postalCode' then return a SOQL query on Contact where the LastName equals the string variable 'lastName' AND the MailingPostalCode equals the string variable 'postalCode'.
What I don't get: are we making a string to satisfy the challenge or is it actually doing something? I don't see where the variable is getting anything from Contact to compare to against the SOQL query.
I am kind of new at this and need to grasp it... an help or input is appreciated!!
Ken

 
Teja M 27Teja M 27
Hello Ken seaney,
the string parameters take input and searches for that in contacts and returns the results. to check that. assign the query to a variable of type List<contact>. and debug that variable.
public class ContactSearch {
    public static List<Contact> searchForContacts(string lastname, string postalCode){
        List<contact> lst = [select id,name from contact where lastName=:lastname AND MailingPostalCode=:postalcode];
         system.debug(lst);
        return lst;
    }
}

open execute anonymous and enter
ContactSearch.searchForContacts('Smith','');

then goto logs and debugonly you will see the result.
James France 10James France 10
Here is what I passed the challenge with:

public class ContactSearch {
    public static List<Contact> searchForContacts(String last, String post) {
        List<Contact> contacts = new List<Contact>();
        contacts = [SELECT ID, Name from Contact
                   where LastName = :last AND MailingPostalCode = :post];
        return contacts;
    }
}
Mario Alberts 3Mario Alberts 3
Hi James,

Where did you use the above code?

Thanks,
Mario
shubham_sonishubham_soni
Perfect Code For Complete Task -
 
public class ContactSearch {
    public static List<Contact> searchForContacts(String a,String b){
    List<Contact> cont = [Select Id,Name FROM Contact Where LastName =: a AND MailingPostalCode =: b ];
        return cont;
    }
}


Then After  open execute anonymous window in Enter Below Code - 
 
List<Contact> listOfContacts = ContactSearch.searchForContacts('Enter a String Value','Enter a String Value');
system.debug('@Developer--> ' + listOfContacts);


 - Shubham Soni
Ben RowleyBen Rowley
public class ContactSearch {

    public static List<Contact> searchForContacts(String firstName, String MailingPostalCode ){
        List<Contact> contacts = [select id,name from Contact where lastName =: firstName and MailingPostalCode =: MailingPostalCode]; 
        return contacts;
    }
}
chetan dabaschetan dabas
Hii Arun,
You can try this one this will work fine.
public class ContactSearch
{
    public static list<contact> searchForContacts(string a,string b)
    {
        list<contact> cntct=[select name,id from contact where lastname=:a and MailingPostalCode=:b];
        return cntct;
    }

}  
Mikhail RzhevskyMikhail Rzhevsky
public class ContactSearch {

    public static List<Contact> searchForContacts(String lastName,String postalCode){
        return [select LastName,MailingPostalCode from Contact
                where LastName = :lastName and MailingPostalCode = :postalCode order by LastName,MailingPostalCode desc];
    }
}
Vedavyas RallabandiVedavyas Rallabandi
Create an Apex class that returns contacts based on incoming parameters.

public class ContactSearch 
    {
    //The method must accept two incoming strings as parameters
    public static list<contact> searchForContact(string last_name, string mail_postalcode){
        
        //It should then find any contact that has a last name matching the first string, 
        //and mailing postal code (API name: MailingPostalCode) matching the second string
     list<contact> cnts = [select name,ID from contact where lastname =: last_name AND MailingPostalCode =: mail_postalcode];                     
        return cnts;
    }
}

But when i click on check challenge, I am getting error,

Executing the 'searchForContacts' method failed. Either the method does not exist, is not static, or does not return the expected contacts.
disharee raydisharee ray
public class ContactSearch {
    public static List<Contact> searchForContacts(String lname, String mPostalCode) {
    List<Contact> l= [SELECT Name FROM Contact 
                         WHERE (LastName=:lname AND MailingPostalCode=:mPostalCode)];     
        System.debug(l);
        return l;
                        
    }
}
asif ali 24asif ali 24
//This code is working properly;
public class ContactSearch{
public static List<Contact> searchForContacts(String asif,String ali){
return [select LastName,MailingPostalCode from Contact order by LastName,MailingPostalCode desc];
}
}
DUGLODUGLO
looking at the answers provided by asif ali 24 and Satyanarayana Pusuluri - they pass the challenge but I don't understand why. They don't check that the contacts returned match the incoming parameters (last name and mailing postal code). Can anyone help me understand why these pass the test?
Ilya IvanovskiyIlya Ivanovskiy
public class ContactSearch {
    public static List<Contact> searchForContacts (String lName, String mailPostalCode){
        List<Contact> cont = [SELECT Name 
                              FROM Contact 
                              WHERE (LastName = :lName AND MailingPostalCode = :mailPostalCode)];
        return cont;      
    }
}
here is the simplest solution to this example, please try
sarvesh nerkarsarvesh nerkar

Hi,

What if in the problem they would not have provided the exact API name 'MailingPostalCode' and rather a general name like 'mailing postal code', then how would have we found out the exact API name? 

(Approach I tried ->  We cannot use * in SELECT queries to get all the names in query SQL results for Contact; Then I navigated to ObjectManager -> Contact to search for 'MailingPostalCode', but it was not present there). 

Venkat DodlaVenkat Dodla
I was not able to pass the exam unitl I removed the __c before MailingPostalCode from my below class. I am suprise how can salesforce allow to pass someone who is receiving null output.
Question for All the above participants who were able to complete the test:
1) Did the field MailingPostalCode exist in your Contact obj which did not exist for me?

2) If the field does not exist, when you created a new field, the api name shows something like MailingPostalCode__c. If so,
with out using the api name, were you able to see the output?

Here is my code by the way,
public class ContactSearch {
    public static List<Contact> searchForContacts(String lName, String pCode){
        List<Contact> cont = [SELECT Id, Name FROM Contact WHERE LastName=:lName AND MailingPostalCode__c=:pCode];
         return cont;
    }
}

Here is my Execute anonymous window code to call/execute the above code,
List<Contact> getList = ContactSearch.searchForContacts('dod','12222-1443');
system.debug('List == '+getList);

Please let me know your opinion. Thanks everyone.
 
Kiranmai PamarthiKiranmai Pamarthi
How to I show list of contacts matched with SIN if its provided/ if sin not provided match agianst last name . here sin not provided is a check box
Sangita07Sangita07

Hi

I also have not found any API name as MailingPostalCode in Contacts. So had to create a new one. But created API name is MailingPostalCode__c and with this I am not able to pass the challenge. I passed the challenge only by removing '__c' but it returned null output. Can someone please expain this?

Baskaran ArumugamBaskaran Arumugam

I got below error when i execute the code

Illegal assignment from List<Contact> to List<contact>

iSaasforceiSaasforce
Hi Mr. chetan dabas
thanks for sharing your knowledge .


Regards
Amar
USoni_SFDevUSoni_SFDev
Best and shortest answer to have :-)
public class ContactSearch {
    public static Contact[] searchForContacts(String str1, String str2) {
        return [SELECT Id, FirstName, LastName FROM Contact WHERE(LastName=:str1 AND MailingPostalCode=:str2)];
    }
}
Rohit GorliRohit Gorli
This works fine for me:)
public class ContactSearch {
    public static List<contact> searchForContacts( String first,String second)
    {
        List<contact> con = [select Name,ID from contact where LastName=:first AND MailingPostalCode=:second];
        return con;
    }
}
 
Sayed Sajid AliSayed Sajid Ali
Try this it works 100%:

public class ContactSearch {
    public static List<Contact> searchForContacts(String lastName, String postalCode){
        Contact[] cont = [SELECT Id, Name FROM Contact
                          WHERE LastName=:lastName AND MailingPostalCode=:postalCode];
        return cont;
    }
}
WaqarAhmedWaqarAhmed
public with sharing class ContactSearch {

    public static List<Contact> searchForContacts(string lname, string mpc) {
        
        List<Contact>myContacts = [SELECT Name from Contact WHERE LastName =: lname AND MailingPostalCode =: mpc];
        
        return myContacts;
    }
}

 
Suraj Tripathi 47Suraj Tripathi 47

HI Arun Chaubey

 I Am Writing a program. please check it and it will help you

public with sharing class conList{

    public static List<Contact> conList1(string name, string mcq) {
        
        List<Contact>Contacts = [SELECT Name from Contact WHERE LastName =: name AND MailingPostalCode =: mcq];
        
        return Contacts ;
    }
}
 

if you resolve your bug. please mark my best Answer.

Thanks  

Suraj Tripathi 

Amol KastureAmol Kasture
public class ContactSearch {

 public static Contact[] searchForContacts(String Lname,String Mailcode)
 {
   Contact[] con = [SELECT ID,Name FROM Contact WHERE LastName=:Lname AND MailingPostalCode=:Mailcode];
   
   System.debug(con.size() + ' contacts returned.');
   return con;
  
   
 }

}
Amol KastureAmol Kasture
if you want to run in Anonymous window, then run it by following way:

String Lname;
String Mailcode;
Contact[] con = [SELECT ID,Name FROM Contact WHERE LastName=:Lname AND MailingPostalCode=:Mailcode];
System.debug(con.size() + ' contacts returned.');
Natalia BannikovaNatalia Bannikova
Hello! It works:

public class ContactSearch{
    public static List<Contact> searchForContacts(String lastname, String Postalcode){
        return [SELECT Name FROM Contact WHERE (LastName=:lastname AND MailingPostalCode=:Postalcode)];
    }
}
Nazli FatimaNazli Fatima
public class ContactSearch {
    public static List<Contact> searchForContacts(string lastname, string Postalcode){
       List<Contact> cont=[SELECT FirstName,LastName, MailingPostalCode 
                           FROM Contact 
                           WHERE LastName=:lastname and MailingPostalCode=:Postalcode ] ;

        return cont;
    }
}
 
austin denzaustin denz

Hi there,
Certainly, I'd be glad to help you understand the question. The task requires creating a public Apex class named 'ContactSearch' with a public static method called 'searchForContacts'. This method takes two strings as input and searches for contacts with a matching last name and mailing postal code. It should return a list of Contact records with at least their ID and Name fields. The method should be designed to fulfill these conditions and return the required Contact records.
Feel free to reach out if you need further assistance!
Best regards. http://postal.com.ng/ibadan-postal-or-zip-codes-oyo-state/
joseph flyerjoseph flyer
Certainly! The task is to create an Apex class named 'ContactSearch' with a public static method 'searchForContacts' that accepts two incoming strings. This method should search for contacts whose last names match the first string and whose mailing postal code matches the second string. It should return a list of Contact records containing at least the ID and Name fields as the return type 'List<Contact>'. If you have any specific questions about implementing this, for more check https://www.geosoft-surtech.com/services/3d-laser-scanning
Fredrick sonjustinFredrick sonjustin
The task requires you to create an Apex class called 'ContactSearch' with a public static method named 'searchForContacts.' This method should take two incoming strings as parameters, where the first string represents a last name and the second string represents a mailing postal code. The method should search for contacts that match these criteria and return a list of Contact records with at least the ID and Name fields. The return type for the 'searchForContacts' method should be 'List<Contact>'. The goal is to implement a search function for contacts based on last name and mailing postal code.dubai movers (https://servicezone.ae/local-movers)