2

I have created a custom composite element for Webform (6.0) that has a date field and a select field. The idea is when a user picks a date, an API call is made that returns available time slots to make a booking.

I am familiar with how this is normally done in FormBase forms and inspecting form_state to inform build values, but I am stuck here.

class WebformTourAvailabilityComposite extends WebformCompositeBase {

  /**
   * {@inheritdoc}
   */
  public static function getCompositeElements(array $element) {
    $date_format_entity = DateFormat::load('html_date');
    $date_format = $date_format_entity->getPattern();

    $elements = [];

    $elements['tour_date'] = [
      '#type' => 'date',
      '#title' => t("Tour Date"),
      '#date_date_format' => $date_format,
      '#date_year_range' => '0:15',
      '#attributes' => [
        'min' => '[webform_submission:created:html_date]',
        'onkeydown' => 'return false'
      ],
      #'#datepicker' => TRUE,
      '#datepicker_button' => TRUE,
      '#date_label_position' => 'invisible',
      '#required' => TRUE,
      '#ajax' => [
        'callback' => 'mymodule_get_date_options',
        'wrapper' => 'available-times'
      ]
    ];

    $elements['tour_time'] = [
      '#type' => 'select',
      '#title' => t('Tour time'),
      '#prefix' => '<div id="available-times">',
      '#suffix' => '</div>',
      #'#options' => [],
    ];

    return $elements;
  }

}

in mymodule.module:

function mymodule_webform_submission_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  $selected = $form_state->getValues();

  if (isset($selected["select_appointment"]["tour_date"])) {
    $response = \Drupal::httpClient()->get('https://nestiolistings.com/api/v2/appointments/group/123/available-times');
    $options = json_decode($response->getBody()->getContents(), TRUE);
    #$form["elements"]["step_1"]["select_appointment"]["tour_time"]["#options"] = $options['data'];
    $form["elements"]["step_1"]["select_appointment"]["#webform_composite_elements"]["tour_time"]["#options"] = $options['data'];
  }
}

function mymodule_get_date_options(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  return $form;
}

Which method I should override or use in the Webform ecosystem, or if this needs to be a composite at all and I can do this some other way?

0

Turns out I was pretty close, an external module was causing interference while authenticated (was getting a post max size exceeded error when submitting the form) on the front end. Unrelated to Webform.

You can add ajax to composite elements and react to them in afterBuild like so (or in your own custom form elements, added to the composite):

class WebformTourAvailabilityComposite extends WebformCompositeBase {

  /**
   * {@inheritdoc}
   */
  public static function getCompositeElements(array $element) {
    $date_format_entity = DateFormat::load('html_date');
    $date_format = $date_format_entity->getPattern();

    $elements = [];

    $elements['tour_date'] = [
      '#type' => 'date',
      '#title' => t("Tour Date"),
      '#date_date_format' => $date_format,
      '#date_year_range' => '0:15',
      '#attributes' => [
        'min' => '[webform_submission:created:html_date]',
        'onkeydown' => 'return false'
      ],
      '#datepicker_button' => TRUE,
      '#date_label_position' => 'invisible',
      '#required' => TRUE,
      '#ajax' => [
        'callback' => ['\Drupal\mymodule\Element', 'refreshTimes'],
        'wrapper' => 'available-times'
      ],
      '#prefix' => '<div id="available-times">',
    ];

    $elements['tour_time'] = [
      '#type' => 'select',
      '#title' => t('Tour time'),
      '#suffix' => '</div>',
      '#after_build' => [[get_called_class(), 'afterBuild']],
      '#validated' => TRUE,
    ];

    return $elements;
  }

  public static function refreshTimes($form, FormStateInterface $form_state) {
    return $form['elements']['tour_time'];
  }

  /**
   * Performs the after_build callback.
   */
  public static function afterBuild(array $element, FormStateInterface $form_state) {
    $client = \Drupal::service('mymodule.client');
    $selected = $form_state->getValues();

    if (isset($selected['tour_date']) && strlen($selected['tour_date'])) {
      $times = $client->getAvailableTourTimes($selected["tour_date"]);
      $element['#options'] = count($times) ? $times : ['' => '- Select -'];
      $element['#description'] = count($times) ? '' : 'There were no available times found for the date you selected. Please choose another date.';
    }

    return $element;
  }

}

Note that your form keys will vary depending on your form, what you name fields, etc. On afterBuild, in this case, if the date picker has a value submitted, it will call a remote API and replace the options in the select with values.

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.