Support for Drupal 7 is ending on 5 January 2025—it’s time to migrate to Drupal 10! Learn about the many benefits of Drupal 10 and find migration tools in our resource center.
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
Comment #2
Chi CreditAttribution: Chi commentedThe following code works fine for me.
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.
Comment #3
alanyong CreditAttribution: alanyong commentedNope. 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.
Comment #4
Chi CreditAttribution: Chi commented@alanyong, probably it is because you provided wrong plugin ID for this function.
Comment #5
HongPong CreditAttribution: HongPong as a volunteer and at kor group commentedalanyong 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.
Comment #6
Chi CreditAttribution: Chi commented@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...
Comment #7
HongPong CreditAttribution: HongPong as a volunteer and at kor group commentedah thank you chi. i was able to use the technique i mentioned above successfully i think.
Comment #8
Chi CreditAttribution: Chi commentedThat way is applicable for Twig tweak 1.x.