InlineBlockUX.php in Layout Builder UX 8
File
src/Plugin/Block/InlineBlockUX.php
View source
<?php
namespace Drupal\lb_ux\Plugin\Block;
use Drupal\Component\Plugin\DerivativeInspectionInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\layout_builder\Plugin\Block\InlineBlock;
use Symfony\Component\DependencyInjection\ContainerInterface;
class InlineBlockUX extends InlineBlock {
protected $keyValueFactory;
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
$instance = parent::create($container, $configuration, $plugin_id, $plugin_definition);
$instance->keyValueFactory = $container
->get('keyvalue');
return $instance;
}
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
$form = parent::buildConfigurationForm($form, $form_state);
$form['label']['#states']['invisible'][':input[name="settings[label_display]"]']['checked'] = FALSE;
if ($this->isNew) {
$form['label_display']['#default_value'] = FALSE;
$form['label']['#default_value'] = $this
->t('@label @count', [
'@label' => $this
->label(),
'@count' => $this
->getNextInlineBlockNumber($form_state),
]);
}
return $form;
}
public function blockSubmit($form, FormStateInterface $form_state) {
parent::blockSubmit($form, $form_state);
if ($form_state
->has('lb_ux.inline_block_count')) {
$section_storage = $form_state
->getFormObject()
->getSectionStorage();
$this->keyValueFactory
->get('lb_ux.inline_block_count.' . $section_storage
->getStorageType())
->set($section_storage
->getStorageId(), $form_state
->get('lb_ux.inline_block_count'));
}
}
protected function getNextInlineBlockNumber(FormStateInterface $form_state) {
if ($form_state
->has('lb_ux.inline_block_count')) {
return $form_state
->get('lb_ux.inline_block_count');
}
$section_storage = $form_state
->getFormObject()
->getSectionStorage();
$count = $this->keyValueFactory
->get('lb_ux.inline_block_count.' . $section_storage
->getStorageType())
->get($section_storage
->getStorageId(), 0);
if (!$count) {
foreach ($section_storage
->getSections() as $section) {
foreach ($section
->getComponents() as $component) {
$plugin = $component
->getPlugin();
if ($plugin instanceof DerivativeInspectionInterface && $plugin
->getBaseId() === 'inline_block') {
$count++;
}
}
}
if ($form_state
->has('layout_builder__component')) {
$count--;
}
}
$form_state
->set('lb_ux.inline_block_count', ++$count);
return $count;
}
}