You are here

class GoogleAnalyticsCounterConfigureTypesForm in Google Analytics Counter 8.3

The form for editing content types with the custom google analytics counter field.

@internal

Hierarchy

Expanded class hierarchy of GoogleAnalyticsCounterConfigureTypesForm

1 string reference to 'GoogleAnalyticsCounterConfigureTypesForm'
google_analytics_counter.routing.yml in ./google_analytics_counter.routing.yml
google_analytics_counter.routing.yml

File

src/Form/GoogleAnalyticsCounterConfigureTypesForm.php, line 18

Namespace

Drupal\google_analytics_counter\Form
View source
class GoogleAnalyticsCounterConfigureTypesForm extends ConfigFormBase {

  /**
   * Config Factory Service Object.
   *
   * @var \Drupal\Core\Config\ConfigFactoryInterface
   */
  protected $configFactory;

  /**
   * The Messenger service.
   *
   * @var \Drupal\Core\Messenger\MessengerInterface
   */
  protected $messenger;

  /**
   * Drupal\google_analytics_counter\GoogleAnalyticsCounterAppManagerInterface.
   *
   * @var \Drupal\google_analytics_counter\GoogleAnalyticsCounterAppManagerInterface
   */
  protected $appManager;

  /**
   * Drupal\google_analytics_counter\GoogleAnalyticsCounterCustomFieldGeneratorInterface.
   *
   * @var \Drupal\google_analytics_counter\GoogleAnalyticsCounterCustomFieldGeneratorInterface
   */
  protected $customField;

  /**
   * {@inheritdoc}
   */
  public function __construct(ConfigFactoryInterface $config_factory, MessengerInterface $messenger, GoogleAnalyticsCounterAppManagerInterface $app_manager, GoogleAnalyticsCounterCustomFieldGeneratorInterface $custom_field) {
    parent::__construct($config_factory);
    $this->configFactory = $config_factory;
    $this->messenger = $messenger;
    $this->appManager = $app_manager;
    $this->customField = $custom_field;
  }

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

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

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, $options = NULL) {
    $config = $this
      ->config('google_analytics_counter.settings');

    // Add a checkbox to determine whether the storage for the custom field should be removed.
    $form['gac_custom_field_storage_status'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Custom field storage information'),
      '#open' => TRUE,
    ];
    $form['gac_custom_field_storage_status']['gac_type_remove_storage'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Remove the custom field'),
      '#description' => $this
        ->t('Removes the custom Google Analytics Counter field from the system completely.'),
      '#default_value' => $config
        ->get("general_settings.gac_type_remove_storage"),
    ];

    // Add a checkbox field for each content type.
    $form['gac_content_types'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Content types'),
      '#description' => $this
        ->t('Check the content types to add the custom Google Analytics Counter field to.'),
      '#open' => TRUE,
    ];
    $content_types = \Drupal::service('entity.manager')
      ->getStorage('node_type')
      ->loadMultiple();
    foreach ($content_types as $machine_name => $content_type) {
      $form['gac_content_types']["gac_type_{$machine_name}"] = [
        '#type' => 'checkbox',
        '#title' => $content_type
          ->label(),
        '#default_value' => $config
          ->get("general_settings.gac_type_{$machine_name}"),
        '#states' => [
          'disabled' => [
            ':input[name="gac_type_remove_storage"]' => [
              'checked' => TRUE,
            ],
          ],
        ],
      ];
    }
    return parent::buildForm($form, $form_state);
  }

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

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $config = $this
      ->config('google_analytics_counter.settings');
    $config_factory = $this
      ->configFactory();
    $values = $form_state
      ->cleanValues()
      ->getValues();

    // Save the remove_storage configuration.
    $config
      ->set('general_settings.gac_type_remove_storage', $values['gac_type_remove_storage'])
      ->save();

    // Loop through each content type. Add/subtract the custom field or do nothing.
    foreach ($values as $key => $value) {
      if ($key == 'gac_type_remove_storage') {
        continue;
      }

      // Get the NodeTypeInterface $type from gac_type_{content_type}.
      $type = \Drupal::service('entity.manager')
        ->getStorage('node_type')
        ->load(substr($key, 9));

      // Add the field if the field has been checked.
      if ($values['gac_type_remove_storage'] == FALSE && $value == 1) {
        $this->customField
          ->gacPreAddField($type, $key, $value);
      }
      else {
        if ($values['gac_type_remove_storage'] == FALSE && $value == 0) {
          $this->customField
            ->gacPreDeleteField($type, $key);

          // Update the gac_type_{content_type} configuration.
          $config_factory
            ->getEditable('google_analytics_counter.settings')
            ->set("general_settings.{$key}", NULL)
            ->save();
        }
        else {

          // Delete the field.
          if ($values['gac_type_remove_storage'] == TRUE) {

            // Delete the field.
            $this->customField
              ->gacPreDeleteField($type, $key);

            // Delete the field storage.
            $this->customField
              ->gacDeleteFieldStorage();

            // Set all the gac_type_{content_type} to NULL.
            $this->customField
              ->gacChangeConfigToNull();
          }
        }
      }
    }
    parent::submitForm($form, $form_state);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
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::$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.
GoogleAnalyticsCounterConfigureTypesForm::$appManager protected property Drupal\google_analytics_counter\GoogleAnalyticsCounterAppManagerInterface.
GoogleAnalyticsCounterConfigureTypesForm::$configFactory protected property Config Factory Service Object. Overrides FormBase::$configFactory
GoogleAnalyticsCounterConfigureTypesForm::$customField protected property Drupal\google_analytics_counter\GoogleAnalyticsCounterCustomFieldGeneratorInterface.
GoogleAnalyticsCounterConfigureTypesForm::$messenger protected property The Messenger service. Overrides MessengerTrait::$messenger
GoogleAnalyticsCounterConfigureTypesForm::buildForm public function Form constructor. Overrides ConfigFormBase::buildForm
GoogleAnalyticsCounterConfigureTypesForm::create public static function Instantiates a new instance of this class. Overrides ConfigFormBase::create
GoogleAnalyticsCounterConfigureTypesForm::getEditableConfigNames protected function Gets the configuration names that will be editable. Overrides ConfigFormBaseTrait::getEditableConfigNames
GoogleAnalyticsCounterConfigureTypesForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
GoogleAnalyticsCounterConfigureTypesForm::submitForm public function Form submission handler. Overrides ConfigFormBase::submitForm
GoogleAnalyticsCounterConfigureTypesForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
GoogleAnalyticsCounterConfigureTypesForm::__construct public function Constructs a \Drupal\system\ConfigFormBase object. Overrides ConfigFormBase::__construct
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 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.