6

How can I customize the default search block form template, I now use below template to display a search form block, but this code doesn't allow me to edit and customize each part of this form separately and doesn't have any flexibility.

form--search-block-form.html.twig

<form{{ attributes.addClass('search-form', 'search-block-form') }}>
  {{ children }}
</form>

and then print in my theme by below code:

{{ page.search_box }}

Is there any better template name suggestion with more variables and flexibility in customization?

4
+50

If you want to use Twig, you can do it by creating a custom module, like this:

/themes/your_theme/templates/form--search-block-form.html.twig

{% set form = element %}

hello {{ form.keys }} world {{ form.actions }}

Result:

enter image description here

In Bartik theme:

enter image description here

  • 2
    Not to hijack your answer, but ... if you do want to use twig, is there no other way then via a custom module? Probably a stupid question, but still: in D7 you'd grab an appropriate template (or create one with the correct name), and put it in the right spot. Are you saying that in D8 there's no such thing? If you think this is too much hijacking, just let my know (I'll then copy/paste this comment in a new answer ...). – Pierre.Vriens Aug 24 '16 at 14:56
  • 1
    @Pierre.Vriens Are you saying that in D8 there's no such thing? yes, unfortunately, for forms there isn't a template that you can just grab out of the box. – No Sssweat Aug 24 '16 at 23:07
4

The search block is provided by the core module Search. If you install this module the block will be available in the block layout, when you place a block.

Probably you have already done this by installing the standard profile.

To customize the search form you can use a form alter hook.

For example put this function in mytheme.theme to change the search button:

function mytheme_form_alter(&$form, $form_state) {
  if ( $form['#form_id'] == 'search_block_form' ) {
    $form['actions']['submit']['#value'] = t('Search my Website');
  }
}
  • 1
    Thank you so much for your help and attention, is there any way or method to customize or create a search form in twig template without need to use preprocess function? – Mojtaba Reyhani Aug 11 '16 at 17:48
  • That depends, what is difficult in twig is to target a specific form, like I did in the hook. If you want to change a form element in general, then use the twig of that element. – 4k4 Aug 11 '16 at 18:13
  • 1
    There is nothing like a simple twig solution for a search form element, as far as I know. – 4k4 Aug 11 '16 at 19:54

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.