1

I am using an autocomplete component in my VF page. And the Problem is when i am hovering / Selecting the record names with Special characters, the Input text box is displaying Encoded Record name as Shown below Screenshot. Please Anyone suggest me the solution to Decode the text using jquery.

Autoselect / Hover

<apex:component controller="autoCompleteController">

var j$ = jQuery.noConflict();

j$(document).ready(function() 

{

    var sObjects;

    var queryTerm;

    j$(esc('{!autocomplete_textbox}')).autocomplete({

        minLength: 1,

        source: function(request, response) {

                    queryTerm = request.term;

                    autoCompleteController.findSObjects("{!objectname}", request.term, "{!additionalfield}", "{!profilename}", function(result, event){

                        if(event.type == 'exception') 

                        {

                              alert(event.message);

                        } else 

                        {

                             sObjects = result;

                             response(sObjects);

                        }

                    });

               },

        focus: function( event, ui ) {

                j$(esc('{!autocomplete_textbox}')).val( ui.item.Name );

                return false;

                },

        select: function( event, ui ) {

                    j$(esc('{!autocomplete_textbox}')).val( ui.item.Name );

                    j$(esc('{!autocomplete_textbox}_lkid')).val( ui.item.Id );

                    j$(esc('{!autocomplete_textbox}_lkold')).val( ui.item.Name );

                    if (event.keyCode == 13) { 

                        event.preventDefault();

                    }

                    return false;

                },

     })

     .data( "autocomplete" )._renderItem = function( ul, item ) {

        var entry = item.Name;

        if("{!additionalfield}" !='')

        {

            j$.each("{!additionalfield}".split(",") , function(key, value) {

                entry = entry + " " + item[value];

            });

        }

        //entry = entry + "</a>";

        //entry = entry.replace(queryTerm, "<b>" + queryTerm + "</b>");

        entry = entry.replace( new RegExp( "(" + queryTerm + ")" , "gi" ), "<strong>$1</strong>" );

        return j$( "<li></li>" )

            .data( "item.autocomplete", item )

            .append( "<a>" + entry + "</a>")

            .appendTo( ul );

    };

});

function esc(myid) 

{

       return '#' + myid.replace(/(:|\.)/g,'\\\\$1');

}

Controller for Component

    global class autoCompleteController 
    {
    @RemoteAction
    global static SObject[] findSObjects(string obj, string qry, string addFields, string profilename) 
    {
    //More than one field can be passed in the addFields parameter Split it into an array for later use 
    List<String> fieldList=new List<String>();
    if (addFields != '')  
    fieldList = addFields.split(',');

    //Check whether the object passed is valid 
    Map<String, Schema.SObjectType> gd = Schema.getGlobalDescribe();
    Schema.SObjectType sot = gd.get(obj);
    if (sot == null) 
    {
        return null;
    }

    // Creating the filter text 
    String filter = ' like \'%' + String.escapeSingleQuotes(qry) + '%\'';

    //Begin building the dynamic soql query 
    String soql = 'SELECT Name';

    // If any additional field was passed, adding it to the soql 
    if (fieldList.size()>0) 
    {
        for (String s : fieldList) 
        {
            soql += ', ' + s;
        }
    }

    // Adding the object and filter by name to the soql 
    soql += ' from ' + obj + ' where name' + filter;

    if(profilename!='')
    {
        //profile name and the System Administrator are allowed
        soql += ' and Profile.Name like \'%' + String.escapeSingleQuotes(profilename) + '%\'';
        system.debug('Profile:'+profilename+' and SOQL:'+soql);
    }

    // Adding the filter for additional fields to the soql 
    if (fieldList != null) 
    {
        for (String s : fieldList) 
        {
            soql += ' or ' + s + filter;
        }
    }

    soql += ' order by Name limit 20';

    system.debug('Qry: '+soql);

    List<sObject> L = new List<sObject>();
    try 
    {
        L = Database.query(soql);
    }
    catch (QueryException e) 
    {
        system.debug('Query Exception:'+e.getMessage());
        return null;
    }
    return L;
    }
    }
4
  • please post your code that populates the options as it will all depend on how you are doing that I would assume you are using HTMLEncode of some sort?. Always wanted to say I was a TATA Developer, lol, although here in the US it has a completely different meaning!
    – Eric
    Aug 6, 2015 at 13:56
  • The code I posted below works (only difference is what I am returning). Did you try adding escape: false to the javascript remoting?
    – Eric
    Aug 6, 2015 at 17:23
  • @Eric Hi Eric, Thank you so much for your Kind reply. I have also posted my class for Component. It seems like my component is differen from your Component. Since I am Using SOQL query in my component, I am confused to adopt your component, I will replace it wit your code. If It is Impossible for my component. Please have a look at Class also. sugest me where I am wrong
    – SFDC_Igle
    Aug 6, 2015 at 17:24
  • You can replace my SOSL with your SOQL and modify as needed..The biggest difference is the return type, I am returning a class where you are returning an object. Also note the differences in my JS .data( 'ui-autocomplete' ) part. I do not recall which actually resolved the issue (I was having same) but it works like it is...My select function is also different and I do not use the esc function
    – Eric
    Aug 6, 2015 at 17:29

1 Answer 1

3

Try setting escape = false. If that does not work see below for working example.

So I am using the same autocomplete and here is my code. The & displays properly. I do not know what you have in your remote action / class so this will get you in the right direction:

Remote Action

    @RemoteAction
    public static search_results[] findSObjects(string objList, string qry, string addFields) {
        // more than one field can be passed in the addFields parameter
        // split it into an array for later use
        List<String> fieldList;
        if (addFields != null) fieldList = addFields.split(',');
       // check to see if the object passed is valid
        Map<String, Schema.SObjectType> gd = Schema.getGlobalDescribe();

        String[] objs = objList.split(',');
        String retClause = 'Returning ';
        for(integer x=0;x<objs.size();x++){
            retClause += x == 0 ? objs[x] : (', ' + objs[x]);
            retClause += '(Name Where Name like \'%' + String.escapeSingleQuotes(qry) + '%\'  order by Name limit 20)';
            if (gd.get(objs[x]) == null) {
                // Object name not valid
                return null;
            }
        }
        String soql = 'FIND \'' + qry + '*\' IN ALL FIELDS ' + retClause;//'select id, Name';

        List<sObject[]> L = new List<sObject[]>();
        try {
            L = search.query(soql);
        }
        catch (QueryException e) {
            system.debug(logginglevel.error, e);
            return null;
        }

        search_results[] results = New search_results[]{};

        for(sObject[] o : L){
            for(sObject r : o){
                results.add(New search_results(r.getsObjectType() + ': ' + r.get('name'),r.id));
            }
        }


        return results;
   }

Class Being Returned

public class search_results{
    public String label;
    public String value;

    public search_results(String l, String v){
        label = l;
        value = v;
    }
}

Javascript

    $('.srchobj').autocomplete({

        minLength: 3,
        source: function(request, response) {
                    queryTerm = request.term;
                    var obj = this.element.attr('autocomplete-object');
                    $('#inviteeID').removeAttr('value');

                    theController.findSObjects(obj, request.term, null, function(result, event){
                        if(event.type == 'exception') {
                              alert(event.message);
                        } else {
                             response(result);
                        }

                    });
               },
            select: function( event, ui ) {
                        $(this).val( ui.item.label );
                        return false;
                    }
     }).data( 'ui-autocomplete' )._renderItem = function( ul, item ) {
        var regex = new RegExp('(' + queryTerm + ')', 'gi');
        var entry = '<a>' + item.label;
        entry = entry + '</a>';
        entry = entry.replace(regex, '<b>$1</b>');
        return $( '<li></li>' )
            .data( 'ui-autocomplete-item', item )
            .append( entry )
            .appendTo( ul );
    };          
});
1
  • Thanks Eric, It worked for "Escape false " as you said earlier, In My JavaScript(Jq) autoCompleteController.findSObjects("{!objectname}", request.term, "{!additionalfield}", "{!profilename}", function(result, event){ ...........................}, {Escape : false } ); "
    – SFDC_Igle
    Aug 9, 2015 at 12:46

You must log in to answer this question.

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