You are here

class WordfilterConfigurationForm in Wordfilter 8.2

Class WordfilterConfigurationForm.

@package Drupal\wordfilter\Form

Hierarchy

Expanded class hierarchy of WordfilterConfigurationForm

File

src/Form/WordfilterConfigurationForm.php, line 16

Namespace

Drupal\wordfilter\Form
View source
class WordfilterConfigurationForm extends EntityForm {

  /**
   * @return \Drupal\wordfilter\Entity\WordfilterConfigurationInterface
   */
  public function getWordfilterConfiguration() {
    return $this->entity;
  }

  /**
   * Helper function to rebuild the form when necessary.
   *
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   * @param array &$old_form
   *   The old form build.
   * @return array
   *   The newly built form.
   */
  protected function rebuild(FormStateInterface $form_state, &$old_form) {
    $form_state
      ->setRebuild();
    $form_builder = \Drupal::getContainer()
      ->get('form_builder');
    $form = $form_builder
      ->rebuildForm($this
      ->getFormId(), $form_state, $old_form);
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form = parent::buildForm($form, $form_state);
    $form_state
      ->setCached(FALSE);
    $wordfilter_configuration = $this
      ->getWordfilterConfiguration();
    $form['label'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Label'),
      '#maxlength' => 255,
      '#default_value' => $wordfilter_configuration
        ->label(),
      '#description' => $this
        ->t("Label for the Wordfilter configuration."),
      '#required' => TRUE,
      '#weight' => 10,
    ];
    $form['id'] = [
      '#type' => 'machine_name',
      '#default_value' => $wordfilter_configuration
        ->id(),
      '#machine_name' => [
        'exists' => '\\Drupal\\wordfilter\\Entity\\WordfilterConfiguration::load',
      ],
      '#disabled' => !$wordfilter_configuration
        ->isNew(),
      '#weight' => 20,
    ];
    $form['process'] = [
      '#type' => 'fieldset',
      '#title' => t('Filtering process'),
      '#collapsible' => FALSE,
      '#collapsed' => FALSE,
      '#weight' => 30,
    ];

    /**
     * @var \Drupal\wordfilter\Plugin\WordfilterProcessManager
     */
    $plugin_manager = \Drupal::service('plugin.manager.wordfilter_process');
    $definitions = $plugin_manager
      ->getDefinitions();
    $available_plugins = [];
    foreach ($definitions as $id => $definition) {
      $available_plugins[$id] = $definition['label'];
    }
    $form['process']['process_id'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Implementation'),
      '#description' => $this
        ->t('The selected implementation will be used to filter the specified words.'),
      '#options' => $available_plugins,
      '#default_value' => $wordfilter_configuration
        ->get('process_id'),
      '#required' => FALSE,
      '#weight' => 10,
      '#ajax' => [
        'event' => 'change',
        'callback' => [
          $this,
          'wordfilterProcessSettingsAjax',
        ],
        'wrapper' => 'wordfilter-process-settings',
        'progress' => [
          'type' => 'throbber',
          'message' => t('Loading settings...'),
        ],
      ],
    ];
    $this
      ->wordfilterProcessSettings($form, $form_state);
    $items = $wordfilter_configuration
      ->getItems();
    $form['items'] = [
      '#tree' => TRUE,
      '#type' => 'fieldset',
      '#title' => t('Filtering items'),
      '#collapsible' => FALSE,
      '#collapsed' => FALSE,
      '#weight' => 40,
    ];
    foreach ($items as $item) {
      $this
        ->wordfilterItemSettings($form, $form_state, $item);
    }
    $num_items = count($items);
    $form['items']['add_destination'] = [
      '#type' => 'container',
      '#attributes' => [
        'id' => 'wordfilter-item-add-destination',
      ],
      '#weight' => $num_items * 100 - 10,
    ];
    $form['items']['add'] = [
      '#tree' => FALSE,
      '#type' => 'submit',
      '#name' => 'item_add',
      '#value' => t('Add another item'),
      '#weight' => $num_items * 100,
      '#ajax' => [
        'callback' => [
          $this,
          'wordfilterNewItemSettingsAjax',
        ],
        'wrapper' => 'wordfilter-item-add-destination',
        'effect' => 'fade',
        'method' => 'before',
        'progress' => [
          'type' => 'throbber',
          'message' => t('Loading settings...'),
        ],
      ],
      '#submit' => [
        '::wordfilterNewItemSettingsAjax',
      ],
    ];
    return $form;
  }

  /**
   * Form builder for Wordfilter process settings.
   *
   * @see ::buildForm().
   */
  public function wordfilterProcessSettings(array &$form, FormStateInterface $form_state) {
    $wordfilter_config = $this
      ->getWordfilterConfiguration();
    $process_id = $form_state
      ->getValue('process_id');
    if (!isset($process_id)) {
      $process_id = $wordfilter_config
        ->get('process_id');
    }

    /**
     * @var \Drupal\wordfilter\Plugin\WordfilterProcessManager
     */
    $plugin_manager = \Drupal::service('plugin.manager.wordfilter_process');

    /**
     * @var \Drupal\wordfilter\Plugin\WordfilterProcessInterface
     */
    $plugin = $plugin_manager
      ->createInstance($process_id);
    $settings = $plugin
      ->settingsForm($form, $form_state, $wordfilter_config);
    $settings += [
      '#prefix' => '<div id="wordfilter-process-settings">',
      '#suffix' => '</div>',
    ];
    $form['process']['settings'] = $settings;
    $form['process']['settings']['#weight'] = 20;
    return $form['process']['settings'];
  }

  /**
   * Ajax Callback for Wordfilter process settings.
   *
   * @see ::wordfilterProcessSettings().
   */
  public function wordfilterProcessSettingsAjax(array &$form, FormStateInterface $form_state) {
    $this
      ->wordfilterProcessSettings($form, $form_state);
    $form = $this
      ->rebuild($form_state, $form);
    return $form['process']['settings'];
  }

  /**
   * Form builder for settings of a given Filtering item.
   *
   * @see ::buildForm().
   */
  public function wordfilterItemSettings(array &$form, FormStateInterface $form_state, WordfilterItem $item) {
    $count = count($form_state
      ->getValue('items', []));
    if ($count === 0) {
      $count = $form_state
        ->getValue('wordfilter_item_count', 0);
      $count++;
    }
    $form_state
      ->setValue('wordfilter_item_count', $count);
    $delta = $item
      ->getDelta();
    $id = Html::getUniqueId('edit-items-' . $delta);
    $settings = [
      '#type' => 'fieldset',
      '#title' => t('Item #@num', [
        '@num' => $count,
      ]),
      '#collapsible' => FALSE,
      '#collapsed' => FALSE,
      '#weight' => $delta,
      '#attributes' => [
        'id' => $id,
      ],
    ];
    $settings['delta'] = [
      '#type' => 'value',
      '#value' => $delta,
      '#weight' => 10,
    ];
    $settings['substitute'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Substitution text'),
      '#default_value' => $item
        ->getSubstitute(),
      '#description' => $this
        ->t('Any filtered word will be replaced by this substitution text (optional).'),
      '#required' => FALSE,
      '#weight' => 20,
    ];
    $settings['filter_words'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Words to filter'),
      '#default_value' => implode(', ', $item
        ->getFilterWords()),
      '#description' => \Drupal::theme()
        ->render('item_list', [
        'items' => [
          $this
            ->t('Enter a <strong>comma-separated</strong> list of filter words.'),
          $this
            ->t('Example: <em>Somebadword, Another, [placeholder]</em>.'),
        ],
      ]),
      '#required' => FALSE,
      '#weight' => 30,
    ];
    $settings['remove'] = [
      '#type' => 'submit',
      '#name' => 'remove_item_' . $delta,
      '#value' => t('Remove this item'),
      '#ajax' => [
        'callback' => [
          $this,
          'removeWordfilterItemAjax',
        ],
        'wrapper' => $id,
        'effect' => 'fade',
        'progress' => [
          'type' => 'throbber',
          'message' => t('Removing...'),
        ],
      ],
      '#submit' => [
        '::removeWordfilterItemAjax',
      ],
      '#weight' => 40,
    ];
    $form['items'][$delta] = $settings;
    return $form['items'][$delta];
  }

  /**
   * Form builder for settings of a new Filtering item.
   *
   * @see ::buildForm().
   */
  public function wordfilterNewItemSettings(array &$form, FormStateInterface $form_state) {
    $new = $this
      ->getWordfilterConfiguration()
      ->newItem();
    $this
      ->wordfilterItemSettings($form, $form_state, $new);
    $form = $this
      ->rebuild($form_state, $form);
    $delta = $new
      ->getDelta();
    return $form['items'][$delta];
  }

  /**
   * Ajax callback for the settings of a new Filtering item.
   *
   * @see ::wordfilterNewItemSettings().
   */
  public function wordfilterNewItemSettingsAjax(array &$form, FormStateInterface $form_state) {
    $settings = $this
      ->wordfilterNewItemSettings($form, $form_state);
    $delta = $settings['delta']['#value'];
    $form = $this
      ->rebuild($form_state, $form);
    return $form['items'][$delta];
  }

  /**
   * Ajax remove callback.
   *
   * @see ::buildForm().
   */
  public function removeWordfilterItemAjax(array &$form, FormStateInterface $form_state) {
    $trigger = $form_state
      ->getTriggeringElement();
    $delta = $trigger['#parents'][1];
    $wordfilter_config = $this
      ->getWordfilterConfiguration();
    $items = $wordfilter_config
      ->getItems();
    if (!empty($items[$delta])) {
      $wordfilter_config
        ->removeItem($items[$delta]);
    }
    $form = $this
      ->rebuild($form_state, $form);
    drupal_set_message(t('Item will be removed permanently when configuration is saved.'));
    return StatusMessages::renderMessages(NULL);
  }

  /**
   * {@inheritdoc}
   */
  public function save(array $form, FormStateInterface $form_state) {
    $wordfilter_configuration = $this
      ->getWordfilterConfiguration();
    $items = $wordfilter_configuration
      ->getItems();

    // Put submitted data onto the items. It has automatically been populated on
    // the configuration entity's data, but not the configuration items objects.
    foreach ($wordfilter_configuration
      ->get('items') as $delta => $item) {
      $items[$delta]
        ->setSubstitute($item['substitute']);
      $items[$delta]
        ->setFilterWords($item['filter_words']);
    }
    $num_items = count($items);
    if ($num_items > 1) {

      // Remove multiple empty items.
      foreach ($items as $item) {
        if (empty($item
          ->getSubstitute()) && empty($item
          ->getFilterWords())) {
          $wordfilter_configuration
            ->removeItem($item);
        }
      }
    }
    $status = $wordfilter_configuration
      ->save();
    switch ($status) {
      case SAVED_NEW:
        drupal_set_message($this
          ->t('Created the %label Wordfilter configuration.', [
          '%label' => $wordfilter_configuration
            ->label(),
        ]));
        break;
      default:
        drupal_set_message($this
          ->t('Saved the %label Wordfilter configuration.', [
          '%label' => $wordfilter_configuration
            ->label(),
        ]));
    }
    $form_state
      ->setRedirectUrl($wordfilter_configuration
      ->toUrl('collection'));
  }

}

Members

Namesort descending Modifiers Type Description Overrides
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::actions protected function Returns an array of supported actions for the current entity form. 29
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::form public function Gets the actual form array to be built. 30
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::create public static function Instantiates a new instance of this class. Overrides ContainerInjectionInterface::create 87
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.
FormBase::validateForm public function Form validation handler. Overrides FormInterface::validateForm 62
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.
WordfilterConfigurationForm::buildForm public function Form constructor. Overrides EntityForm::buildForm
WordfilterConfigurationForm::getWordfilterConfiguration public function
WordfilterConfigurationForm::rebuild protected function Helper function to rebuild the form when necessary.
WordfilterConfigurationForm::removeWordfilterItemAjax public function Ajax remove callback.
WordfilterConfigurationForm::save public function Form submission handler for the 'save' action. Overrides EntityForm::save
WordfilterConfigurationForm::wordfilterItemSettings public function Form builder for settings of a given Filtering item.
WordfilterConfigurationForm::wordfilterNewItemSettings public function Form builder for settings of a new Filtering item.
WordfilterConfigurationForm::wordfilterNewItemSettingsAjax public function Ajax callback for the settings of a new Filtering item.
WordfilterConfigurationForm::wordfilterProcessSettings public function Form builder for Wordfilter process settings.
WordfilterConfigurationForm::wordfilterProcessSettingsAjax public function Ajax Callback for Wordfilter process settings.