class ContainerForm in GoogleTagManager 8
Defines the Google tag manager container settings form.
Hierarchy
- class \Drupal\Core\Form\FormBase implements ContainerInjectionInterface, FormInterface uses DependencySerializationTrait, LoggerChannelTrait, MessengerTrait, LinkGeneratorTrait, RedirectDestinationTrait, UrlGeneratorTrait, StringTranslationTrait
- class \Drupal\Core\Entity\EntityForm implements EntityFormInterface
- class \Drupal\google_tag\Form\ContainerForm uses ContainerTrait
- class \Drupal\Core\Entity\EntityForm implements EntityFormInterface
Expanded class hierarchy of ContainerForm
File
- src/
Form/ ContainerForm.php, line 16
Namespace
Drupal\google_tag\FormView source
class ContainerForm extends EntityForm {
use ContainerTrait;
/**
* The condition plugin manager.
*
* @var \Drupal\Core\Condition\ConditionManager
*/
protected $conditionManager;
/**
* The context repository service.
*
* @var \Drupal\Core\Plugin\Context\ContextRepositoryInterface
*/
protected $contextRepository;
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'google_tag_container';
}
/**
* Constructs a ContainerForm object.
*
* @param \Drupal\Core\Executable\ExecutableManagerInterface $condition_manager
* The ConditionManager for building the insertion conditions.
* @param \Drupal\Core\Plugin\Context\ContextRepositoryInterface $context_repository
* The lazy context repository service.
*/
public function __construct(ExecutableManagerInterface $condition_manager, ContextRepositoryInterface $context_repository) {
$this->conditionManager = $condition_manager;
$this->contextRepository = $context_repository;
}
/**
* {@inheritdoc}
*
* This routine is the trick to DependencyInjection in Drupal. Without it the
* __construct method complains of no arguments instead of three.
*/
public static function create(ContainerInterface $container) {
return new static($container
->get('plugin.manager.condition'), $container
->get('context.repository'));
}
/**
* {@inheritdoc}
*/
public function form(array $form, FormStateInterface $form_state) {
$form = parent::form($form, $form_state);
$container = $this->container = $this->entity;
$this->prefix = '';
// Store the contexts for other objects to use during form building.
$form_state
->setTemporaryValue('gathered_contexts', $this->contextRepository
->getAvailableContexts());
// The main premise of entity forms is that we get to work with an entity
// object at all times instead of checking submitted values from the form
// state.
// Build form elements.
$form['label'] = [
'#type' => 'textfield',
'#title' => 'Label',
'#default_value' => $container
->label(),
'#required' => TRUE,
];
$form['id'] = [
'#type' => 'machine_name',
'#default_value' => $container
->id(),
'#required' => TRUE,
'#machine_name' => [
'exists' => [
$this,
'containerExists',
],
'replace_pattern' => '[^a-z0-9_.]+',
],
];
$form['settings'] = [
'#type' => 'vertical_tabs',
'#title' => $this
->t('Container settings'),
'#description' => $this
->t('The settings affecting the snippet contents for this container.'),
'#attributes' => [
'class' => [
'google-tag',
],
],
];
$form['conditions'] = [
'#type' => 'vertical_tabs',
'#title' => $this
->t('Insertion conditions'),
'#description' => $this
->t('The snippet insertion conditions for this container.'),
'#attributes' => [
'class' => [
'google-tag',
],
],
'#attached' => [
'library' => [
'google_tag/drupal.settings_form',
],
],
];
$form['general'] = $this
->generalFieldset($form_state);
$form['advanced'] = $this
->advancedFieldset($form_state);
$form['path'] = $this
->pathFieldset($form_state);
$form['role'] = $this
->roleFieldset($form_state);
$form['status'] = $this
->statusFieldset($form_state);
$form += $this
->conditionsForm([], $form_state);
$form['actions'] = [
'#type' => 'actions',
];
$form['actions']['submit'] = [
'#type' => 'submit',
'#value' => 'Save',
];
$form['actions']['delete'] = [
'#type' => 'submit',
'#value' => 'Delete',
];
return $form;
}
/**
* Fieldset builder for the container settings form.
*/
public function generalFieldset(FormStateInterface &$form_state) {
$container = $this->entity;
// Build form elements.
$fieldset = [
'#type' => 'details',
'#title' => $this
->t('General'),
'#group' => 'settings',
];
$fieldset['container_id'] = [
'#type' => 'textfield',
'#title' => $this
->t('Container ID'),
'#description' => $this
->t('The ID assigned by Google Tag Manager (GTM) for this website container. To get a container ID, <a href="https://tagmanager.google.com/">sign up for GTM</a> and create a container for your website.'),
'#default_value' => $container
->get('container_id'),
'#attributes' => [
'placeholder' => [
'GTM-xxxxxx',
],
],
'#size' => 12,
'#maxlength' => 15,
'#required' => TRUE,
];
$fieldset['weight'] = [
'#type' => 'weight',
'#title' => 'Weight',
'#default_value' => $container
->get('weight'),
];
return $fieldset;
}
/**
* Builds the form elements for the insertion conditions.
*
* @param array $form
* An associative array containing the structure of the form.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The current state of the form.
*
* @return array
* The augmented form array with the insertion condition elements.
*/
protected function conditionsForm(array $form, FormStateInterface $form_state) {
$conditions = $this->entity
->getInsertionConditions();
// See core/lib/Drupal/Core/Plugin/FilteredPluginManagerTrait.php
// The next method calls alter hooks to filter the definitions.
// Implement one of the hooks in this module.
$definitions = $this->conditionManager
->getFilteredDefinitions('google_tag', $form_state
->getTemporaryValue('gathered_contexts'), [
'google_tag_container' => $this->entity,
]);
ksort($definitions);
$form_state
->setTemporaryValue('filtered_conditions', array_keys($definitions));
foreach ($definitions as $condition_id => $definition) {
if ($conditions
->has($condition_id)) {
$condition = $conditions
->get($condition_id);
}
else {
/** @var \Drupal\Core\Condition\ConditionInterface $condition */
$condition = $this->conditionManager
->createInstance($condition_id, []);
}
$form_state
->set([
'conditions',
$condition_id,
], $condition);
$form[$condition_id] = $this
->conditionFieldset($condition, $form_state);
}
/*
// Add comment to first condition tab.
// @todo This would apply if all insertion conditions were converted to
// condition plugins.
$description = $this->t('On this and the following tabs, specify the conditions on which the GTM JavaScript snippet will either be inserted on or omitted from the page response, thereby enabling or disabling tracking and other analytics. All conditions must be satisfied for the snippet to be inserted. The snippet will be omitted if any condition is not met.');
$condition_id = current(array_keys($definitions));
$form[$condition_id]['#description'] = $description;
*/
return $form;
}
/**
* Returns the form elements from the condition plugin object.
*
* @param \Drupal\Core\Condition\ConditionInterface $condition
* The condition plugin.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The current state of the form.
*
* @return array
* The form array for the insertion condition.
*/
public function conditionFieldset(ConditionInterface $condition, FormStateInterface $form_state) {
// Build form elements.
$fieldset = [
'#type' => 'details',
'#title' => $condition
->getPluginDefinition()['label'],
'#group' => 'conditions',
'#tree' => TRUE,
] + $condition
->buildConfigurationForm([], $form_state);
return $fieldset;
}
/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
$this
->validateFormValues($form, $form_state);
parent::validateForm($form, $form_state);
$this
->validateConditionsForm($form, $form_state);
}
/**
* Form validation handler for the insertion conditions.
*
* @param array $form
* An associative array containing the structure of the form.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The current state of the form.
*/
protected function validateConditionsForm(array $form, FormStateInterface $form_state) {
// Validate the insertion condition settings.
$condition_ids = $form_state
->getTemporaryValue('filtered_conditions');
foreach ($condition_ids as $condition_id) {
// Allow the condition to validate the form.
$condition = $form_state
->get([
'conditions',
$condition_id,
]);
$condition
->validateConfigurationForm($form[$condition_id], SubformState::createForSubform($form[$condition_id], $form, $form_state));
}
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
parent::submitForm($form, $form_state);
$this
->submitConditionsForm($form, $form_state);
}
/**
* Form submission handler for the insertion conditions.
*
* @param array $form
* An associative array containing the structure of the form.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The current state of the form.
*/
protected function submitConditionsForm(array $form, FormStateInterface $form_state) {
$condition_ids = $form_state
->getTemporaryValue('filtered_conditions');
foreach ($condition_ids as $condition_id) {
$values = $form_state
->getValue($condition_id);
// Allow the condition to submit the form.
$condition = $form_state
->get([
'conditions',
$condition_id,
]);
$condition
->submitConfigurationForm($form[$condition_id], SubformState::createForSubform($form[$condition_id], $form, $form_state));
$configuration = $condition
->getConfiguration();
// Update the insertion conditions on the container.
$this->entity
->setInsertionCondition($condition_id, $configuration);
}
}
/**
* {@inheritdoc}
*/
public function save(array $form, FormStateInterface $form_state) {
// Drupal/Core/Condition/ConditionPluginCollection.php
// On save, above class filters any condition with default configuration.
// See ::getConfiguration()
// The database row omits such conditions from the container 'conditions'.
// google_tag/src/ContainerAccessControlHandler.php
// On access check, the list of conditions only includes those in database.
// Those with default configuration are assumed not to apply as the default
// values should produce no restriction.
// However, core treats an empty values list opposite this module.
parent::save($form, $form_state);
// @todo This could be done in container::postSave() method.
global $_google_tag_display_message;
$_google_tag_display_message = TRUE;
$manager = \Drupal::service('google_tag.container_manager');
$manager
->createAssets($this->entity);
// Redirect to collection page.
$form_state
->setRedirect('entity.google_tag_container.collection');
}
/**
* Checks if a container machine name is taken.
*
* @param string $value
* The machine name.
* @param array $element
* An array containing the structure of the 'id' element.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The current state of the form.
*
* @return bool
* Whether or not the container machine name is taken.
*/
public function containerExists($value, array $element, FormStateInterface $form_state) {
/** @var \Drupal\Core\Config\Entity\ConfigEntityInterface $container */
$container = $form_state
->getFormObject()
->getEntity();
return (bool) $this->entityTypeManager
->getStorage($container
->getEntityTypeId())
->getQuery()
->condition($container
->getEntityType()
->getKey('id'), $value)
->execute();
}
}
Members
Name![]() |
Modifiers | Type | Description | Overrides |
---|---|---|---|---|
ContainerForm:: |
protected | property | The condition plugin manager. | |
ContainerForm:: |
protected | property | The context repository service. | |
ContainerForm:: |
public | function | Returns the form elements from the condition plugin object. | |
ContainerForm:: |
protected | function | Builds the form elements for the insertion conditions. | |
ContainerForm:: |
public | function | Checks if a container machine name is taken. | |
ContainerForm:: |
public static | function |
This routine is the trick to DependencyInjection in Drupal. Without it the
__construct method complains of no arguments instead of three. Overrides FormBase:: |
|
ContainerForm:: |
public | function |
Gets the actual form array to be built. Overrides EntityForm:: |
|
ContainerForm:: |
public | function | Fieldset builder for the container settings form. | |
ContainerForm:: |
public | function |
Returns a unique string identifying the form. Overrides EntityForm:: |
|
ContainerForm:: |
public | function |
Form submission handler for the 'save' action. Overrides EntityForm:: |
|
ContainerForm:: |
protected | function | Form submission handler for the insertion conditions. | |
ContainerForm:: |
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 EntityForm:: |
|
ContainerForm:: |
protected | function | Form validation handler for the insertion conditions. | |
ContainerForm:: |
public | function |
Form validation handler. Overrides FormBase:: |
|
ContainerForm:: |
public | function | Constructs a ContainerForm object. | |
ContainerTrait:: |
protected | property | The container entity. | |
ContainerTrait:: |
protected | property | The property prefix that allows reuse by container and settings forms. | |
ContainerTrait:: |
public | function | Fieldset builder for the container settings form. | |
ContainerTrait:: |
public | function | Cleans a string representing a list of items. | |
ContainerTrait:: |
public | function | Fieldset builder for the container settings form. | |
ContainerTrait:: |
public | function | Fieldset builder for the container settings form. | |
ContainerTrait:: |
public | function | Fieldset builder for the container settings form. | |
ContainerTrait:: |
protected | function | Returns a translated string after placeholder substitution. | |
ContainerTrait:: |
public | function | Returns states array for a form element. | |
ContainerTrait:: |
public | function | Fieldset builder for the container settings form. | |
ContainerTrait:: |
public | function | ||
DependencySerializationTrait:: |
protected | property | An array of entity type IDs keyed by the property name of their storages. | |
DependencySerializationTrait:: |
protected | property | An array of service IDs keyed by property name used for serialization. | |
DependencySerializationTrait:: |
public | function | 1 | |
DependencySerializationTrait:: |
public | function | 2 | |
EntityForm:: |
protected | property | The entity being used by this form. | 7 |
EntityForm:: |
protected | property | The entity type manager. | 3 |
EntityForm:: |
protected | property | The module handler service. | |
EntityForm:: |
protected | property | The name of the current operation. | |
EntityForm:: |
private | property | The entity manager. | |
EntityForm:: |
protected | function | Returns an array of supported actions for the current entity form. | 29 |
EntityForm:: |
protected | function | Returns the action form element for the current entity form. | |
EntityForm:: |
public | function | Form element #after_build callback: Updates the entity with submitted data. | |
EntityForm:: |
public | function |
Builds an updated entity object based upon the submitted form values. Overrides EntityFormInterface:: |
2 |
EntityForm:: |
public | function |
Form constructor. Overrides FormInterface:: |
10 |
EntityForm:: |
protected | function | Copies top-level form values to entity properties | 7 |
EntityForm:: |
public | function |
Returns a string identifying the base form. Overrides BaseFormIdInterface:: |
5 |
EntityForm:: |
public | function |
Gets the form entity. Overrides EntityFormInterface:: |
|
EntityForm:: |
public | function |
Determines which entity will be used by this form from a RouteMatch object. Overrides EntityFormInterface:: |
1 |
EntityForm:: |
public | function |
Gets the operation identifying the form. Overrides EntityFormInterface:: |
|
EntityForm:: |
protected | function | Initialize the form state and the entity before the first form build. | 3 |
EntityForm:: |
protected | function | Prepares the entity object before the form is built first. | 3 |
EntityForm:: |
protected | function | Invokes the specified prepare hook variant. | |
EntityForm:: |
public | function | Process callback: assigns weights and hides extra fields. | |
EntityForm:: |
public | function |
Sets the form entity. Overrides EntityFormInterface:: |
|
EntityForm:: |
public | function |
Sets the entity manager for this form. Overrides EntityFormInterface:: |
|
EntityForm:: |
public | function |
Sets the entity type manager for this form. Overrides EntityFormInterface:: |
|
EntityForm:: |
public | function |
Sets the module handler for this form. Overrides EntityFormInterface:: |
|
EntityForm:: |
public | function |
Sets the operation for this form. Overrides EntityFormInterface:: |
|
EntityForm:: |
public | function | ||
EntityForm:: |
public | function | ||
FormBase:: |
protected | property | The config factory. | 1 |
FormBase:: |
protected | property | The request stack. | 1 |
FormBase:: |
protected | property | The route match. | |
FormBase:: |
protected | function | Retrieves a configuration object. | |
FormBase:: |
protected | function | Gets the config factory for this form. | 1 |
FormBase:: |
private | function | Returns the service container. | |
FormBase:: |
protected | function | Gets the current user. | |
FormBase:: |
protected | function | Gets the request object. | |
FormBase:: |
protected | function | Gets the route match. | |
FormBase:: |
protected | function | Gets the logger for a specific channel. | |
FormBase:: |
protected | function |
Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait:: |
|
FormBase:: |
public | function | Resets the configuration factory. | |
FormBase:: |
public | function | Sets the config factory for this form. | |
FormBase:: |
public | function | Sets the request stack object to use. | |
LinkGeneratorTrait:: |
protected | property | The link generator. | 1 |
LinkGeneratorTrait:: |
protected | function | Returns the link generator. | |
LinkGeneratorTrait:: |
protected | function | Renders a link to a route given a route name and its parameters. | |
LinkGeneratorTrait:: |
public | function | Sets the link generator service. | |
LoggerChannelTrait:: |
protected | property | The logger channel factory service. | |
LoggerChannelTrait:: |
protected | function | Gets the logger for a specific channel. | |
LoggerChannelTrait:: |
public | function | Injects the logger channel factory. | |
MessengerTrait:: |
protected | property | The messenger. | 29 |
MessengerTrait:: |
public | function | Gets the messenger. | 29 |
MessengerTrait:: |
public | function | Sets the messenger. | |
RedirectDestinationTrait:: |
protected | property | The redirect destination service. | 1 |
RedirectDestinationTrait:: |
protected | function | Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url. | |
RedirectDestinationTrait:: |
protected | function | Returns the redirect destination service. | |
RedirectDestinationTrait:: |
public | function | Sets the redirect destination service. | |
StringTranslationTrait:: |
protected | property | The string translation service. | 1 |
StringTranslationTrait:: |
protected | function | Formats a string containing a count of items. | |
StringTranslationTrait:: |
protected | function | Returns the number of plurals supported by a given language. | |
StringTranslationTrait:: |
protected | function | Gets the string translation service. | |
StringTranslationTrait:: |
public | function | Sets the string translation service to use. | 2 |
StringTranslationTrait:: |
protected | function | Translates a string to the current language or to a given language. | |
UrlGeneratorTrait:: |
protected | property | The url generator. | |
UrlGeneratorTrait:: |
protected | function | Returns the URL generator service. | |
UrlGeneratorTrait:: |
public | function | Sets the URL generator service. | |
UrlGeneratorTrait:: |
protected | function | Generates a URL or path for a specific route based on the given parameters. |