Assign an action to a simple button I am trying to render a simple button with a submission handler. I tried two  methods, and this is the code I used.

First method

mymodule.module

function mymodule_entity_view_alter(array &amp;$build, EntityInterface $entity, EntityViewDisplayInterface $display) {
  $type = $entity-&gt;bundle();
  if ($type == "property") {
    $build['#attached']['library'][] = 'mymodule/custom_styling';
    $build['mymodule_btn'] = [
      '#type' =&gt; 'submit',
      '#value' =&gt; 'Generate PDF',
      '#submit' =&gt; ['mymodule_generate_pdf'],
      '#weight' =&gt; -1,
    ];
   }
}

function mymodule_generate_pdf() {
  // ...
}


Second method

mymodule.module

function mymodule_entity_view_alter(array &amp;$build, EntityInterface $entity, EntityViewDisplayInterface $display) {
  $type = $entity-&gt;bundle();
  if ($type == "property") {
    $build['#attached']['library'][] = 'mymodule/custom_styling';
     return \Drupal::formBuilder()-&gt;getForm(Drupal\MyModule\Form\MyModuleForm::class);
  }
}


MyModuleForm.php

namespace Drupal\MyModule\Form;

use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\HttpFoundation\Request;

/**
 * Generate the button.
 */
class MyModuleForm extends ConfigFormBase {

  /**
   * {@inheritdoc}.
   */
  public function getFormId() {
    return 'mymodule_form';
  }

  /**
   * {@inheritdoc}.
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['mymodule_btn'] = [
      '#type' =&gt; 'submit',
      '#value' =&gt; 'Generate PDF',
      //'#submit' =&gt; ['mymodule_pdf_generate_pdf'],
      '#weight' =&gt; -1,
    ];

    return $form;
  }

  /**
   * {@inheritdoc}.
   */
  public function validateForm(array &amp;$form, FormStateInterface $form_state) {
    // ...
  }

  /**
   * {@inheritdoc}.
   */
  public function submitForm(array &amp;$form, FormStateInterface $form_state) {
    // ...
    \Drupal::formBuilder()-&gt;submitForm('mymodule_form', $form_state);
  }

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
  }
}


The first method generates the button, but the submission handler is not executed. The second method doesn't even generate the button.

How can I fix the code I wrote?
In Method 2 you want to add the form as an element in the $build array.

Should be something like this:

$build['my_form'] = \Drupal::formBuilder()-&gt;getForm(Drupal\myModule\Form\myModuleForm::class);


Also you don't need to return anything, $build is passed by reference, so anything you add to it will stick.