如何使用Drupal 8以编程方式在自定义块中呈现自定义表单?

时间:2018-10-06 15:13:34

标签: drupal-8

我需要以编程方式在自定义块中呈现自定义表单。这是我在控制器内的代码:

  $form = \Drupal::formBuilder()->getForm('Drupal\wa_encuesta\Form\NewForm', $extra);
[enter image description here][1]  $form=render($form);

  $blockContent = BlockContent::create([
    'info' => $title,
    'type' => 'basic',
    'body'=>[
      'value' => $form,
      'format' => 'full_html'
    ]
  ]);
  $blockContent->save();

 //$block = Block::create([
 $block =  \Drupal\block\Entity\Block::create([
   'id' => 'about_us',
   'plugin' => 'block_content:' . $blockContent->uuid(),
   'region' => 'header',
   'provider' => 'block_content',
   'weight' => -100,
   'theme' => \Drupal::config('system.theme')->get('default'),
   'visibility' => array(),
   'settings' => [
     'label' => 'About us',
     'label_display' => FALSE,
   ],
 ]);
 $block->save();

该表单呈现自定义块,但在提交时不起作用。

enter image description here

2 个答案:

答案 0 :(得分:1)

我通常通过将hook_preprocess_block或hook_preprocess_node与树枝文件结合在一起来完成此操作。

示例: 假设您要在一个块中进行渲染: 在主题文件中定义hook_preprocess_block():

function THEME_preprocess_block(&$variables) {
  $blockId = $variables['elements'][#id];
  //check for your block id
  $render_service = Drupal::service('renderer');
  $form_html = $render_service->renderPlain(Drupal\wa_encuesta\Form\NewForm::class, $extra);
  //set in variables
  $variables['my_form_html'] = $form_html;
}

现在,为块标识您的树枝文件名称,然后输入:

{{ my_form_html }}

答案 1 :(得分:0)

请在此处查看我对同一问题的回答:How to create a form using block module in drupal 8?

基本上,您只需要创建一个单独的表单和一个块,然后将表单呈现在块中,然后将其放置在所需的区域即可。