5 * Adding classes to blocks.
8 use Drupal\Core\Form\FormStateInterface;
9 use Drupal\block\Entity\Block;
10 use Drupal\Component\Utility\Html;
11 use Drupal\Core\Routing\RouteMatchInterface;
12 use Drupal\block\BlockInterface;
15 * Implements hook_ENTITY_TYPE_presave().
17 function block_class_block_presave(BlockInterface $entity) {
18 if (empty($entity->getThirdPartySetting('block_class', 'classes'))) {
19 $entity->unsetThirdPartySetting('block_class', 'classes');
24 * Implements hook_form_FORM_ID_alter().
26 function block_class_form_block_form_alter(&$form, FormStateInterface $form_state, $form_id) {
27 if (\Drupal::currentUser()->hasPermission('administer block classes')) {
29 /** @var \Drupal\block\BlockInterface $block */
30 $block = $form_state->getFormObject()->getEntity();
32 // This will automatically be saved in the third party settings.
33 $form['third_party_settings']['#tree'] = TRUE;
34 $form['third_party_settings']['block_class']['classes'] = [
35 '#type' => 'textfield',
36 '#title' => t('CSS class(es)'),
37 '#description' => t('Customize the styling of this block by adding CSS classes. Separate multiple classes by spaces.'),
38 '#default_value' => $block->getThirdPartySetting('block_class', 'classes'),
45 * Implements hook_preprocess_HOOK().
47 function block_class_preprocess_block(&$variables) {
48 // Blocks coming from page manager widget does not have id.
49 if (!empty($variables['elements']['#id'])) {
50 $block = Block::load($variables['elements']['#id']);
51 if ($block && $classes = $block->getThirdPartySetting('block_class', 'classes')) {
52 $classes_array = explode(' ', $classes);
53 foreach ($classes_array as $class) {
54 $variables['attributes']['class'][] = Html::cleanCssIdentifier($class, []);
61 * Implements hook_help().
63 function block_class_help($route_name, RouteMatchInterface $route_match) {
64 switch ($route_name) {
65 // Main module help for the forms_to_email module.
66 case 'help.page.block_class':
68 $output .= '<h3>' . t('About') . '</h3>';
69 $output .= '<p>' . t("Block Class allows users to add classes to any block through the block's configuration interface. Hooray for more powerful block theming!") . '</p>';
71 $output .= '<h3>' . t('Installation note') . '</h3>';
73 $output .= '<dt>' . t('Enable the module on <a href=":extend_link">extend menu</a>.', [':extend_link' => \Drupal::url('system.modules_list')]) . '</dt>';
76 $output .= '<h3>' . t('Usage') . '</h3>';
78 $output .= '<dt>' . t("To add a class to a block, simply visit that block's configuration page at Administration > Structure > Block Layout and click on Configure of the desired block.") . '</dt>';