1

How do I handle apostrophes when using apex:inputtext component to set the value of a search?

Some searches indicate string.escapeSingleQuotes(searchString); or {!JSENCODE(!searchString)} would resolve but I am confused on appropriate usage.

Example of Component:

<apex:page controller="myClass" showHeader="true">
    <apex:inputText id="searchString" value="{!searchString}" onkeypress="return noenter(event);"/>
</apex:page>

Example of Controller:

public class myClass {
    Public string searchString{get;set;}
}

Error Received:

EX: Searching O'Doole = unexpected token: 'Doole'

This variable is used to set another variable in myClass:

if(searchType == 'lastNameSearch') {
    searchWhere = 'client_Last_Name  = \'' + searchString + '\'';
    searchLastName = true;
    }
1

1 Answer 1

2

If you use variable binding, you don't do anything special at all; the system does it for you.

<apex:page controller="myClass" showHeader="true">
    <apex:inputText id="searchString" value="{!searchString}" onkeypress="return noenter(event);"/>
</apex:page>

public class myClass {
    Public string searchString{get;set;}
    public void doSearch() {
        List<List<SObject>> results = [FIND :searchString RETURNING Account, Contact];
    }
}

When using Dynamic SOQL/SOSL, use String.escapeSingleQuotes or bind to the parameter using a colon. I prefer the latter, because it's easier to read.


Binding

if(searchType == 'lastNameSearch') {
  searchWhere = 'Client_Last_Name__c = :searchString';
  searchLastName = true;
}

Escaping

if(searchType == 'lastNameSearch') {
  searchWhere = 'Client_Last_Name__c = \''+ String.escapeSingleQuotes(searchString)+'\'';
  searchLastName = true;
}
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .