You are here

class AmpAnalyticsSettingsForm in Accelerated Mobile Pages (AMP) 8.3

Defines the configuration export form.

Hierarchy

Expanded class hierarchy of AmpAnalyticsSettingsForm

1 string reference to 'AmpAnalyticsSettingsForm'
amp.routing.yml in ./amp.routing.yml
amp.routing.yml

File

src/Form/AmpAnalyticsSettingsForm.php, line 12

Namespace

Drupal\amp\Form
View source
class AmpAnalyticsSettingsForm extends ConfigFormBase {

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

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $config = $this
      ->config('amp.analytics.settings');
    $ampService = \Drupal::service('amp.utilities');
    $form['google_analytics'] = [
      '#type' => 'details',
      '#title' => t('Google Analytics'),
      '#open' => !empty($config
        ->get('google_analytics_id')),
    ];
    $form['google_analytics']['google_analytics_id'] = [
      '#type' => 'textfield',
      '#default_value' => $config
        ->get('google_analytics_id'),
      '#title' => $this
        ->t('Google Analytics ID'),
      '#description' => '<p>' . $this
        ->t('Enter a value to add the Google Analytics ' . 'code to your AMP pages. This ID is unique to each site you want to ' . 'track separately, and is in the form of UA-xxxxxxx-yy. To get a Web ' . 'Property ID, <a href=":analytics">register your site with Google ' . 'Analytics</a>, or if you already have registered your site, go to ' . 'your Google Analytics Settings page to see the ID next to every site ' . 'profile. <a href=":webpropertyid">Find more information in the ' . 'documentation</a>.', [
        ':analytics' => 'http://www.google.com/analytics/',
        ':webpropertyid' => Url::fromUri('https://developers.google.com/analytics/resources/concepts/gaConceptsAccounts', [
          'fragment' => 'webProperty',
        ])
          ->toString(),
      ]) . '</p><p>' . $ampService
        ->libraryDescription([
        'amp/amp.analytics',
      ]) . '</p>',
      '#maxlength' => 20,
      '#size' => 15,
      '#placeholder' => 'UA-',
    ];
    $form['gtm'] = [
      '#type' => 'details',
      '#title' => t('Google Tag Manager'),
      '#open' => !empty($config
        ->get('amp_gtm_id')),
    ];
    $form['gtm']['amp_gtm_id'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('The Google Tag Manager ID'),
      '#default_value' => $config
        ->get('amp_gtm_id'),
      '#description' => '<p>' . $this
        ->t('Enter a value to add the Google Tag Manager ' . 'code to your AMP pages. This is the Google Tag Manager ID for the ' . 'site owner. Get this in your <a href=":url">Google Tag Manager</a> ' . 'account. GTM has built-in AMP functionality. Go to the GTM ' . 'administration page, enter an account (your business) and container ' . '(the site url), select AMP, and click Create. Pull out the ' . 'id from that code (it looks like GTM-xxxxxxx) and paste it here.', [
        ':url' => Url::fromUri('https://tagmanager.google.com')
          ->toString(),
      ]) . '</p><p>' . $ampService
        ->libraryDescription([
        'amp/amp.analytics',
      ]) . '</p>',
      '#maxlength' => 20,
      '#size' => 15,
      '#placeholder' => 'GTM-',
    ];
    $form['pixel'] = [
      '#type' => 'details',
      '#title' => t('amp-pixel'),
      '#open' => !empty($config
        ->get('amp_pixel')),
    ];
    $form['pixel']['amp_pixel'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Enable amp-pixel'),
      '#default_value' => $config
        ->get('amp_pixel'),
      '#description' => $ampService
        ->libraryDescription([
        'amp/amp.pixel',
      ]),
    ];
    $form['pixel']['amp_pixel_domain_name'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('amp-pixel domain name'),
      '#default_value' => $config
        ->get('amp_pixel_domain_name'),
      '#description' => $this
        ->t('The domain name where the tracking pixel will be loaded: do not include http or https.'),
      '#states' => [
        'visible' => [
          ':input[name="amp_pixel"]' => [
            'checked' => TRUE,
          ],
        ],
      ],
    ];
    $form['pixel']['amp_pixel_query_string'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('amp-pixel query path'),
      '#default_value' => $config
        ->get('amp_pixel_query_string'),
      '#description' => $this
        ->t('The path at the domain where the GET request will be received, e.g. "pixel" in example.com/pixel?RANDOM.'),
      '#states' => [
        'visible' => [
          ':input[name="amp_pixel"]' => [
            'checked' => TRUE,
          ],
        ],
      ],
    ];
    $form['pixel']['amp_pixel_random_number'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Random number'),
      '#default_value' => $config
        ->get('amp_pixel_random_number'),
      '#description' => $this
        ->t('Use the special string RANDOM to add a random number to the URL if required. Find more information in the <a href="https://github.com/ampproject/amphtml/blob/master/spec/amp-var-substitutions.md#random">amp-pixel documentation</a>.'),
      '#states' => [
        'visible' => [
          ':input[name="amp_pixel"]' => [
            'checked' => TRUE,
          ],
        ],
      ],
    ];
    return parent::buildForm($form, $form_state);
  }

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

    // Validate the Google Analytics ID.
    if (!empty($form_state
      ->getValue('google_analytics_id'))) {
      $form_state
        ->setValue('google_analytics_id', trim($form_state
        ->getValue('google_analytics_id')));

      // Replace all type of dashes (n-dash, m-dash, minus) with normal dashes.
      $form_state
        ->setValue('google_analytics_id', str_replace([
        '–',
        '—',
        '−',
      ], '-', $form_state
        ->getValue('google_analytics_id')));
      if (!preg_match('/^UA-\\d+-\\d+$/', $form_state
        ->getValue('google_analytics_id'))) {
        $form_state
          ->setErrorByName('google_analytics_id', t('A valid Google Analytics Web Property ID is case sensitive and formatted like UA-xxxxxxx-yy.'));
      }
    }

    // Validate the Google Tag Manager ID.
    if (!empty($form_state
      ->getValue('gtm_id'))) {
      $form_state
        ->setValue('gtm_id', trim($form_state
        ->getValue('gtm_id')));

      // Replace all type of dashes (n-dash, m-dash, minus) with normal dashes.
      $form_state
        ->setValue('gtm_id', str_replace([
        '–',
        '—',
        '−',
      ], '-', $form_state
        ->getValue('gtm_id')));
      if (!preg_match('/^GTM-[\\d\\w]+$/', $form_state
        ->getValue('gtm_id'))) {
        $form_state
          ->setErrorByName('gtm_id', t('A valid Google Tag Manager ID is case sensitive and formatted like GTM-xxxxxxx.'));
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $config = $this
      ->config('amp.analytics.settings');
    $config
      ->set('google_analytics_id', $form_state
      ->getValue('google_analytics_id'))
      ->save();
    $config
      ->set('amp_gtm_id', $form_state
      ->getValue('amp_gtm_id'))
      ->save();
    $config
      ->set('amp_pixel', $form_state
      ->getValue('amp_pixel'))
      ->save();
    $config
      ->set('amp_pixel_domain_name', $form_state
      ->getValue('amp_pixel_domain_name'))
      ->save();
    $config
      ->set('amp_pixel_query_string', $form_state
      ->getValue('amp_pixel_query_string'))
      ->save();
    $config
      ->set('amp_pixel_random_number', $form_state
      ->getValue('amp_pixel_random_number'))
      ->save();
    parent::submitForm($form, $form_state);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
AmpAnalyticsSettingsForm::buildForm public function Form constructor. Overrides ConfigFormBase::buildForm
AmpAnalyticsSettingsForm::getEditableConfigNames protected function Gets the configuration names that will be editable. Overrides ConfigFormBaseTrait::getEditableConfigNames
AmpAnalyticsSettingsForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
AmpAnalyticsSettingsForm::submitForm public function Form submission handler. Overrides ConfigFormBase::submitForm
AmpAnalyticsSettingsForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
ConfigFormBase::create public static function Instantiates a new instance of this class. Overrides FormBase::create 13
ConfigFormBase::__construct public function Constructs a \Drupal\system\ConfigFormBase object. 11
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.
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.