Repository URL to install this package:
|
Version:
2.0.2 ▾
|
<?php
namespace Drupal\custom_forms\EventSubscriber;
use Drupal\Component\Datetime\TimeInterface;
use Drupal\Core\Logger\LoggerChannelFactoryInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\custom_forms\CustomFormItem;
use Drupal\custom_forms\CustomFormItemFactory;
use Drupal\custom_forms\Entity\CustomForm;
use Drupal\entity_clone\Event\EntityCloneEvent;
use Drupal\entity_clone\Event\EntityCloneEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* Class CloneEventSubscriber
*
* Event subscriber that handles cloning of custom form items when a custom form
* is cloned.
*
* @package Drupal\custom_forms\EventSubscriber
*/
class CloneEventSubscriber implements EventSubscriberInterface {
use StringTranslationTrait;
/**
* The logger channel factory.
*
* @var \Drupal\Core\Logger\LoggerChannelInterface
*/
protected $logger;
/**
* @var \Drupal\Component\Datetime\TimeInterface
*/
protected $datetime;
/**
* The factory in charge of CRUD operations for custom form items.
*
* @var \Drupal\custom_forms\CustomFormItemFactory
*/
protected $itemFactory;
public function __construct(LoggerChannelFactoryInterface $logger_factory, TimeInterface $datetime, CustomFormItemFactory $item_factory) {
$this->logger = $logger_factory->get('Custom Forms');
$this->datetime = $datetime;
$this->itemFactory = $item_factory;
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents() {
return [
EntityCloneEvents::POST_CLONE => 'cloneFormItems',
];
}
/**
* Clone the custom form items
*
* @param \Drupal\entity_clone\Event\EntityCloneEvent $event
*/
public function cloneFormItems(EntityCloneEvent $event) {
// We only want to handle the even for custom form.
if ($event->getEntity()->getEntityTypeId() !== 'custom_form') {
return;
}
/** @var \Drupal\custom_forms\Entity\CustomForm $original */
$original = $event->getEntity();
/** @var \Drupal\custom_forms\Entity\CustomForm $clone */
$clone = $event->getClonedEntity();
// If we are missing the original or cloned entities, log an error.
if ($original === NULL || $clone === NULL) {
$this->logger->error(
$this->t('Original or cloned custom form entities are missing, cloning of form fields failed.')
);
return;
}
$original_items = $this->itemFactory->getFormItems($original, FALSE, TRUE);
/** @var \Drupal\custom_forms\CustomFormItem $item */
foreach ($original_items as $item) {
$this->itemFactory->cloneItem($item, $clone);
}
}
}