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
Darren DoudDarren Doud 

Trailhead Challenge Question Writing SOQL Queries Unit

I am working on a Trailhead Challenge and receive this error when I execute.

User-added image

Create an Apex class that returns contacts based on incoming parameters.

For this challenge, you will need to 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>'.

Here's my code:

User-added image

Can someone assist me? Please.

Thank you,
Darren
Best Answer chosen by Darren Doud
ShotShot
Thats because you are trying to write your code in anonymous window.
In dev console click File - New Apex Class and write there your code.

All Answers

ShotShot
Thats because you are trying to write your code in anonymous window.
In dev console click File - New Apex Class and write there your code.
This was selected as the best answer
Darren DoudDarren Doud
Agh! Your right. I didn't even notice that after I was doing it. Must have been a long day. Thanks.
Mayank Jain 52Mayank Jain 52

public class ContactSearch {
      public static List<Contact>  searchForContacts (string lastname , string Postalcode){
      List<Contact> Contacts = [Select ID,Name from Contact where LastName = :lastname AND MailingPostalCode = :Postalcode ];
        return Contacts;
              }
       }
kuldeep paliwalkuldeep paliwal
public class ContactSearch {
//its dont execute on developer console becose of static keyword try to remove static and run on developer console
    public static List<Contact> searchForContacts(String lastName, String mailingPostalCode) {
        List<Contact> conList = [SELECT Id, Name, LastName, MailingPostalCode
                                 FROM Contact
                                 WHERE LastName = :lastName AND MailingPostalCode = :mailingPostalCode];
        return conList;
    }   
}
Ruchir SinghalRuchir Singhal
Hello All,

I am getting below error

" Executing the 'searchForContacts' method failed. Either the method does not exist, is not static, or does not return the expected contacts."

Below is my code
#############################
public class ContactSearch {

    public static List<Contact> searchForContacts (String lastname, String Postalcode)
    {
        List<Contact> Contacts = [Select ID, Name from Contact where firstname = :lastname AND MailingPostalCode = :Postalcode];
        return Contacts;
        
    }
}

Can you please help me
DineshGuptaDineshGupta
Try this.,. It works..

public class ContactSearch
{
    public static List<Contact> searchForContacts(String Str1, String Str2)
    {
        List<Contact> ContactList = [select ID,Name from Contact where LastName = :Str1 and MailingPostalCode = :Str2];
        return ContactList;
    }
}
Atul Tiwari 4Atul Tiwari 4
Its working fine for me

public class ContactSearch {
    
    Public static List<Contact> searchForContacts (String Lname,String Fname )
    {
        List <Contact> con = [SELECT Id,Name FROM Contact where Lastname=:Lname and MailingPostalCode=:Fname];
        System.debug(con);
        return con;
    }
}
chetan dabaschetan dabas
you can try this one and yes, one more thing, no need to create a new apex class it will show you an error that 
"duplicate value found: <unknown> duplicates value on record with id: <unknown>" .you can simply update in the existing class
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;
    }

}
Mayank BatraMayank Batra
I dont know whats wrong here. 

I used following code in the ContactSearch Apex class :
 
public class ContactSearch {
    public static List<contact> searchForContacts (String firstName, String zipCode) {        
        List<Contact> contacts = [select ID, name from Contact where firstname =:firstName and MailingPostalCode =:zipCode];
        return contacts;
    }
}

I tested this set of code with following code in anonymous window :
 

Contact[] conts = ContactSearch.searchForContacts('Jack', '27215');
System.debug(conts.size());
for(Contact cont : conts){
	system.debug('cont ' + cont.name);    
}


The debug statements work fine in the logs. They get 1 record back and print the name Jack Rogers. But the Trailhead gives following error :

Challenge not yet complete in My Trailhead Playground 1
Executing the 'searchForContacts' method failed. Either the method does not exist, is not static, or does not return the expected contacts.

"My Trailhead Playground 1" is the only trailhead playground we have. Thoughts??

Mayank BatraMayank Batra
Any 'angels' out there?
 
Kaushik MoteKaushik Mote
Hi Mayank, 
Please use LastName instead of FirstName in the query as the criteria mentioned in the assignment is for matching LastName.
This worked fine,

public class ContactSearch 
{
      public static List<Contact> searchForContacts(String LName, String MPcode)
   {
            
       List <Contact> cts =[SELECT Id, Name from Contact
                        where LastName=:LName and MailingPostalCode =:MPcode];
   
    return cts;
      }
}
Priyanka kenchi 9Priyanka kenchi 9
I have an error..please help me.
Error:There was an unexpected error in your org which is preventing this assessment check from completing: System.DmlException: Delete failed. First exception on row 0 with id 0037F00001PzZrgQAF; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, Hey! You are not authorized to perform this action.: []

above is my error and here is my code

public class ContactSearch {
      public static List<Contact>  searchForContacts (string lastname , string MailingPostalcode){
      List<Contact> Contacts = [Select ID,Name from Contact where LastName = :lastname AND MailingPostalCode = :MailingPostalcode ];
        return Contacts;
              }
       }
pease help me out
Dharti ShahDharti Shah
I used following code and worked fine
1. launch > developer console
public class ContactSearch {

    public static List<Contact> searchForContacts (String lname, String postalCode){
       List<Contact> contacts = [SELECT LastName FROM Contact where lastName = :lname AND
      MailingPostalCode = :postalCode] ;
        return contacts;  
    }
}



2. debug > open execute annonymous window

ContactSearch.searchForContacts('your string lastname', 'your postalcode');


 
M UsamaM Usama
Below is my code: 

public class ContactSearch {
    public static List <Contact> searchForContacts (string lastname, string postalcode)
    {
        List <Contact> Con = [SELECT Name,AccountId FROM Contact WHERE Last_Name__c=: lastname AND MailingPostalCode=: postalcode ];
    
    system.debug(Con);
        return Con;
    
        
    }
}

And I get the error:
Executing the 'searchForContacts' method failed. Either the method does not exist, is not static, or does not return the expected contacts.
Kapil GugoriaKapil Gugoria
Hi All,

I am trying to complete the below trailhead challenge 
===========================================================================================
Challenge of Trail head 

Create an Apex class with a method that returns an array (or list) of strings.
Create an Apex class with a method that returns an array (or list) of formatted strings ('Test 0', 'Test 1', ...). The length of the array is determined by an integer parameter.
The Apex class must be called StringArrayTest and be in the public scope
The Apex class must have a public static method called generateStringArray
The generateStringArray method must return an array (or list) of strings
The method must accept an incoming Integer as a parameter, which will be used to determine the number of returned strings
The method must return a string value in the format Test n where n is the index of the current string in the array
=============================================================================================
Below is the code 

public class StringArrayTest {
    
    public static List<string> generateStringArray(Integer length)
    {
        List<string> mydata = new List<String>();
        for (Integer i=0;i<length;i++)
        {
            mydata.add('Test' + i);
        }
        system.debug(mydata);
        return mydata;
    }
    
}
=============================================================================================
   Below is the result 

18:10:45:012 USER_DEBUG [10]|DEBUG|(Test0, Test1, Test2, Test3)
=============================================================================================

but the issue is while completing my challenge  trailhead is giving the error which is ....

''Executing the 'generateStringArray' method failed. Either the method does not exist, is not static, or does not return the proper number of strings.''
SunjivSunjiv
For Contact Search
public class ContactSearch {
    public static Contact[] searchForContacts(String lname, String pCode){
        return [select ID, Name from Contact where LastName=:lname AND MailingPostalCode=:pCode];
    }
}

Regards,
Sanjeev
Sandy D 6Sandy D 6
The only culprit is if any of the following are active on an object, here, “Contact”, then the trailhead challenge is failing…
Workflow rules
Process builder
Flows
Duplicate rules
Matching rules
Trigger


otherwise, the codes written above are absolutely correct and working fine..it just did for me !
Sharukh SKSharukh SK
Challenge not yet complete in My Trailhead Playground 2
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: REQUIRED_FIELD_MISSING, Required fields are missing: [Loan_Amount__c]: [Loan_Amount__c]
Sharukh SKSharukh SK
I am getting above error for this Challenge. What should l do?
 
hit_nishanthit_nishant
public class ContactSearch 
{
    public static List<Contact> searchForContacts(String s1, String s2){
        Contact[] listContacts = [SELECT Account.id, Account.Name FROM Contact WHERE LastName=:s1 AND MailingPostalCode=:s2];
        return listContacts;
    }

}
Ntrial user 9Ntrial user 9
public class ContactSearch {
    public static list<contact> searchForContacts(string lname,string pcode){        
        contact[] cnt = [select Account.Id,Account.Name from Contact 
                         where (Lastname =:lname and MailingPostalCode =:pcode)];
        Contact cntlist = cnt[0];
        String AccntId=cntlist.Account.Id;
        String AccntName=cntlist.Account.Name;
        system.debug('The AccountID '+AccntId+'; The Account Name '+AccntName);
        return cnt;                
    }
}
Vrushabh LengadeVrushabh Lengade
Use colon while comparing since we are using variables from the Apex code (bind),
public class ContactSearch {
    public static List<Contact> searchForContacts(String name, String id_no) {
        Contact[] con = [SELECT Id, Name FROM Contact WHERE (LastName=:name AND MailingPostalCode=:id_no)];
        return con;
         }
}
SUSHIL VERMA 22SUSHIL VERMA 22
public class ContactSearch{
    public static List<Contact> searchForContacts(String FirstName,String ID){
        List<Contact> conList = [SELECT Id,Name FROM Contact WHERE (LastName=:FirstName AND MailingPostalCode=:ID)];
       return conList;
    }
    }
Sameer Macwan 7Sameer Macwan 7
Hello Folks,

This Worked for me I hope it will work for you guys as well.

Follow the steps:

Step 1: Go into the Developer Console > Apex class >ContactSearch

Step 2: Follow the below syntax.

public class ContactSearch {

    public static List<Contact> searchForContacts (String lname, String postalCode){
       List<Contact> contacts = [SELECT LastName FROM Contact where lastName = :lname AND
      MailingPostalCode = :postalCode] ;
        return contacts;  
    }
}

Step 3: For debug execution.

ContactSearch.searchForContacts('lname', 'postalCode');

Example:
ContactSearch.searchForContacts('Forbes', '78767');

Thank you!!!

Sameer Macwan
 
Arya Siddhartha GuptaArya Siddhartha Gupta
public class ContactSearch {
    public static List<Contact> searchForContacts(String a, String b)
    {
        Integer i=0;
        List<Contact> cont=[Select ID,LastName, MailingPostalCode from Contact];
        List<Contact> contlist=new List<Contact>();
        for (Contact con : cont)
        {
            if (con.LastName==a || con.MailingPostalCode==b)
                {
                    contlist.add(con);
                
            	}
         }
        return contlist;             
    }
}
I tried this with For loop 
 
Kurt SavageKurt Savage
Thank you Mayan Jain 52; I had it spot on except I forgot the colons to represent the variables.  I just could not figure out what was throwing the error.