View source
<?php
namespace Drupal\form_api_example\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
class BuildDemo extends FormBase {
protected static $sequenceCounter = 0;
public function __construct() {
$this
->displayMethodInvocation('__construct');
}
private function displayMethodInvocation($method_name) {
self::$sequenceCounter++;
$this
->messenger()
->addMessage(self::$sequenceCounter . ". {$method_name}");
}
public function buildForm(array $form, FormStateInterface $form_state) {
$form['description'] = [
'#type' => 'item',
'#markup' => $this
->t('Demonstrates how submit, rebuild, form-rebuild and #ajax submit work.'),
];
$form['change'] = [
'#type' => 'checkbox',
'#title' => $this
->t('Change Me'),
'#ajax' => [
'callback' => '::ajaxSubmit',
'wrapper' => 'message-wrapper',
],
];
$form['actions'] = [
'#type' => 'actions',
];
$form['actions']['submit'] = [
'#type' => 'submit',
'#value' => 'Submit',
];
$form['actions']['button'] = [
'#type' => 'button',
'#value' => 'Rebuild',
];
$form['actions']['rebuild'] = [
'#type' => 'submit',
'#value' => 'Submit Rebuild',
'#submit' => [
'::rebuildFormSubmit',
],
];
$form['actions']['ajaxsubmit'] = [
'#type' => 'submit',
'#value' => 'Ajax Submit',
'#ajax' => [
'callback' => '::ajaxSubmit',
'wrapper' => 'message-wrapper',
],
];
$form['messages'] = [
'#type' => 'container',
'#attributes' => [
'id' => 'message-wrapper',
],
];
return $form;
}
public function getFormId() {
$this
->displayMethodInvocation('getFormId');
return 'form_api_example_build_form';
}
public function validateForm(array &$form, FormStateInterface $form_state) {
$this
->displayMethodInvocation('validateForm');
}
public function submitForm(array &$form, FormStateInterface $form_state) {
$this
->displayMethodInvocation('submitForm');
}
public function ajaxSubmit(array &$form, FormStateInterface $form_state) {
$this
->displayMethodInvocation('ajaxSubmit');
$form['messages']['status'] = [
'#type' => 'status_messages',
];
return $form['messages'];
}
public function rebuildFormSubmit(array &$form, FormStateInterface $form_state) {
$this
->displayMethodInvocation('rebuildFormSubmit');
$form_state
->setRebuild(TRUE);
}
}