Advertising sustains the DA. Ads are hidden for members. Join today

On this page

Webform Cookbook

How to use options from an external webservice

Last updated on
19 April 2019

To populate webform options from an external webservice you need to create an empty set of webform options by going to /admin/structure/webform/config/options/manage/add 
and then populating these options using hook_webform_options_WEBFORM_OPTIONS_ID_alter().

Here is an example of an empty webform optiond config call 'External Countries' (machine_name: external_countries). The complete config name is webform.webform_options.external_countries.yml

langcode: en
status: true
dependencies: {  }
id: external_countries
label: 'External Countries'
category: ''
likert: false
options: ''

Here is a very simple example of using hook_webform_options_WEBFORM_OPTIONS_ID_alter() to populates the External Countries (external_countries) webform options using an external list of U.S. States in JSON.

/**
 * Implements hook_webform_options_WEBFORM_OPTIONS_ID_alter().
 */
function CUSTOM_MODULE_webform_options_external_countries_alter(array &$options, array &$element) {
  // Load cached options.
  if ($cache = \Drupal::cache()->get('external_countries')) {
    $options = $cache->data;
    return;
  }

  // Get data as associative array from the external webservice.
  $external_countries_url = 'https://gist.githubusercontent.com/mshafrir/2646763/raw/8b0dbb93521f5d6889502305335104218454c2bf/states_hash.json';
  $options = json_decode(file_get_contents($external_countries_url), TRUE);

  // Cache options so that we don't have to make continual requests
  // to the external webservice.
  \Drupal::cache()->set('external_countries', $options);
}

Help improve this page

Page status: No known problems

You can: