0

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 &$build, EntityInterface $entity, EntityViewDisplayInterface $display) {
  $type = $entity->bundle();
  if ($type == "property") {
    $build['#attached']['library'][] = 'mymodule/custom_styling';
    $build['mymodule_btn'] = [
      '#type' => 'submit',
      '#value' => 'Generate PDF',
      '#submit' => ['mymodule_generate_pdf'],
      '#weight' => -1,
    ];
   }
}

function mymodule_generate_pdf() {
  // ...
}

Second method

mymodule.module

function mymodule_entity_view_alter(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display) {
  $type = $entity->bundle();
  if ($type == "property") {
    $build['#attached']['library'][] = 'mymodule/custom_styling';
     return \Drupal::formBuilder()->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' => 'submit',
      '#value' => 'Generate PDF',
      //'#submit' => ['mymodule_pdf_generate_pdf'],
      '#weight' => -1,
    ];

    return $form;
  }

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

  /**
   * {@inheritdoc}.
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    // ...
    \Drupal::formBuilder()->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?

0

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()->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.

  • It works beautifully, but now my question is: how I can pass $entity so that I can use the entity's properties? – Kartagis Jun 12 '18 at 13:32
  • 1
    @Kartagis – Please ask a new question instead of broadening this one. – leymannx Jun 21 '18 at 10:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.