Skip to content

Instantly share code, notes, and snippets.

@daggerhart
Last active March 1, 2023 00:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save daggerhart/37863638ed56ad73786474884290db1c to your computer and use it in GitHub Desktop.
Save daggerhart/37863638ed56ad73786474884290db1c to your computer and use it in GitHub Desktop.
Drupal 9, Webform 6 - custom element w/ ajax in form
<?php
namespace Drupal\ocf_integration_webform\Plugin\WebformElement;
use Drupal\Core\Form\FormStateInterface;
use Drupal\webform\Element\WebformAjaxElementTrait;
use Drupal\webform\Plugin\WebformElementBase;
use Symfony\Component\HttpFoundation\Request;
/**
* @WebformElement(
* id = "ajax_form_test",
* label = @Translation("Ajax form test"),
* description = @Translation("Provides a form element for a choosing an Open Collective event ticket."),
* category = @Translation("Options elements"),
* )
*/
class AjaxInWebformElement extends WebformElementBase {
use WebformAjaxElementTrait;
protected function defineDefaultProperties() {
return [
'field_1' => '',
'field_2' => [],
] + parent::defineDefaultProperties();
}
public function form(array $form, FormStateInterface $form_state) {
$form = parent::form($form, $form_state);
$form['field_1'] = [
'#type' => 'select',
'#title' => $this->t('Field 1'),
"#validated" => TRUE,
'#options' => [
'one' => 'One',
'two' => 'Two'
],
// When the event_id changes, update the options field values.
'#ajax' => [
'callback' => '\Drupal\ocf_integration_webform\Plugin\WebformElement\AjaxInWebformElement::ajaxCheckboxes',
'disable-refocus' => TRUE,
'event' => 'change',
'wrapper' => 'field_2_wrapper',
'progress' => [
'type' => 'throbber',
'message' => t('Verifying entry...'),
],
],
];
$form['field_2'] = [
'#type' => 'checkboxes',
'#title' => $this->t('Field 2'),
'#options' => [
'check_one' => 'Check One',
'check_two' => 'Check Two',
],
'#prefix' => '<div id="field_2_wrapper">',
'#suffix' => '</div>',
];
return $form;
}
/**
* Ajax callback.
*/
public static function ajaxCheckboxes(array &$form, FormStateInterface $form_state, Request $request) {
$form['field_2'] = [
'#type' => 'checkboxes',
'#title' => t('Field 2 - Changed'),
'#options' => [
'check_three' => 'Check Three - changed',
'check_found' => 'Check Four - changed',
],
'#prefix' => '<div id="field_2_wrapper">',
'#suffix' => '</div>',
];
return $form['field_2'];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment