You are here

class ConfigContentTypes in Allow a content type only once (Only One) 8

Class ConfigContentTypes.

Hierarchy

Expanded class hierarchy of ConfigContentTypes

1 string reference to 'ConfigContentTypes'
onlyone.routing.yml in ./onlyone.routing.yml
onlyone.routing.yml

File

src/Form/ConfigContentTypes.php, line 17

Namespace

Drupal\onlyone\Form
View source
class ConfigContentTypes extends ConfigFormBase {

  /**
   * The event dispatcher.
   *
   * @var \Symfony\Component\EventDispatcher\EventDispatcherInterface
   */
  protected $eventDispacher;

  /**
   * The onlyone service.
   *
   * @var \Drupal\onlyone\OnlyOneInterface
   */
  protected $onlyone;

  /**
   * Constructor.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The factory for configuration objects.
   * @param \Symfony\Component\EventDispatcher\EventDispatcherInterface $event_dispacher
   *   The event dispacher.
   * @param \Drupal\onlyone\OnlyOneInterface $onlyone
   *   The onlyone service.
   */
  public function __construct(ConfigFactoryInterface $config_factory, EventDispatcherInterface $event_dispacher, OnlyOneInterface $onlyone) {
    parent::__construct($config_factory);
    $this->eventDispacher = $event_dispacher;
    $this->onlyone = $onlyone;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('config.factory'), $container
      ->get('event_dispatcher'), $container
      ->get('onlyone'));
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'onlyone_config_content_types';
  }

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    return [
      'onlyone.settings',
    ];
  }

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

    // Getting the available content types.
    $available_content_types = $this->onlyone
      ->getAvailableContentTypesForPrint();

    // Getting the number of content types.
    $cant_available_content_types = count($available_content_types);
    if ($cant_available_content_types) {

      // The details form element with the available content types.
      $form['available_content_type'] = [
        '#type' => 'details',
        '#title' => $this
          ->t("Content types available to have Only One content"),
        '#open' => TRUE,
      ];

      // All the available content types.
      $form['available_content_type']['onlyone_node_types'] = [
        '#type' => 'checkboxes',
        '#title' => $this
          ->t('Configure these content types to have Only One content per language:'),
        '#options' => $available_content_types,
        '#default_value' => $this
          ->config('onlyone.settings')
          ->get('onlyone_node_types'),
        '#description' => $this
          ->t('The selected content types will allow Only One content per language.'),
      ];
    }

    // Getting the non-available content types.
    $not_available_content_types = $this->onlyone
      ->getNotAvailableContentTypesForPrint();

    // Getting the number of not availables content types.
    $cant_not_available_content_types = count($not_available_content_types);

    // If all the content types are available we don't need to show the element.
    if ($cant_not_available_content_types) {
      $collapsed = $cant_available_content_types ? FALSE : TRUE;

      // The details form element with the unavailable content types.
      $form['not_available_content_type'] = [
        '#type' => 'details',
        '#title' => $this
          ->t('Content types not available to have Only One content per language'),
        '#description' => $this
          ->t('Content types which have more than one content in at least one language:'),
        '#open' => $collapsed,
        '#attributes' => [
          'class' => [
            'details-description--not-available-content-types',
          ],
        ],
      ];

      // Showing all the not availables content types.
      foreach ($not_available_content_types as $key => $value) {
        $form['not_available_content_type'][$key] = [
          '#type' => 'item',
          '#markup' => $value,
        ];
      }

      // Attaching the css file.
      $form['#attached']['library'] = [
        'onlyone/admin_settings',
      ];
    }
    if (!$cant_available_content_types && !$cant_not_available_content_types) {
      $form['not_available_content_type'] = [
        '#markup' => $this
          ->t('There are not content types on this site, go to the <a href=":add-content-type">Add content type</a> page to create one.', [
          ':add-content-type' => Url::fromRoute('node.type_add')
            ->toString(),
        ]),
      ];
    }

    // Show the submit button if there is availables content types.
    if ($cant_available_content_types) {
      return parent::buildForm($form, $form_state);
    }
    else {
      $form = parent::buildForm($form, $form_state);
      unset($form['actions']);
      return $form;
    }
  }

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

    // Cleaning the not checked content types from the selected checkboxes.
    $content_types_checked = array_filter($form_state
      ->getValue('onlyone_node_types'));

    // Getting the configured content types.
    $onlyone_content_types = $this
      ->config('onlyone.settings')
      ->get('onlyone_node_types');

    // Checking if we have any change in the configured content types.
    if ($content_types_checked == array_values($onlyone_content_types)) {
      $this
        ->messenger()
        ->addWarning($this
        ->t("You don't have changed the configured content types."));
    }
    else {

      // Saving the configuration.
      $this
        ->config('onlyone.settings')
        ->set('onlyone_node_types', $content_types_checked)
        ->save();

      // Calling parent method.
      parent::submitForm($form, $form_state);

      // Dispatching the event related to a change in the configured content
      // types.
      $this->eventDispacher
        ->dispatch(OnlyOneEvents::CONTENT_TYPES_UPDATED);
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ConfigContentTypes::$eventDispacher protected property The event dispatcher.
ConfigContentTypes::$onlyone protected property The onlyone service.
ConfigContentTypes::buildForm public function Form constructor. Overrides ConfigFormBase::buildForm
ConfigContentTypes::create public static function Instantiates a new instance of this class. Overrides ConfigFormBase::create
ConfigContentTypes::getEditableConfigNames protected function Gets the configuration names that will be editable. Overrides ConfigFormBaseTrait::getEditableConfigNames
ConfigContentTypes::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
ConfigContentTypes::submitForm public function Form submission handler. Overrides ConfigFormBase::submitForm
ConfigContentTypes::__construct public function Constructor. Overrides ConfigFormBase::__construct
ConfigFormBaseTrait::config protected function Retrieves a configuration object.
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
FormBase::$configFactory protected property The config factory. 1
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
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.
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.