I'm using the "exposed form in block" option for some of my views. However, I did not manage to render this block using either drupal_block() or drupal_form(). Maybe someone could suggest how to do this? Meanwhile I implemented a new twig tweak function that I named "drupal_exposed_form":

  public function drupalExposedForm($view_name, $display_name) {
    $view = Views::getView($view_name);
    $view->setDisplay($display_name);
    $view->initHandlers();
    $form_state = (new FormState())
      ->setStorage([
       'view' => $view,
       'display' => &$view->display_handler->display,
       'rerender' => TRUE,
      ])
      ->setMethod('get')
      ->setAlwaysProcess()
      ->disableRedirect();
    $form_state->set('rerender', NULL);
    return \Drupal::formBuilder()->buildForm('\Drupal\views\Form\ViewsExposedForm', $form_state);
  }

It will render the exposed filter form using e.g. drupal_exposed_form('my_view', 'block_1').

Comments

meanderix created an issue. See original summary.

Chi’s picture

Status: Active » Closed (works as designed)

The following code works fine for me.

{{ drupal_block('views_exposed_filter_block:content-page_1') }}
{{ drupal_view('content', 'page_1') }}

Note that exposed filters can be rendered in a block only for page display type with enabled ajax option. So that {{ drupal_view('content') }} would not work correctly because default display is used.

See #2681947: Allow 'Put the exposed form in a block' setting to be used with views block displays and #2692297: Allow exposed form for non-ajax block displays for details.

alanyong’s picture

Nope. It's not working. I get this error after I place {{ drupal_block(machine_name) }}

This block is broken or missing. You may be missing content or you might need to enable the original module.

Chi’s picture

@alanyong, probably it is because you provided wrong plugin ID for this function.

HongPong’s picture

alanyong look for id in the url like http://site.com/admin/structure/block/manage/BLOCKID

You may be also be able to dump preprocess hook info from inside the theme to better ID the blocks.

Chi’s picture

@HongPong, drupal_block() accepts block plugin ID, not entity ID. See this guide for details
https://www.drupal.org/docs/8/modules/twig-tweak/rendering-blocks-with-t...

HongPong’s picture

ah thank you chi. i was able to use the technique i mentioned above successfully i think.

Chi’s picture

That way is applicable for Twig tweak 1.x.