entity_value_inheritance-1.3.0/src/EventSubscriber/DisabledFieldSubscriber.php
src/EventSubscriber/DisabledFieldSubscriber.php
<?php
namespace Drupal\entity_value_inheritance\EventSubscriber;
use Drupal\Core\Render\Element;
use Drupal\entity_value_inheritance\Event\InheritanceAlterFieldEvent;
use Drupal\entity_value_inheritance\Event\InheritanceEvents;
/**
* Event Subscriber used for Disabling fields.
*/
class DisabledFieldSubscriber extends EventSubscriberBase {
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents(): array {
$events = [];
$events[InheritanceEvents::ALTER_FIELD][] = ['disableField', 1000];
return $events;
}
/**
* Disable the field.
*
* Event to disable the field if the configuration is set to disabled and
* show the message.
*/
public function disableField(InheritanceAlterFieldEvent $event) {
$inheritance = $event->getInheritance();
if (
$inheritance->getStrategy() === 'disable' &&
!($event->getEntity()->get($inheritance->getDestinationReferenceField())->isEmpty())
) {
$element = $event->getElement();
$this->modifyField($element);
$event->setElement($element);
$message = $inheritance->getSetting('message');
$event->setMessage($message);
}
}
/**
* Add disable attribute to all children.
*
* @param array &$element
* Element to loop through.
*/
protected function modifyField(array &$element): void {
$children = Element::getVisibleChildren($element);
$element['#disabled'] = TRUE;
// If there are children then recurse the function.
if (count($children) > 0) {
foreach ($children as $child) {
$this->modifyField($element[$child]);
}
}
}
}
