You are here

class WebformEntityElementsForm in Webform 8.5

Same name and namespace in other branches
  1. 6.x src/WebformEntityElementsForm.php \Drupal\webform\WebformEntityElementsForm

Webform manage elements YAML source form.

Hierarchy

Expanded class hierarchy of WebformEntityElementsForm

File

src/WebformEntityElementsForm.php, line 17

Namespace

Drupal\webform
View source
class WebformEntityElementsForm extends BundleEntityFormBase {
  use WebformDialogFormTrait;

  /**
   * The element info manager.
   *
   * @var \Drupal\Core\Render\ElementInfoManagerInterface
   */
  protected $elementInfo;

  /**
   * The webform element manager.
   *
   * @var \Drupal\webform\Plugin\WebformElementManagerInterface
   */
  protected $elementManager;

  /**
   * The webform element validator.
   *
   * @var \Drupal\webform\WebformEntityElementsValidatorInterface
   */
  protected $elementsValidator;

  /**
   * The webform token manager.
   *
   * @var \Drupal\webform\WebformTokenManagerInterface
   */
  protected $tokenManager;

  /**
   * Constructs a WebformEntityElementsForm.
   *
   * @param \Drupal\Core\Render\ElementInfoManagerInterface $element_info
   *   The element manager.
   * @param \Drupal\webform\Plugin\WebformElementManagerInterface $element_manager
   *   The webform element manager.
   * @param \Drupal\webform\WebformEntityElementsValidatorInterface $elements_validator
   *   Webform element validator.
   * @param \Drupal\webform\WebformTokenManagerInterface $token_manager
   *   The webform token manager.
   */
  public function __construct(ElementInfoManagerInterface $element_info, WebformElementManagerInterface $element_manager, WebformEntityElementsValidatorInterface $elements_validator, WebformTokenManagerInterface $token_manager) {
    $this->elementInfo = $element_info;
    $this->elementManager = $element_manager;
    $this->elementsValidator = $elements_validator;
    $this->tokenManager = $token_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('plugin.manager.element_info'), $container
      ->get('plugin.manager.webform.element'), $container
      ->get('webform.elements_validator'), $container
      ->get('webform.token_manager'));
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form = parent::buildForm($form, $form_state);
    return $this
      ->buildDialogForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function form(array $form, FormStateInterface $form_state) {

    /** @var \Drupal\webform\WebformInterface $webform */
    $webform = $this
      ->getEntity();
    $t_args = [
      ':form_api_href' => 'https://www.drupal.org/node/37775',
      ':render_api_href' => 'https://www.drupal.org/developing/api/8/render',
      ':yaml_href' => 'https://en.wikipedia.org/wiki/YAML',
    ];
    $form['elements'] = [
      '#type' => 'webform_codemirror',
      '#mode' => 'yaml',
      '#title' => $this
        ->t('Elements (YAML)'),
      '#description' => $this
        ->t('Enter a <a href=":form_api_href">Form API (FAPI)</a> and/or a <a href=":render_api_href">Render Array</a> as <a href=":yaml_href">YAML</a>.', $t_args) . '<br /><br />' . '<em>' . $this
        ->t('Please note that comments are not supported and will be removed.') . '</em>',
      '#default_value' => $this
        ->getElementsWithoutWebformTypePrefix($webform
        ->get('elements')),
      '#required' => TRUE,
      '#element_validate' => [
        '::validateElementsYaml',
      ],
      '#attributes' => [
        'style' => 'min-height: 300px',
      ],
    ];
    $form['token_tree_link'] = $this->tokenManager
      ->buildTreeElement();
    $this->tokenManager
      ->elementValidate($form);
    return parent::form($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  protected function actions(array $form, FormStateInterface $form_state) {
    $actions = parent::actions($form, $form_state);
    unset($actions['delete']);
    return $actions;
  }

  /**
   * Element validate callback: Add 'webform_' #type prefix to elements.
   */
  public function validateElementsYaml(array &$element, FormStateInterface $form_state) {
    if ($form_state
      ->getErrors()) {
      return;
    }
    $elements = $form_state
      ->getValue('elements');
    $elements = $this
      ->getElementsWithWebformTypePrefix($elements);
    $form_state
      ->setValueForElement($element, $elements);
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    parent::validateForm($form, $form_state);
    if ($form_state
      ->hasAnyErrors()) {
      return;
    }

    /** @var \Drupal\webform\WebformInterface $webform */
    $webform = $this
      ->getEntity();
    $elements = $webform
      ->getElementsDecoded();
    $this
      ->addWebformTypePrefixRecursive($elements);
    $webform
      ->setElements($elements);

    // Validate elements YAML.
    if ($messages = $this->elementsValidator
      ->validate($webform)) {
      $form_state
        ->setErrorByName('elements');
      foreach ($messages as $message) {
        $this
          ->messenger()
          ->addError($message);
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function save(array $form, FormStateInterface $form_state) {

    /** @var \Drupal\webform\WebformInterface $webform */
    $webform = $this
      ->getEntity();
    $webform
      ->save();
    $context = [
      '@label' => $webform
        ->label(),
      'link' => $webform
        ->toLink($this
        ->t('Edit'), 'edit-form')
        ->toString(),
    ];
    $t_args = [
      '%label' => $webform
        ->label(),
    ];
    $this
      ->logger('webform')
      ->notice('Webform @label elements saved.', $context);
    $this
      ->messenger()
      ->addStatus($this
      ->t('Webform %label elements saved.', $t_args));
  }

  /****************************************************************************/

  // Webform type prefix add and remove methods.

  /****************************************************************************/

  /**
   * Get elements without 'webform_' #type prefix.
   *
   * @return string
   *   Elements (YAML) without 'webform_' #type prefix.
   */
  protected function getElementsWithoutWebformTypePrefix($value) {
    $elements = WebformYaml::decode($value);
    if (!is_array($elements)) {
      return $value;
    }
    $this
      ->removeWebformTypePrefixRecursive($elements);
    return WebformYaml::encode($elements);
  }

  /**
   * Remove 'webform_' prefix from #type.
   *
   * @param array $element
   *   A form element.
   */
  protected function removeWebformTypePrefixRecursive(array &$element) {
    if (isset($element['#type']) && strpos($element['#type'], 'webform_') === 0 && $this->elementManager
      ->hasDefinition($element['#type'])) {
      $type = str_replace('webform_', '', $element['#type']);
      if (!$this->elementInfo
        ->hasDefinition($type) && !$this->elementManager
        ->hasDefinition($type)) {
        $element['#type'] = $type;
      }
    }
    foreach (Element::children($element) as $key) {
      if (is_array($element[$key])) {
        $this
          ->removeWebformTypePrefixRecursive($element[$key]);
      }
    }
  }

  /**
   * Get elements with 'webform_' #type prefix.
   *
   * @return string
   *   Elements (YAML) with 'webform_' #type prefix.
   */
  protected function getElementsWithWebformTypePrefix($value) {
    $elements = WebformYaml::decode($value);
    if (!is_array($elements)) {
      return $value;
    }
    $this
      ->addWebformTypePrefixRecursive($elements);
    return WebformYaml::encode($elements);
  }

  /**
   * Remove 'webform_' prefix from #type.
   *
   * @param array $element
   *   A form element.
   */
  protected function addWebformTypePrefixRecursive(array &$element) {
    if (isset($element['#type']) && !$this->elementInfo
      ->hasDefinition($element['#type'])) {
      $type = 'webform_' . $element['#type'];
      if ($this->elementManager
        ->hasDefinition($type)) {
        $element['#type'] = $type;
      }
    }
    foreach (Element::children($element) as $key) {
      if (is_array($element[$key])) {
        $this
          ->addWebformTypePrefixRecursive($element[$key]);
      }
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
BundleEntityFormBase::protectBundleIdElement protected function Protects the bundle entity's ID property's form element against changes.
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
EntityForm::$entity protected property The entity being used by this form. 7
EntityForm::$entityTypeManager protected property The entity type manager. 3
EntityForm::$moduleHandler protected property The module handler service.
EntityForm::$operation protected property The name of the current operation.
EntityForm::$privateEntityManager private property The entity manager.
EntityForm::actionsElement protected function Returns the action form element for the current entity form.
EntityForm::afterBuild public function Form element #after_build callback: Updates the entity with submitted data.
EntityForm::buildEntity public function Builds an updated entity object based upon the submitted form values. Overrides EntityFormInterface::buildEntity 2
EntityForm::copyFormValuesToEntity protected function Copies top-level form values to entity properties 7
EntityForm::getBaseFormId public function Returns a string identifying the base form. Overrides BaseFormIdInterface::getBaseFormId 5
EntityForm::getEntity public function Gets the form entity. Overrides EntityFormInterface::getEntity
EntityForm::getEntityFromRouteMatch public function Determines which entity will be used by this form from a RouteMatch object. Overrides EntityFormInterface::getEntityFromRouteMatch 1
EntityForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId 10
EntityForm::getOperation public function Gets the operation identifying the form. Overrides EntityFormInterface::getOperation
EntityForm::init protected function Initialize the form state and the entity before the first form build. 3
EntityForm::prepareEntity protected function Prepares the entity object before the form is built first. 3
EntityForm::prepareInvokeAll protected function Invokes the specified prepare hook variant.
EntityForm::processForm public function Process callback: assigns weights and hides extra fields.
EntityForm::setEntity public function Sets the form entity. Overrides EntityFormInterface::setEntity
EntityForm::setEntityManager public function Sets the entity manager for this form. Overrides EntityFormInterface::setEntityManager
EntityForm::setEntityTypeManager public function Sets the entity type manager for this form. Overrides EntityFormInterface::setEntityTypeManager
EntityForm::setModuleHandler public function Sets the module handler for this form. Overrides EntityFormInterface::setModuleHandler
EntityForm::setOperation public function Sets the operation for this form. Overrides EntityFormInterface::setOperation
EntityForm::submitForm public function This is the default entity object builder function. It is called before any other submit handler to build the new entity object to be used by the following submit handlers. At this point of the form workflow the entity is validated and the form state… Overrides FormInterface::submitForm 17
EntityForm::__get public function
EntityForm::__set public function
FormBase::$configFactory protected property The config factory. 1
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::config protected function Retrieves a configuration object.
FormBase::configFactory protected function Gets the config factory for this form. 1
FormBase::container private function Returns the service container.
FormBase::currentUser protected function Gets the current user.
FormBase::getRequest protected function Gets the request object.
FormBase::getRouteMatch protected function Gets the route match.
FormBase::logger protected function Gets the logger for a specific channel.
FormBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
FormBase::resetConfigFactory public function Resets the configuration factory.
FormBase::setConfigFactory public function Sets the config factory for this form.
FormBase::setRequestStack public function Sets the request stack object to use.
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.
WebformAjaxFormTrait::announce protected function Queue announcement with Ajax response.
WebformAjaxFormTrait::buildAjaxForm protected function Add Ajax support to a form.
WebformAjaxFormTrait::createAjaxResponse protected function Create an AjaxResponse or WebformAjaxResponse object.
WebformAjaxFormTrait::getAnnouncements protected function Get announcements.
WebformAjaxFormTrait::getDefaultAjaxSettings protected function Get default ajax callback settings. 1
WebformAjaxFormTrait::getFormStateRedirectUrl protected function Get redirect URL from the form's state.
WebformAjaxFormTrait::getWrapperId protected function Get the form's Ajax wrapper id. 1
WebformAjaxFormTrait::isCallableAjaxCallback protected function Determine if Ajax callback is callable.
WebformAjaxFormTrait::isDialog protected function Is the current request for an Ajax modal/dialog.
WebformAjaxFormTrait::isOffCanvasDialog protected function Is the current request for an off canvas dialog.
WebformAjaxFormTrait::missingAjaxCallback protected function Handle missing Ajax callback.
WebformAjaxFormTrait::replaceForm protected function Replace form via an Ajax response. 1
WebformAjaxFormTrait::resetAnnouncements protected function Reset announcements.
WebformAjaxFormTrait::setAnnouncements protected function Set announcements.
WebformAjaxFormTrait::submitAjaxForm public function Submit form #ajax callback. 1
WebformAjaxFormTrait::validateAjaxForm public function Validate form #ajax callback. 1
WebformDialogFormTrait::buildDialogConfirmForm protected function Add modal dialog support to a confirm form.
WebformDialogFormTrait::buildDialogDeleteAction protected function Build webform dialog delete link.
WebformDialogFormTrait::buildDialogForm protected function Add modal dialog support to a form.
WebformDialogFormTrait::cancelAjaxForm public function Cancel form #ajax callback. Overrides WebformAjaxFormTrait::cancelAjaxForm 1
WebformDialogFormTrait::closeDialog public function Close dialog.
WebformDialogFormTrait::isAjax protected function Returns if webform is using Ajax. Overrides WebformAjaxFormTrait::isAjax 1
WebformDialogFormTrait::noSubmit public function Empty submit callback used to only have the submit button to use an #ajax submit callback. Overrides WebformAjaxFormTrait::noSubmit
WebformDialogFormTrait::noValidate public function Validate callback to clear validation errors. 2
WebformEntityElementsForm::$elementInfo protected property The element info manager.
WebformEntityElementsForm::$elementManager protected property The webform element manager.
WebformEntityElementsForm::$elementsValidator protected property The webform element validator.
WebformEntityElementsForm::$tokenManager protected property The webform token manager.
WebformEntityElementsForm::actions protected function Returns an array of supported actions for the current entity form. Overrides EntityForm::actions
WebformEntityElementsForm::addWebformTypePrefixRecursive protected function Remove 'webform_' prefix from #type.
WebformEntityElementsForm::buildForm public function Form constructor. Overrides EntityForm::buildForm
WebformEntityElementsForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
WebformEntityElementsForm::form public function Gets the actual form array to be built. Overrides EntityForm::form
WebformEntityElementsForm::getElementsWithoutWebformTypePrefix protected function Get elements without 'webform_' #type prefix.
WebformEntityElementsForm::getElementsWithWebformTypePrefix protected function Get elements with 'webform_' #type prefix.
WebformEntityElementsForm::removeWebformTypePrefixRecursive protected function Remove 'webform_' prefix from #type.
WebformEntityElementsForm::save public function Form submission handler for the 'save' action. Overrides EntityForm::save
WebformEntityElementsForm::validateElementsYaml public function Element validate callback: Add 'webform_' #type prefix to elements.
WebformEntityElementsForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
WebformEntityElementsForm::__construct public function Constructs a WebformEntityElementsForm.