Skip to content

Instantly share code, notes, and snippets.

@lauriii
Created October 12, 2022 11:30
Show Gist options
  • Save lauriii/a8fd4894616d0ad6d6e048948bcc33cf to your computer and use it in GitHub Desktop.
Save lauriii/a8fd4894616d0ad6d6e048948bcc33cf to your computer and use it in GitHub Desktop.
diff --git a/src/Plugin/rest/resource/WebformAutocompleteOptions.php b/src/Plugin/rest/resource/WebformAutocompleteOptions.php
new file mode 100644
index 0000000..09a7cb8
--- /dev/null
+++ b/src/Plugin/rest/resource/WebformAutocompleteOptions.php
@@ -0,0 +1,76 @@
+<?php
+
+namespace Drupal\webform_rest\Plugin\rest\resource;
+
+use Drupal\rest\Plugin\ResourceBase;
+use Drupal\rest\ModifiedResourceResponse;
+use Drupal\webform\Entity\Webform;
+use Drupal\webform\Entity\WebformOptions;
+use Drupal\webform\Utility\WebformOptionsHelper;
+use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
+use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
+
+/**
+ * Creates a resource for retrieving webform elements.
+ *
+ * @RestResource(
+ * id = "webform_rest_autocomplete_options",
+ * label = @Translation("Webform Autocomplete Options"),
+ * uri_paths = {
+ * "canonical" = "/webform_rest/{webform_id}/autocomplete_options/{options_id}"
+ * }
+ * )
+ */
+class WebformAutocompleteOptions extends ResourceBase {
+
+ /**
+ * Responds to GET requests, returns webform autocomplete options.
+ *
+ * @param string $webform_id
+ * Webform ID.
+ * @param string $options_id
+ * Webform options ID.
+ *
+ * @return \Drupal\rest\ResourceResponse
+ * HTTP response object containing webform autocomplete options.
+ *
+ * @throws \Symfony\Component\HttpKernel\Exception\HttpException
+ * Throws HttpException in case of error.
+ */
+ public function get($webform_id, $options_id) {
+ if (empty($webform_id)) {
+ throw new BadRequestHttpException(t("Webform ID wasn't provided"));
+ }
+ if (!$options_id) {
+ throw new BadRequestHttpException(t("Options ID wasn't provided"));
+ }
+
+ $webform = Webform::load($webform_id);
+ $elements = $webform->getElementsInitializedAndFlattened();
+
+ // Ensure that webform contains an autocomplete element using requested
+ // options.
+ $has_access = FALSE;
+ foreach ($elements as $element) {
+ if (isset($element['#autocomplete_items']) && $element['#autocomplete_items'] === $options_id) {
+ $has_access = TRUE;
+ break;
+ }
+ }
+
+ $options_entity = WebformOptions::load($options_id);
+
+ if (!$options_entity || !$has_access) {
+ throw new NotFoundHttpException(t("Can't load autocomplete options."));
+ }
+
+ $options = $options_entity->getOptions();
+ if (empty($options)) {
+ $element = ['#options' => $options_entity->id()];
+ $options = WebformOptions::getElementOptions($element);
+ }
+
+ return new ModifiedResourceResponse(WebformOptionsHelper::convertOptionsToString($options));
+ }
+
+}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment