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
SV MSV M 

Page Reference is not working on vf page

Hi,
I have a requirement where I have a search box in VF Page which displays Contacts based on Search String. If there is only one record matches the string the page should automatically redirect to that Contact record.
I am using Page Reference and Param to get the Id from the Search String. But it's throwing an error says URL is broke.
//Controller
public class SearchContactsController {
    public List<Contact> conList{get;set;}
    public String search {get;set;}
    public String Id{get;set;}
    public PageReference contacts() {
        Id = ApexPages.currentPage().getParameters().get('id');
        conList = [SELECT Id, FirstName, LastName FROM Contact WHERE LastName =:search];
        if(conList.size() == 0) {
            ApexPages.addMessage(new ApexPages.message(ApexPages.Severity.ERROR,'No Records Found'));
        }else {
            if(conList.size() == 1) {
                PageReference pr = new PageReference('/'+Id);
                pr.setRedirect(true);
                return pr;
            }
        }
        return null;
    }
}
//VF Page
<apex:page controller="SearchContactsController">
    <apex:form >
        <apex:pageMessages />
        <apex:pageBlock >
            <apex:inputText value="{!search}" label="Search Contacts"/>
            <apex:commandButton value="Search" action="{!contacts}">
                <!--<apex:param name="id" assignTo="{!search}" value=""/>-->
            </apex:commandButton>
        </apex:pageBlock>
        <apex:pageBlock >
            <apex:pageBlockTable value="{!conList}" var="con">
                <apex:column headerValue="FirstName" value="{!con.FirstName}"/>
                <apex:column headerValue="LastName">
                    <apex:outputLink value="/{!con.Id}">{!con.LastName}
                        <apex:param name="id" assignTo="{!search}" value="{!con.Id}"/>
                    </apex:outputLink>
                </apex:column>
            </apex:pageBlockTable>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Can someone help me with what's wrong with my code. Thanks in Advance...
ANUTEJANUTEJ (Salesforce Developers) 
Hi Sai Vineeth,

Please make sure the URL is proper, try checking in the log if there is any issue with the URL that is being generated.

Let me know if it helps you and close your query by marking it as solved so that it can help others in the future.  

Thanks.