1

I use search api module and a view of products. If I put the search text block and I do a search, It redirect to an url like this: <my domain>?search_api_fulltext=word1+word2+word3&sort_by=title_1&sort_order=ASC

Where all search words are separated by a plus sign ("+"). I have my custom search block and I want to redirect to the same url in the submit function of the form. This is my code:

public function submitForm(array &$form, FormStateInterface $form_state) {

if (!empty($form_state->getValue('textBox'))) {      
  $text = str_replace(' ', '+', $form_state->getValue('textBox'));
  $option = [
    'query' => ['search_api_fulltext' => $text, 
                'sort_by'=>'search_api_relevance', 
                'sort_order'=>'ASC'],
  ];
  $url = Url::fromUri('internal:/shop', $option);
  $form_state->setRedirectUrl($url);      
}
return;

}

But it redirect to <my domain>?search_api_fulltext=word1%2Bword2&sort_by=title_1&sort_order=ASC, where plus signs are replaced with %2B, and then, the search is incorrect. How could I avoid this replacement?

2
  • I suspect you need to pass an array for multiple values, instead of creating the string as you are. Try changing this $text = str_replace(' ', '+', $form_state->getValue('textBox')); to $text = explode(' ', $form_state->getValue('textBox'));. – Jaypan Jun 4 '20 at 15:16
  • Thanks for your help but It doesn't work. – briast Jun 4 '20 at 15:52
1

The URL you're building is taking the query (e.g. "word1 word2 word3") and replacing it with literal "+" chars for spaces. Hence, the %2B encoding in the string.

You don't need to parse/encode $form_state->getValue('textBox'). Per the documentation of Url::fromUri() for the $options param:

  • 'query': An array of query key/value-pairs (without any URL-encoding) to append to the URL.

$options['query'] expects its key/value pairs to have the literal strings.

You needn't worry about +/%20 encoding differences. They are different ways to encode the space character. (the + is an older space-encoding spec which you can do if absolutely needed, see rawurlencode, urlencode, & http_build_query in the PHP docs).

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.