You are here

class TagSetForm in Extensible BBCode 4.0.x

Same name and namespace in other branches
  1. 8.3 src/Form/TagSetForm.php \Drupal\xbbcode\Form\TagSetForm

Base form for tag sets.

Hierarchy

Expanded class hierarchy of TagSetForm

File

src/Form/TagSetForm.php, line 20

Namespace

Drupal\xbbcode\Form
View source
class TagSetForm extends EntityForm {
  use LabeledFormTrait;

  /**
   * The entity storage.
   *
   * @var \Drupal\Core\Entity\EntityStorageInterface
   */
  protected $tagStorage;

  /**
   * The format storage.
   *
   * @var \Drupal\Core\Entity\EntityStorageInterface
   */
  protected $formatStorage;

  /**
   * The tag plugin manager.
   *
   * @var \Drupal\xbbcode\TagPluginManager
   */
  protected $pluginManager;

  /**
   * Constructs a new FilterFormatFormBase.
   *
   * @param \Drupal\Core\Entity\EntityStorageInterface $tagStorage
   *   The entity storage.
   * @param \Drupal\Core\Entity\EntityStorageInterface $formatStorage
   *   The format storage.
   * @param \Drupal\xbbcode\TagPluginManager $pluginManager
   *   The tag plugin manager.
   */
  public function __construct(EntityStorageInterface $tagStorage, EntityStorageInterface $formatStorage, TagPluginManager $pluginManager) {
    $this->tagStorage = $tagStorage;
    $this->formatStorage = $formatStorage;
    $this->pluginManager = $pluginManager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) : self {
    $typeManager = $container
      ->get('entity_type.manager');
    return new static($typeManager
      ->getStorage('xbbcode_tag_set'), $typeManager
      ->getStorage('filter_format'), $container
      ->get('plugin.manager.xbbcode'));
  }

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

    // Begin by creating a table with checkboxes for each plugin.
    $form['_tags'] = [
      '#type' => 'tableselect',
      '#title' => $this
        ->t('Tags'),
      '#header' => [
        'name' => $this
          ->t('Tag name'),
        'label' => $this
          ->t('Plugin'),
      ],
      '#options' => [],
      '#empty' => $this
        ->t('No custom tags or plugins are available.'),
    ];

    /** @var \Drupal\xbbcode\Entity\TagSetInterface $tagSet */
    $tagSet = $this->entity;
    $plugins = new TagPluginCollection($this->pluginManager, $tagSet
      ->getTags());
    $available = $this->pluginManager
      ->getDefinedIds();
    $settings = [];

    // Add the fields for the activated plugins, keyed by current tag name.
    // (This is because the same plugin might be active with multiple names.)
    foreach ($plugins as $name => $plugin) {

      /** @var \Drupal\xbbcode\Plugin\TagPluginInterface $plugin */
      $settings["enabled:{$name}"] = $this
        ->buildRow($plugin, TRUE);
      $form['_tags']['#default_value']["enabled:{$name}"] = TRUE;

      // Exclude already enabled plugins from the bottom part of the table.
      unset($available[$plugin
        ->getPluginId()]);
    }

    // Add the fields for the available plugins, keyed by plugin ID.
    // (This is because multiple plugins might use the same default tag name.)
    foreach ($available as $plugin_id) {

      /** @var \Drupal\xbbcode\Plugin\TagPluginInterface $plugin */
      try {
        $plugin = $this->pluginManager
          ->createInstance($plugin_id);
        $settings["available:{$plugin_id}"] = $this
          ->buildRow($plugin, FALSE);
      } catch (PluginException $exception) {

        // If the plugin is broken, log it and don't show it.
        watchdog_exception('xbbcode', $exception);
      }
    }

    // Add placeholders in the tableselect.
    foreach ($settings as $key => $row) {
      foreach ((array) $row as $name => $cell) {
        $form['_tags']['#options'][$key][$name]['data'] = $name;
      }
    }

    // Put the settings forms into a virtual _settings subkey.
    $form['_settings'] = $settings;
    $form['_settings']['#tree'] = TRUE;

    // Move the settings from there into the tableselect rows when rendering.
    $form['#pre_render'][] = static function (array $form) : array {
      $table =& $form['_tags'];
      $settings = $form['_settings'];
      foreach (Element::children($settings) as $key) {
        foreach ((array) $settings[$key] as $name => $cell) {
          $table['#options'][$key][$name]['data'] = $cell;
        }
      }
      unset($form['_settings']);
      return $form;
    };
    $formats = $this->formatStorage
      ->getQuery()
      ->condition('filters.xbbcode.status', TRUE)
      ->execute();
    if ($formats) {
      $form['formats'] = [
        '#type' => 'checkboxes',
        '#title' => $this
          ->t('Text formats'),
        '#description' => $this
          ->t('Text formats that use this tag set.'),
        '#options' => [],
      ];
      foreach ($this->formatStorage
        ->loadMultiple($formats) as $id => $format) {
        $form['formats']['#options'][$id] = $format
          ->label();
      }
      if (!$this->entity
        ->isNew()) {
        $form['formats']['#default_value'] = $this->formatStorage
          ->getQuery()
          ->condition('filters.xbbcode.settings.tags', $this->entity
          ->id())
          ->execute();
      }
    }
    return parent::form($form, $form_state);
  }

  /**
   * Determines if the tag already exists.
   *
   * @param string $id
   *   The tag set ID.
   *
   * @return bool
   *   TRUE if the tag set exists, FALSE otherwise.
   */
  public function exists(string $id) : bool {
    return (bool) $this->tagStorage
      ->getQuery()
      ->condition('id', $id)
      ->execute();
  }

  /**
   * Build a table row for a single plugin.
   *
   * @param \Drupal\xbbcode\Plugin\TagPluginInterface $plugin
   *   The plugin instance.
   * @param bool $enabled
   *   Whether or not the plugin is currently enabled.
   *
   * @return array
   *   A form array to put into the parent table.
   */
  protected function buildRow(TagPluginInterface $plugin, bool $enabled) : array {
    $row = [
      '#enabled' => $enabled,
      '#default_name' => $plugin
        ->getDefaultName(),
    ];
    $path = $enabled ? 'enabled:' . $plugin
      ->getName() : 'available:' . $plugin
      ->getPluginId();
    $row['name'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Tag name'),
      '#title_display' => 'invisible',
      '#required' => TRUE,
      '#size' => 8,
      '#field_prefix' => '[',
      '#field_suffix' => ']',
      '#default_value' => $plugin
        ->getName(),
      '#pattern' => '[a-z0-9_-]+',
      '#attributes' => [
        'default' => $plugin
          ->getDefaultName(),
      ],
      '#states' => [
        'enabled' => [
          ':input[name="_tags[' . $path . ']"]' => [
            'checked' => TRUE,
          ],
        ],
      ],
    ];
    $row['label'] = [
      '#type' => 'inline_template',
      '#template' => '<strong>{{ plugin.label }}</strong><br />{{ plugin.description}}',
      '#context' => [
        'plugin' => $plugin,
      ],
    ];
    $row['id'] = [
      '#type' => 'value',
      '#value' => $plugin
        ->getPluginId(),
    ];
    return $row;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) : void {
    parent::validateForm($form, $form_state);
    $exists = [];
    $enabled = array_filter($form_state
      ->getValue('_tags'));
    $settings =& $form_state
      ->getValue('_settings');
    foreach (array_keys($enabled) as $key) {
      $name = $settings[$key]['name'];
      $exists[$name][$key] = $form['_settings'][$key]['name'];
    }
    foreach ($exists as $name => $rows) {
      if (count($rows) > 1) {
        foreach ((array) $rows as $row) {
          $form_state
            ->setError($row, $this
            ->t('The name [@tag] is used by multiple tags.', [
            '@tag' => $name,
          ]));
        }
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  protected function copyFormValuesToEntity(EntityInterface $entity, array $form, FormStateInterface $form_state) : void {
    parent::copyFormValuesToEntity($entity, $form, $form_state);
    $enabled = array_keys(array_filter($form_state
      ->getValue('_tags')));
    $settings =& $form_state
      ->getValue('_settings');
    $tags = [];
    foreach ($enabled as $key) {
      $row = $settings[$key];
      $tags[$row['name']] = $this
        ->buildPluginConfiguration($row);
    }

    /** @var \Drupal\Core\Config\Entity\ConfigEntityInterface $entity */
    $entity
      ->set('tags', $tags);
  }

  /**
   * Build a plugin configuration item from form values.
   *
   * @param array $values
   *   The form values.
   *
   * @return array
   *   The new plugin configuration.
   */
  protected function buildPluginConfiguration(array $values) : array {
    return [
      'id' => $values['id'],
    ];
  }

  /**
   * {@inheritdoc}
   *
   * @throws \Drupal\Core\Entity\EntityMalformedException
   * @throws \Drupal\Core\Entity\Exception\UndefinedLinkTemplateException
   * @throws \Drupal\Core\Entity\EntityStorageException
   */
  public function save(array $form, FormStateInterface $form_state) : int {
    $result = parent::save($form, $form_state);
    $old = $form['formats']['#default_value'];
    $new = array_filter($form_state
      ->getValue('formats'));
    $update = [
      '' => array_diff_assoc($old, $new),
      $this->entity
        ->id() => array_diff_assoc($new, $old),
    ];
    foreach ($update as $tag_set => $formats) {

      /** @var \Drupal\filter\FilterFormatInterface $format */
      foreach ($this->formatStorage
        ->loadMultiple($formats) as $id => $format) {
        $filter = $format
          ->filters('xbbcode');
        $config = $filter
          ->getConfiguration();
        $config['settings']['tags'] = $tag_set;
        $filter
          ->setConfiguration($config);
        $format
          ->save();
      }
    }
    if ($result === SAVED_NEW) {
      $this
        ->messenger()
        ->addStatus($this
        ->t('The BBCode tag set %set has been created.', [
        '%set' => $this->entity
          ->label(),
      ]));
    }
    elseif ($result === SAVED_UPDATED) {
      $this
        ->messenger()
        ->addStatus($this
        ->t('The BBCode tag set %set has been updated.', [
        '%set' => $this->entity
          ->label(),
      ]));
    }
    $form_state
      ->setRedirectUrl($this->entity
      ->toUrl('collection'));
    return $result;
  }

  /**
   * {@inheritdoc}
   */
  public function getEntity() : EntityInterface {
    $entity = parent::getEntity();
    assert($entity instanceof EntityInterface);
    return $entity;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property
DependencySerializationTrait::$_serviceIds protected property
DependencySerializationTrait::__sleep public function 2
DependencySerializationTrait::__wakeup public function 2
EntityForm::$entity protected property The entity being used by this form. 11
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::actions protected function Returns an array of supported actions for the current entity form. 35
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 3
EntityForm::buildForm public function Form constructor. Overrides FormInterface::buildForm 13
EntityForm::getBaseFormId public function Returns a string identifying the base form. Overrides BaseFormIdInterface::getBaseFormId 6
EntityForm::getEntityFromRouteMatch public function Determines which entity will be used by this form from a RouteMatch object. Overrides EntityFormInterface::getEntityFromRouteMatch 3
EntityForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId 12
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::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 20
FormBase::$configFactory protected property The config factory. 3
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. 3
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.
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.
LabeledFormTrait::addLabelFields public function Add label fields to the form array.
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. 27
MessengerTrait::messenger public function Gets the messenger. 27
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. 4
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.
TagSetForm::$formatStorage protected property The format storage.
TagSetForm::$pluginManager protected property The tag plugin manager.
TagSetForm::$tagStorage protected property The entity storage.
TagSetForm::buildPluginConfiguration protected function Build a plugin configuration item from form values.
TagSetForm::buildRow protected function Build a table row for a single plugin.
TagSetForm::copyFormValuesToEntity protected function Copies top-level form values to entity properties. Overrides EntityForm::copyFormValuesToEntity
TagSetForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
TagSetForm::exists public function Determines if the tag already exists.
TagSetForm::form public function Gets the actual form array to be built. Overrides EntityForm::form
TagSetForm::getEntity public function Gets the form entity. Overrides LabeledFormTrait::getEntity
TagSetForm::save public function Overrides EntityForm::save
TagSetForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
TagSetForm::__construct public function Constructs a new FilterFormatFormBase.