0

I have a LWC component which takes 4 input from the user and fetches the matching records based on the conditions in the query. In the below apex method to fetch records, the parameter 'c' which is a string is to be treated as a wild search. This method and query works fine in the wild character search but just one scenario.

If the input in 'c' parameter, for example is '%%%%'(or any other alpha numeric combination consisting '%') then it returns all the records matching the criteria. What I want is the '%' which comes from input to be treated as a string and not another wild search character in the query.

@AuraEnabled(cacheable=true)
    public static List<ABC> search(String a, String b, String c, String d){
        String query1 = 'Select Id, Name from ABC where ';

        if(string.isNotBlank(a))
        query1 += ' QWE = \''+a+'\' ';

        if(string.isNotBlank(b))
        query1 += ' and RTY = \''+b+'\' ';

        if(string.isNotBlank(c))
        query1 += ' and Name like \''+c+'%\' ';  //**********clause********

        if(string.isNotBlank(d))
        query1+= ' and XYZ = \''+d+'\' ';
        query1+= ' ORDER BY Name ASC';
        List<ABC> tagsList = Database.query(query1);
        return tagsList;

    }

Should this be handled in the LWC somehow or there's a way to handle in apex as well? Minimum of 4 characters will always be there in the string 'c' and removing '%' from the input doesn't sound like a good idea. Please suggest.

1 Answer 1

0

As per the documentation, you simply need to ensure that the value gets escaped.

Nowever, even though you are building the query dynamically I still recommend you use bindings.

For example:

String escapedC = String.isNotBlank(c) ? c.replace('%', '\\%') : null;

if (escapedC != null) {
  query1 += ' AND Name LIKE :escapedC';
}
1
  • Thanks! this works well. Jun 25, 2021 at 9:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.