Plugin API

& Blocks

Vad är plugins?

Drupal själva definierar det kort såhär

Plugins are small pieces of functionality that are swappable. Plugins that perform similar functionality are of the same plugin type.

Plugins are defined by modules: a module may provide plugins of different types, and different modules may provide their own plugins of a particular type.

Exempel på plugins i Drupal 8 Core

  • Bildeffekter

  • Block

  • Fält

  • WYSIWYG knappar

Block plugin


namespace Drupal\hello_world\Plugin\Block;

use Drupal\Core\Block\BlockBase;

/**
 * Provides a 'Hello' Block
 *
 * @Block(
 *   id = "hello_block",
 *   admin_label = @Translation("Hello block"),
 * )
 */
class HelloBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
    return [
      '#markup' => $this->t('Hello, World!'),
    ];
  }
}

Var placerar man plugins?

  • Placeras oftast i Plugin mappen.
  • Plugin mappen ska ligga i src.
  • Undermappen oftast samma namn som det man skapar plugin för.

Hur hämtar vi ut entiteter?

\Drupal::EntityTypeManager();

\Drupal::EntityQuery();

Låter oss hantera entiteter på en högre nivå. Vi kan ladda enskilda entiteter, hämta formulär, url:er m.m.

Låter oss skriva detaljerade förfrågningar för att hämta en eller flera entiteter. Ungefär som att skriva en SQL-query fast för en Drupal-entitet.

\Drupal::EntityTypeManager();

/**
 * Load a single entity.
 */
$color = \Drupal::entityTypeManager()
      ->getStorage('color')
      ->load('red');
/**
 * Load all entities.
 */
$colors = \Drupal::EntityTypeManager()
  ->getStorage('colors')
  ->loadMultiple();
/**
 * Load a entity form.
 */
$color_add_form = \Drupal::entityTypeManager()
  ->getFormObject('color', 'add');

\Drupal::EntityQuery();

/**
 * First perform the query to get the entity ids.
 */
$ids = \Drupal::entityQuery('movie')
  ->sort('rating', 'DESC')
  ->range(0, 5)
  ->execute();
/**
 * Then load the entities we found with the entity type manager.
 */
$movies = \Drupal::entityTypeManager()
  ->getStorage('movie')
  ->loadMultiple($ids);

Ladda noder med entity query

/**
 * First perform the query to load node ids.
 */
$ids = \Drupal::entityQuery('node')
  ->condition('type', 'article')
  ->condition('status', 1)
  ->sort('created', 'DESC')
  ->range(0, 10)
  ->execute();

/**
 * Then load the node entities we found with the entity type manager.
 */
$nodes = \Drupal::entityTypeManager()
  ->getStorage('node')
  ->loadMultiple($ids);

Dagens övningar!

  • Block som listar våra färger.

  • Block som listar de 5 populäraste filmerna.

  • Block med ett formulär.

Om vi hinner!

Cache i Drupal 8 och hur vi kan använda det till våra block!

Sammanfattning av dagen!

Frågor och Svar!

Min sista lektion

Drupal 8 - Blocks & Plugins

By Christoffer Palm

Drupal 8 - Blocks & Plugins

This presentation introduces us to the Plugin API in Drupal 8 and Block in particular.

  • 4,448