RenderedSiteSettingsBlock.php in Site Settings and Labels 8
File
src/Plugin/Block/RenderedSiteSettingsBlock.php
View source
<?php
namespace Drupal\site_settings\Plugin\Block;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
class RenderedSiteSettingsBlock extends BlockBase implements ContainerFactoryPluginInterface {
protected $entityTypeManager;
public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->entityTypeManager = $entity_type_manager;
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($configuration, $plugin_id, $plugin_definition, $container
->get('entity_type.manager'));
}
public function defaultConfiguration() {
return [
'setting' => NULL,
'label_display' => FALSE,
] + parent::defaultConfiguration();
}
public function blockForm($form, FormStateInterface $form_state) {
$form['setting'] = [
'#type' => 'entity_autocomplete',
'#target_type' => 'site_setting_entity_type',
'#title' => $this
->t('Site setting type'),
'#weight' => '20',
'#required' => TRUE,
];
if (isset($this->configuration['setting']) && !empty($this->configuration['setting'])) {
$setting_entity_type = $this->entityTypeManager
->getStorage('site_setting_entity_type')
->load($this->configuration['setting']);
$form['setting']['#default_value'] = $setting_entity_type;
}
return $form;
}
public function blockSubmit($form, FormStateInterface $form_state) {
$this->configuration['setting'] = $form_state
->getValue('setting');
}
public function build() {
$build = [];
$entities = $this->entityTypeManager
->getStorage('site_setting_entity')
->loadByProperties([
'type' => $this->configuration['setting'],
]);
if (empty($entities)) {
return $build;
}
$view_builder = $this->entityTypeManager
->getViewBuilder('site_setting_entity');
foreach ($entities as $entity) {
$pre_render = $view_builder
->view($entity, 'default');
$render_output = render($pre_render);
$build[] = [
'#markup' => $render_output,
];
}
return $build;
}
}