5 * Module for adding classes to blocks.
8 use Drupal\block\Entity\Block;
11 * Implements hook_form_FORM_ID_alter().
13 function block_class_form_block_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
14 if (\Drupal::currentUser()->hasPermission('administer block classes')) {
16 /** @var \Drupal\block\BlockInterface $block */
17 $block = $form_state->getFormObject()->getEntity();
19 // This will automatically be saved in the third party settings.
20 $form['third_party_settings']['#tree'] = TRUE;
21 $form['third_party_settings']['block_class']['classes'] = array(
22 '#type' => 'textfield',
23 '#title' => t('CSS class(es)'),
24 '#description' => t('Customize the styling of this block by adding CSS classes. Separate multiple classes by spaces.'),
25 '#default_value' => $block->getThirdPartySetting('block_class', 'classes'),
32 * Implements hook_preprocess_HOOK().
34 function block_class_preprocess_block(&$variables) {
35 // Blocks coming from page manager widget does not have id.
36 if (!empty($variables['elements']['#id'])) {
37 $block = Block::load($variables['elements']['#id']);
38 if ($classes = $block->getThirdPartySetting('block_class', 'classes')) {
39 $variables['attributes']['class'][] = $classes;