julian0018
julian0018

Reputation: 33

How to render custom form inside a custom block programmatically with drupal 8?

I need render a custom form in a custom block programmatically. This is my code inside a controller:

  $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();

The form render a custom block but this not working when submit.

enter image description here

Upvotes: 1

Views: 5533

Answers (2)

Frank Drebin
Frank Drebin

Reputation: 1083

please see my answer to the same question here: How to create a form using block module in drupal 8?

Basically you just create a separate form and a block, render the form in the block and then place the block in the desired region.

Upvotes: 0

Gorav Singal
Gorav Singal

Reputation: 538

I usually get this done by combination of hook_preprocess_block or hook_preprocess_node and twig file.

Example: Say, you want to render this in a block: Define hook_preprocess_block() in your theme file:

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;
}

Now, identify your twig file name for your block, and just put:

{{ my_form_html }}

Upvotes: 1

Related Questions