php
SampleEntityProvider.php
<?php
namespace Drupal\MY_MODULE;
use Drupal\Core\DependencyInjection\ServiceProviderBase;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Psr\Log\LoggerInterface;
/**
* A service that generates a sample entity with populated fields.
*/
class SampleEntityProvider extends ServiceProviderBase {
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* The logger service.
*
* @var \Psr\Log\LoggerInterface
*/
protected $logger;
/**
* Creates a SampleEntityProvider object.
*
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
* @param \Psr\Log\LoggerInterface $logger
* A logger instance.
*/
public function __construct(EntityTypeManagerInterface $entity_type_manager, LoggerInterface $logger) {
$this->entityTypeManager = $entity_type_manager;
$this->logger = $logger;
}
/**
* Gets a sample entity with populated fields.
*
* @param string $entity_type_id
* The entity type id the samle entity should have.
* @param string $entity_bundle
* The bundle the sample entity should have.
*
* @return \Drupal\Core\Entity\EntityInterface|void $entity
* The generated sample entity.
*/
public function getSampleEntity(string $entity_type_id, string $entity_bundle) {
try {
$entity_storge = $this->entityTypeManager->getStorage($entity_type_id);
$bundle_key = $entity_storge->getEntityType()->getKey('bundle');
$sample_entity = $entity_storge->create([$bundle_key => $entity_bundle]);
$this->populateFields($sample_entity);
return $sample_entity;
} catch (\Exception $e) {
$this->logger->error($e->getMessage());
}
}
/**
* Populate the fields on a given entity with sample values.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* The entity to be enriched with sample field values.
*
* @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
* @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
*/
public function populateFields(EntityInterface $entity) {
$properties = [
'entity_type' => $entity->getEntityType()->id(),
'bundle' => $entity->bundle(),
];
$field_config_storage = \Drupal::entityTypeManager()->getStorage('field_config');
/** @var \Drupal\field\FieldConfigInterface[] $instances */
$instances = $field_config_storage->loadByProperties($properties);
foreach ($instances as $instance) {
$field_storage = $instance->getFieldStorageDefinition();
$max = $cardinality = $field_storage->getCardinality();
if ($cardinality == FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED) {
// Just an arbitrary number for 'unlimited'.
$max = rand(1, 3);
}
$field_name = $field_storage->getName();
$entity->$field_name->generateSampleItems($max);
}
}
}
DomainRouteProvider.php
<?php
namespace Drupal\poormans_domain\Routing;
use Drupal\Core\Routing\RouteProvider;
use Symfony\Component\HttpFoundation\Request;
/**
* Custom router.route_provider service to make it domain context sensitive.
*/
class DomainRouteProvider extends RouteProvider {
/**
* {@inheritdoc}
*/
protected function getRouteCollectionCacheId(Request $request) {
// Add domain sensitive cache information to the cid.
$this->addExtraCacheKeyPart('poormans_domain', $request->getHost());
return parent::getRouteCollectionCacheId($request);
}
}
poormans_domain.services.yml
services:
poormans_domain.route_provider:
class: Drupal\poormans_domain\Routing\DomainRouteProvider
decorates: router.route_provider
decoration_priority: 10
arguments: ['@database', '@state', '@path.current', '@cache.data', '@path_processor_manager', '@cache_tags.invalidator', 'router', '@language_manager']
27.01.2023
poormans_domain.services.yml
MetaCspSubscriber.php
/**
* Alter CSP policy for meta.
*/
class MetaCspSubscriber implements EventSubscriberInterface {
/**
* @var \Drupal\meta_atipixel\MetaAtiCode
*/
protected $metaAtiCode;
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents() {
$events[CspEvents::POLICY_ALTER] = ['onCspPolicyAlter'];
return $events;
}
/**
* MetaCspSubscriber constructor.
*
* @param\Drupal\meta_atipixel\MetaAtiCode $meta_ati_code
* The ati code service.
*/
public function __construct(MetaAtiCode $meta_ati_code) {
$this->metaAtiCode = $meta_ati_code;
}
/**
* Add hashed and nonces if we are not on unsafe-inline anyway.
*
* @param \Drupal\csp\Event\PolicyAlterEvent $alterEvent
* The Policy Alter event.
*/
public function onCspPolicyAlter(PolicyAlterEvent $alterEvent) {
$policy = $alterEvent->getPolicy();
$nonce = $this->metaAtiCode->getNonce();
if (!in_array("'unsafe-inline'", $policy->getDirective('script-src'))) {
$additions = [
// scripts in html.html.twig
"'sha256-u9HSg2Pp8ssH/rPdIjXPA2C4w25lvarx61zTFRKUrmM='",
"'sha256-MpSPVM+F08E973/LoTypmKAw/3M85wXWX6kWfoTFytc='",
"'sha256-LP15v8l8fhV/n/S6XgVVfXn7GJIVJ3hoL8UIw4BYxsE='",
// onClicks in page.html.twig
"'sha256-UvdkyVIodw5ho+TLRpWSJlSwRybZxclpp+OSCf7w67I='",
"'sha256-GGza1Y9dREBYst5ReIQ6hgev0+2sE9tMsbcJ29qs4w4='",
"'sha256-O5E6+QtFv/CBsWdAYZvTiTYiHXAA7iTst1rBecCv6dI='",
"'sha256-hIoyxe70kL8INnzt1lpp3M9bfkqfZmnY0SXJrA5LKoA='",
"'sha256-IVlAoFKs/eP8PtbJup9f6kWE26ZguV+Cmqs6+98t3EE='",
"'sha256-JmPJi7h6GEv+mUBBxVrImXEvDVkqcCK/xncob2D/3JA='",
// Ati pixel nonce
"'nonce-$nonce'"
];
$policy->fallbackAwareAppendIfEnabled('script-src', $additions);
}
}
}
10.08.2022 | Dominik Wille
MetaCspSubscriber.php
Easy clean up cron functionality using DB Statements. Should be used with custom tables, which brought their own schema. See: https://mariadb.com/kb/en/date-and-time-units/
example.php
/**
* Implements hook_cron().
*/
function your_module_cron() {
\Drupal::database()
->query("DELETE FROM example_custom_table WHERE created < UNIX_TIMESTAMP(NOW() - INTERVAL 6 MONTH)")
->execute();
}
29.06.2022 | Nikolas Kopp
Cleanup Cron
Related issue: https://www.drupal.org/project/drupal/issues/2408549
SMTPConfigForm.php
/**
* Check if config variable is overridden by the settings.php.
*
* @param string $name
* SMTP settings key.
*
* @return bool
* Boolean.
*/
protected function isOverridden($name) {
$original = $this->configFactory->getEditable('smtp.settings')->get($name);
$current = $this->configFactory->get('smtp.settings')->get($name);
return $original != $current;
}
10.08.2022 | Dominik Wille
SMTPConfigForm.php
EntityInstanceAliasFragment.php
/**
* Defines the entity_instance_alias_fragment entity class.
*
* @ContentEntityType(
* id = "entity_instance_alias_fragment",
* label = @Translation("entity_instance alias fragment"),
* label_collection = @Translation("Alias fragments"),
* label_singular = @Translation("Alias fragment"),
* label_plural = @Translation("Alias fragments"),
* label_count = @PluralTranslation(
* singular = "@count Alias fragment",
* plural = "@count Alias fragments"
* ),
* handlers = {
* "storage" = "Drupal\Core\Entity\Sql\SqlContentEntityStorage",
* "storage_schema" = "Drupal\Core\Entity\Sql\SqlContentEntityStorageSchema",
* },
* base_table = "entity_instance_alias_fragment",
* revision_table = "entity_instance_alias_fragment_revision",
* entity_keys = {
* "id" = "id",
* "revision" = "revision_id",
* "langcode" = "langcode",
* "uuid" = "uuid",
* "published" = "status",
* },
* admin_permission = "administer alias fragments",
* list_cache_tags = { "route_match" },
* constraints = {
* "UniqueEntityInstanceAliasFragment" = {}
* }
* )
*/
01.06.2022 | Dominik Wille
Using Constraints for content entity types
FYI: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Form%21F…
SettingsForm.php
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$config = $this->config('user_cancel_entity_queue.settings');
$clean_value_keys = $form_state->getCleanValueKeys();
$clean_value_keys[] = 'submit';
$values = array_filter($form_state->getValues(), function($value, $key) use ($clean_value_keys) {
return !in_array($key, $clean_value_keys);
},ARRAY_FILTER_USE_BOTH);
foreach ($values as $key => $value) {
$config->set($key, $value);
}
$config->save();
parent::submitForm($form, $form_state);
}CourseDate.php
public function submitForm(array &$form, FormStateInterface $form_state) {
/** @var DrupalDateTime $course_date */
$course_date = $form_state->getValue('field_course_date');
$this->node->set('field_course_date', $course_date->format(DateTimeItemInterface::DATETIME_STORAGE_FORMAT, ['timezone' => 'UTC']));
$this->node->save();
}Description
If you handle dates in a custom form, Drupal does not always store the date in the UTC format. It takes your local timezone. So we have to store the value of our date field as UTC.
Changed File
The file generating your form. E.g. mymodule/src/Form/CourseDate.php
04.05.2022 | Michael Ebert
CourseDate.php
PasswordItem.php
/**
* Defines the 'password' entity field type.
*
* @FieldType(
* id = "password",
* label = @Translation("Password"),
* description = @Translation("An entity field containing a password value."),
* no_ui = TRUE,
* )
*/
18.12.2025 | Michael Böker