Create a Drupal 8 block in seconds

Blocs de pierres empilées
Thème

We continue to explore the possibilities offered by the Console module and will discover how to build a Drupal 8 block with a few command and in a very short time.

If you have not yet installed console, you can read this post Create a Drupal module 8 in 30 seconds.

We will generate a block that will allow us to display a welcome text and the name of the user logged in. Execute the following command

cd /path/to/drupal8folder
bin/console generate:plugin:block

 

As you may have noticed, blocks in Drupal 8 are now plugins. And because of this we generate a block type plugin.

Génération d'un bloc Durpal 8

As always, we must indicate in which module we will generate the code (in our example, our module entitled example, original eh?).

Then we define respectively the block name, label and ID. We also have the ability to associate a form with the block that will allow us to associate specific fields. In our example, we create a text field that will contain the welcome message.

Our command will generate a file in the directory src/Plugin/Block entitled CurrentUser.php. Consult the code generated.

 /**
 * @file
 * Contains Drupal\example\Plugin\Block\CurrentUser.
 */

namespace Drupal\example\Plugin\Block;

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

/**
 * Provides a 'CurrentUser' block.
 *
 * @Block(
 *  id = "current_user",
 *  admin_label = @Translation("current_user")
 * )
 */
class CurrentUser extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
    return [
      '#markup' => 'current_user',
    ];
  }

  /**
   * Overrides \Drupal\block\BlockBase::blockForm().
   */
  public function blockForm($form, FormStateInterface $form_state) {
    $form['welcome_text'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Welcome text'),
      '#description' => $this->t(''),
      '#default_value' => isset($this->configuration['welcome_text']) ? $this->configuration['welcome_text'] : '',
    ];
    return $form;
  }

  /**
   * Overrides \Drupal\block\BlockBase::blockSubmit().
   */
  public function blockSubmit($form, FormStateInterface $form_state) {
    $this->configuration['welcome_text'] = $form_state->getValue('welcome_text');
  }
} 

We can modify the build() function to retrieve the account of the logged in user and display our welcome message that we can configure in the block's parameters.

   public function build() {
    // Fetch current user.
    $account = \Drupal::currentUser();
    return [
      '#markup' => t('@welcome @username',
        array(
          '@welcome' => $this->configuration['welcome_text'],
          '@username' => user_format_name($account)
        )
      ),
    ];
  } 

And it remains for us to instantiate our block from the Administration page and position it for example in the first sidebar.

Page d'administration des blocs Drupal 8

 

Configuration d'un bloc Drupal 8

And our result.

Affichage d'un bloc Drupal 8 personnalisé

Devilishly effective, do not you think ? This is almost self-explanatory, but feel free.

Ajouter un commentaire