Simple Search Highlighter

Thursday, May 20, 2010 by Aslam - The Alexendra
Hi All,
Recently i faced one issue where i need to use a simple search on some table and fetch the results on screen. But the main problem i faced that how to highlight the search word in the screen in some color format. So here is the solution for that. (It is inspired from one PHP Code blog: http://www.phpro.org/articles/Highlight-Search-Words.html).

For SFDC work around, here is the solution with code:

1) Apex Class:- I used the contact for my searching example. Here is the code:-

public class ContactSearchHighlight{
public string srchArg{get;set;}
public List<Contact> lstcontact {get;set;}
public ContactSearchHighlight(){
lstContact
= [select id, name, details__c from contact where details__c != null];
}

public PageReference search(){
string srchPhrase = '%' + srchArg + '%';
lstContact
= [select id, name, details__c from contact where details__c like :srchPhrase];

for(Contact cnt: lstContact){
cnt.details__c
= highlightPhrase(cnt.details__c, srchArg);
}

return null;
}

public string highlightPhrase(string mainString, string phrase){
mainString
= mainString.toLowerCase().replaceAll(phrase.toLowerCase(), '<span class="highlight_word">' + phrase + '</span>');
return mainString;
}

}





2) VisualForce page and code for Search and highlight

<apex:page controller="ContactSearchHighlight" showHeader="false" sidebar="false">
<apex:sectionHeader title="Search Contacts" subtitle="Highlighter"/>
<style type="text/css">
h1
{
font-size
:16px;
}
.highlight_word
{
background-color
: PaleGreen;
font-weight
:bold;
font-style
:italic;
}
.searchbox
{
border
:1px solid #ccc;
font-family
:verdana;
padding
:10px;
}
.searchbox p
{
text-transform
: capitialize;
}
.hrstyle
{
color
: #f00;
background-color
: #f00;
height
: 1px;
}
</style>
<apex:form>
<apex:inputtext value="{!srchArg}"/>
<apex:commandButton value="Search" action="{!search}"/>
</apex:form><br/>
<div class="searchbox">
<apex:repeat value="{!lstContact}" var="cnt">
<h1>{!cnt.Name}</h1>
<p><apex:outputText value="{!cnt.details__c}" escape="false" />
<div style="text-align:center;color:#ccc;">
-----------------------------------------------
</div>
</p>

</apex:repeat>
</div>
</apex:page>



3) And finally here is the link to check it right now online. Just try to search something like "park", or "usa', or "and"

http://labsprojects-developer-edition.ap1.force.com/ContactSearchHighlight



Is it nice!!!


Thanks
Aslam Bari

3 comments:

meprakashg said...

Yes it is very nice
seems good

Kathy Pink said...

HI
You may be interested in how multi-currency is handled in salesforce. see Accorto's Blog
http://www.accorto.com/_blog/blog/post/Salesforce_Multi-Currency_Expense_Reports/

Unknown said...

I love this!! But I am just getting my toes wet with customization and programming SFDC. Please excuse my ignorance but where would i paste this code in my org?
I am using Ent edition.

Post a Comment