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
SFDC ADM 7SFDC ADM 7 

how to check name in object from vosualforce page

Hi,
I am very new to salesforce
I have two inputtext on visualforce page and a search button
I have one custom object as Object1__c.
When I click on search button I want to check first name and last name in Object1__c. If it exists then it should display details.
If it is not exists, I want to display error message.
How can I do this?
Please help me

Thanks in Advance
Ashish Agarwal 31Ashish Agarwal 31
Hi SFDC ADM 7,

You can refer the code below and see if it works for you.

Visualforce Code : 
<apex:page controller="SearchNameController">
    <apex:pageMessages id="pageMessage"/>
    <apex:form >
        <apex:pageBlock >
            <apex:pageBlockSection id="searchSection">
                <apex:inputText value="{!strFirstName}" label="Enter First Name : "/>
                <apex:inputText value="{!strLastName }" label="Enter Last Name : "/>
                <apex:commandButton value="Search" action="{!searchName}" reRender="pageMessage,resultSection" oncomplete="return false;"/>
            </apex:pageBlockSection>
            <apex:outputPanel id="resultSection">
                <apex:pageBlockSection rendered="{! objObject1 != null }">
                    <apex:outputText value="{!objObject1.FirstName}"/>
                    <apex:outputText value="{!objObject1.LastName}"/>
                </apex:pageBlockSection>
            </apex:outputPanel>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Controller Code : 
public with sharing class SearchNameController {
    public static String strFirstName { get; set; } 
    public static String strLastName { get; set; }
    public static Contact objObject1 { get; set; }
    
    public static void searchName() {
        if( String.isnotBlank( strFirstName ) && String.isNotBlank( strLastName ) ) {
            list<Object1__c> lstObject1s = [ SELECT Id
                                               , FirstName__c
                                               , LastName__c
                                            FROM Object1__c
                                           WHERE FirstName__c = :strFirstName 
                                             AND LastName__c = :strLastName ];
            if( lstObject1s != null && !lstObject1s.isEmpty() ) {
                objObject1= lstObject1s[0];  
            }
            else {
                ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.error,'No match found'));
            }
        }
        else {
            ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.info,'Please enter First and Last Name'));
        }
    }
}