2

UPDATED Added other files just in case the error is somewhere else

I just created a custom module for Drupal 8 that defines a block. I want to add some CSS styles to the content of the block.

My last attempt to achieve this was adding a libraries.yml file to the module linking the block_header.css file. In the render array, I added #prefix and #suffix with the CSS classes (<div class='foo'>).

The code doesn't give me any error, but it's not applying the font weight I would expect.

Could you point me to the right direction?

These are the files.

block_header.info.yml

name: Block Header creator
type: module
description: 'Create block with a main header and a text on mouseover'
core: 8.x
package: Fussion Corp - Custom Modules
configure: block_header.settings

block_header.routing.yml

block.content:
  path: '/block'
  defaults:
    _controller: '\Drupal\block_header\Controller\BlockController::content'
    _title: 'Block Header'
  requirements:
    _permission: 'access content'

block_header.libraries.yml

block_header:
version: 1.x
css:
    theme:
        css/block_header.css: {}

BlockController.php

<?php
/**
 * @file
 * Contains \Drupal\block_header\Controller\BlockController.
 */
namespace Drupal\block_header\Controller;
class BlockController {
  public function content() {
    return array(
      '#type' => 'markup',
      '#markup' => t('Sample Text!'),
    );
  }
}

block_header.module

<?php

/**
 * Implements hook_preprocess_HOOK()
 */
function block_header_preprocess_block(&$variables) {
  if ($variables['plugin_id'] == 'block_header') {
    $variables['page']['#attached']['library'][] = 'block_header/block_header';
  }
}

BlockHeader.php

<?php

namespace Drupal\block_header\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Block\BlockPluginInterface;
use Drupal\Core\Form\FormStateInterface;

/**
 * Provides a 'Header' Block.
 *
 * @Block(
 *   id = "block_header",
 *   admin_label = @Translation("Block Header"),
 *   category = @Translation("Block Header"),
 * )
 */

class BlockHeader extends BlockBase implements BlockPluginInterface {

  /**
   * {@inheritdoc}
   */
  public function build() {
    $config = $this->getConfiguration();

    if (!empty($config['block_header_title']) && ($config['block_header_text'])) {
      $title = $config['block_header_title'];
      $descp = $config['block_header_text'];
    }
    else {
      $title = $this->t('<div>Atención! Titulo no configurado!</div> </p>');
      $descp = $this->t('<div>Atención! Descripción no configurada!</div>');
    }
    $block = array
        (
            'title' => array
            (
             '#prefix' => '<div class="title"><p>', /* HERE I ADD THE CSS TAGS */
             '#suffix' => '</p></div>',
             '#markup' => t('@title', array('@title' => $title,)),
            ),
            'description' => array
            (
             '#prefix' => '<div class="descp"><p>', /* HERE I ADD THE CSS TAGS */
             '#suffix' => '</p></div>',
             '#markup' => t('@descp', array('@descp' => $descp,))
            ),
        );
    return $block;  

  }


   /**
   * {@inheritdoc}
   */
  public function blockForm($form, FormStateInterface $form_state) {
    $form = parent::blockForm($form, $form_state);

    $config = $this->getConfiguration();

    $form['block_header_title'] = array(
      '#type' => 'textfield',
      '#title' => $this->t('Titulo del Bloque'),
      '#description' => $this->t('Titulo del Bloque'),
      '#default_value' => isset($config['block_header_title']) ? $config['block_header_title'] : '',
    );

    $form['block_header_text'] = array(
      '#type' => 'textarea',
      '#title' => $this->t('Descripción'),
      '#description' => $this->t('Descripción del bloque'),
      '#default_value' => isset($config['block_header_text']) ? $config['block_header_text'] : '',
    );

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function blockSubmit($form, FormStateInterface $form_state) {
    parent::blockSubmit($form, $form_state);
    $values = $form_state->getValues();
    $this->configuration['block_header_title'] = $values['block_header_title'];
    $this->configuration['block_header_text'] = $values['block_header_text'];
    $this->configuration['block_header_title'] = $form_state->getValue('block_header_title');
    $this->configuration['block_header_text'] = $form_state->getValue('block_header_text');
  }
}

This is the structure of the directory containing the module.

My module structure

What am I doing wrong?

0

2 Answers 2

4

Hooks go inside the .module file.

block_header.module

<?php

/**
 * Implements hook_preprocess_HOOK()
 */
function block_header_preprocess_block(&$variables) {
  if ($variables['plugin_id'] == 'block_header') {
    $variables['#attached']['library'][] = 'block_header/block_header';
  }
}

Just FYI, this did not work:

    $variables['elements']['#attached']['library'][] = 'block_header/block_header';

block_header.libraries.yml

block_header:
  version: 1.x
  css:
    theme:
      css/block_header.css: {}
5
  • Thank you very much!!! this *.module file worked!!! Thank you for your time! Commented Jan 14, 2018 at 21:10
  • @Hawk I think Clive's answer is better for your own custom block case.
    – No Sssweat
    Commented Jan 14, 2018 at 23:06
  • I disagree with your prior comment, may I? And if yes: why not? Commented Jan 22, 2018 at 21:40
  • I disagree with your prior comment, may I? yes, you may.
    – No Sssweat
    Commented Jan 23, 2018 at 1:39
  • I agree with No Sssweat, Clive's answer is more appropriate. preprocess_block is heavy handed for just attaching a stylesheet to a particular block. It's going to run for every block in the module.
    – TedMilker
    Commented Apr 14, 2021 at 19:44
4

The attachment should be on the block itself:

$block = [
        '#attached'=> ['library' => ['block_header/block_header']],
        'title' => array
        (
         '#prefix' => '<div class="title"><p>', /* HERE I ADD THE CSS TAGS */
         '#suffix' => '</p></div>',
         '#markup' => t('@title', array('@title' => $title,)),
        ),
        'description' => array
        (
         '#prefix' => '<div class="descp"><p>', /* HERE I ADD THE CSS TAGS */
         '#suffix' => '</p></div>',
         '#markup' => t('@descp', array('@descp' => $descp,))
        ),
    ];

And remember YAML is sensitive to white space, make sure your libraries file is formatted correctly:

block_header:
  version: 1.x
  css:
    theme:
      css/block_header.css: {}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.