View source
<?php
namespace Drupal\layout_builder_ids\EventSubscriber;
use Drupal\Component\Utility\Html;
use Drupal\core_event_dispatcher\Event\Form\FormAlterEvent;
use Drupal\Core\Form\FormStateInterface;
use Drupal\hook_event_dispatcher\HookEventDispatcherInterface;
use Drupal\layout_builder_ids\Service\LayoutBuilderIdsService;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class LayoutBuilderIdsConfigureBlock implements EventSubscriberInterface {
protected $layoutBuilderIdsService;
public function __construct(LayoutBuilderIdsService $layoutBuilderIdsService) {
$this->layoutBuilderIdsService = $layoutBuilderIdsService;
}
public static function alterForm(FormAlterEvent $event) : void {
$form =& $event
->getForm();
if (in_array($form['#form_id'], [
'layout_builder_add_block',
'layout_builder_update_block',
], TRUE)) {
$layout_builder_id = $event
->getFormState()
->getFormObject()
->getCurrentComponent()
->get('layout_builder_id');
$form['settings']['layout_builder_id'] = [
'#type' => 'textfield',
'#title' => 'Block ID',
'#weight' => 99,
'#default_value' => $layout_builder_id ?: NULL,
'#description' => t('Block ID is an optional setting which is used to support an anchor link to this block. For example, entering "feature" lets you link directly to this block by adding "#feature" to the end of the URL.</br>IDs should start with a letter, may only contain letters, numbers, underscores, hyphens, and periods, and should be unique on the page.'),
];
$form['#validate'][] = 'Drupal\\layout_builder_ids\\EventSubscriber\\LayoutBuilderIdsConfigureBlock::layoutBuilderIdsConfigureBlockFormValidation';
array_unshift($form['#submit'], 'Drupal\\layout_builder_ids\\EventSubscriber\\LayoutBuilderIdsConfigureBlock::layoutBuilderIdsConfigureBlockSubmitForm');
}
}
public static function layoutBuilderIdsConfigureBlockFormValidation(array &$form, FormStateInterface $form_state) {
$layout_builder_id = Html::getId($form_state
->getValue([
'settings',
'layout_builder_id',
]));
if ($layout_builder_id !== '' && $layout_builder_id !== NULL) {
$found_id = LayoutBuilderIdsService::layoutBuilderIdsCheckIds($layout_builder_id, $form_state, 'block');
if ($found_id) {
$form_state
->setError($form['settings']['layout_builder_id'], 'There is already a block or section with the ID "' . $layout_builder_id . '".');
}
}
}
public static function layoutBuilderIdsConfigureBlockSubmitForm(array &$form, FormStateInterface $form_state) {
$layout_builder_id = $form_state
->getValue([
'settings',
'layout_builder_id',
]);
if ($layout_builder_id !== NULL) {
$component = $form_state
->getFormObject()
->getCurrentComponent();
$component
->set('layout_builder_id', Html::getId($layout_builder_id));
}
}
public static function getSubscribedEvents() : array {
return [
HookEventDispatcherInterface::FORM_ALTER => 'alterForm',
];
}
}