View source
<?php
namespace Drupal\ajax_forms_test\Plugin\Block;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Form\FormBuilderInterface;
use Drupal\Core\Form\FormInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Messenger\MessengerInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class AjaxFormBlock extends BlockBase implements FormInterface, ContainerFactoryPluginInterface {
protected $formBuilder;
protected $messenger;
public function __construct(array $configuration, $plugin_id, $plugin_definition, FormBuilderInterface $form_builder, MessengerInterface $messenger) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->formBuilder = $form_builder;
$this->messenger = $messenger;
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($configuration, $plugin_id, $plugin_definition, $container
->get('form_builder'), $container
->get('messenger'));
}
public function build() {
return $this->formBuilder
->getForm($this);
}
public function getFormId() {
return 'ajax_forms_test_block';
}
public function buildForm(array $form, FormStateInterface $form_state) {
$form['test1'] = [
'#type' => 'select',
'#title' => $this
->t('Test 1'),
'#required' => TRUE,
'#options' => [
'option1' => $this
->t('Option 1'),
'option2' => $this
->t('Option 2'),
],
'#ajax' => [
'callback' => '::updateOptions',
'wrapper' => 'edit-test1-wrapper',
],
'#prefix' => '<div id="edit-test1-wrapper">',
'#suffix' => '</div>',
];
$form['actions'] = [
'#type' => 'actions',
];
$form['actions']['submit'] = [
'#type' => 'submit',
'#value' => $this
->t('Submit'),
];
return $form;
}
public function updateOptions(array $form, FormStateInterface $form_state) {
$form['test1']['#options']['option1'] = $this
->t('Option 1!!!');
$form['test1']['#options'] += [
'option3' => $this
->t('Option 3'),
'option4' => $this
->t('Option 4'),
];
return $form['test1'];
}
public function validateForm(array &$form, FormStateInterface $form_state) {
}
public function submitForm(array &$form, FormStateInterface $form_state) {
$this->messenger
->addStatus('Submission successful.');
}
}