I read How do I find the search block form ID? several days ago. I want to use the answer given there in my project.

Where should I add this code in my project? Where can I find more information about it?

$form =\Drupal::service('class_resolver')-getInstanceFromDefinition('Drupal\mymodule\Form\Mymodule\SearchBlockForm');
return \Drupal::formBuilder()->getForm($form);

The key line of code here is this one:


Can you explain me what the code does?

  • Because drupal is open source, you can see the finding documentation in your IDE.
    – Eyal
    Commented Mar 9, 2017 at 23:37
  • Based on my understanding the first piece of code goes into a custom module. The second bit $form = \Drupal::service('class_resolver')... goes directly into a template. $form->setFormIdentifier('some_custom_value'); is required if you want to override form functionality using hooks based on your need.
    – Ash U
    Commented Mar 10, 2017 at 0:06

1 Answer 1


As per the comments from Jaypan, the first thing to do is extending SearchBlockForm so you can give it a custom ID. Put the code in mymodule/src/Form/MymoduleSearchBlockForm.php.
Add the following code in the custom class (in this case, FoobarblkBlock) to create a custom block. Put the code in mymodule/src/Plugin/Block/FoobarblkBlock.php

 * @file
namespace Drupal\mymodule\Plugin\Block;

use Drupal\Core\Block\BlockBase;

 * Creates a 'Foobar' Block
 * @Block(
 * id = "block_foobarblk",
 * admin_label = @Translation("Foo Bar block"),
 * )
class FoobarblkBlock extends BlockBase {

     * {@inheritdoc}
    public function build() {
      $form = \Drupal::service('class_resolver')->getInstanceFromDefinition('Drupal\mymodule\Form\MymoduleSearchBlockForm');

return \Drupal::formBuilder()->getForm($form);

Place the block in the required region. The resulting form will be:

<form action="/search/node" method="get" id="search-block-form-some-custom-value" accept-charset="UTF-8">

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.