0

Drupal seems to be removing all text prior to an underscore in my form. This is in the Form.php file of my module implementing Google CSE, so I cannot change the attribute name.

if (array_key_exists('search_broadness', $get_results) && $get_results['search_broadness'] == 'narrow') {
  $block .= 'data-as_sitesearch="' . $gcse_narrow_search_query . '"';
}
$form['search']['results'] = array(
  '#type' => 'item',
  '#markup' => $block,
  '#allowed_tags' => ['script', 'div'],
)

And this is the output, note that the data-as_sitesearch is shortened to sitesearch.

<div class="gcse-searchresults-only" sitesearch="https://www.example.com/drupal8_gcse/"></div>

The Drupal Google CSE module does not have this feature, so I cannot use that. #markup in Drupal 7 worked to get around this, but not in Drupal 8. Is there a workaround to bypass this sanitation?

  • What adds those attributes? – Kevin Dec 19 '18 at 16:44
  • It is a part of the Google Custom Search API, see Google CSE Elements – user Dec 19 '18 at 16:47
  • It's pretty insecure (make sure you don't do this if you have user-submitted input being rendered in the markup), but using an inline_template would probably work – Clive Dec 19 '18 at 16:49
  • No I mean, what part of the render path inside of Drupal is adding those attributes? – Kevin Dec 19 '18 at 16:49
  • $form = \Drupal::formBuilder()->getForm('Drupal\cse_selector\Form\ResultsForm'); I think this is what you mean, It is in my module's Controller.php – user Dec 19 '18 at 16:50
0

I'm struggling to understand what that code is trying to do; I'm assuming your end goal is to render either this:

<div class="gcse-searchresults-only"></div>

Or this, if the condition passes:

<div class="gcse-searchresults-only" data-as_sitesearch="https://www.example.com/drupal8_gcse/"></div>

But I don't see how the code sample would ever to get to even the result in your question. There's no mention of a <div>, and if $block contains the opening <div..., then you've forgotten to close the opening tag and provide a closing tag after concat'ing the attribute string.

To make the whole thing easier (and a bit cleaner), you can use html_tag instead:

$form['search']['results'] = [
  '#type' => 'html_tag',
  '#tag' => 'div',
  '#attributes' => ['class' => ['gcse-searchresults-only']],
  '#value' => '',
];

if (array_key_exists('search_broadness', $get_results) && $get_results['search_broadness'] == 'narrow') {
  $form['search']['results']['#attributes']['data-as_sitesearch'] = $gcse_narrow_search_query;
}
  • I isolated only the lines that I was having trouble with, sorry for any confusion, the div tags have other attributes that were unrelated to this question. Thanks for the solution. – user Dec 19 '18 at 21:52

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.