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?