D8 Plugins - pierregermain/MyDrupal GitHub Wiki
Más info en: Block API
- Se crean en
/src/Plugin/Block/SimpleBlock.php
- Extendemos de BlockBase que implementa BlockPluginInterface
- Obliga a usar la annotation
@Block
- Obliga a implementar el método build.
- Obliga a usar la annotation
Ejemplo:
namespace Drupal\mymodule\Plugin\Block;
use Drupal\Core\Block\BlockBase;
/**
* Provides a Simple example block.
*
* @Block(
*
id = "mymodule_simple_block",
*
admin_label = @Translation("Mymodule Simple Block")
* )
*/
class SimpleBlock extends BlockBase {
public function build() {
return [
'#markup' => '<span>' . $this->t('Sample block') . '</span>',
];
}
}
- Usamos el método buildConfigurationForm
public function defaultConfiguration() {
return [
'label' => 'Custom Title',
'label_display' => FALSE,
];
}
- Añadimos el siguiente método con su
- método de validación
- submit
- default configuration
- La info se guarda en el objeto de configuración
block.block.simpleblock
- Este código se añade directamente al bloque que estaría en la ruta
src/Plugin/Block
public function blockForm($form, FormStateInterface $form_state) {
$form['mymodule_block_message'] = array(
'#type' => 'textfield',
'#title' => $this->t('Display message'),
'#default_value' => $this->configuration['block_message'],
);
$range = range(1, 10);
$form['mymodule_node_number'] = array(
'#type' => 'select',
'#title' => $this->t('Number of nodes'),
'#default_value' => $this->configuration['node_number'],
'#options' => array_combine($range, $range),
);
return $form;
}
public function blockValidate($form, FormStateInterface $form_state) {
if (strlen($form_state->getValue('mymodule_block_message')) < 10) {
$form_state->setErrorByName('mymodule_block_message', $this->t('The text must be at least 10 characters long'));
}
}
public function blockSubmit($form, FormStateInterface $form_state) {
$this->configuration['block_message'] = $form_state->getValue('mymodule_block_message');
$this->configuration['node_number'] = $form_state->getValue('mymodule_node_number');
}
public function defaultConfiguration() {
return array(
'block_message' => 'List of highlighted nodes',
'node_number' => 5,
);
}
para usar la configuración desde el build:
public function build() {
$node_number = $this->configuration['node_number'];
$block_message = $this->configuration['block_message'];
// 1
$build[] = [
'#markup' => '<h3>' . $this->t($block_message) . '</h3>',
];
// 2a
$result = $this->database->select('forcontu_node_highlighted', 'f')
->fields('f', ['nid'])
->condition('highlighted', 1)
->orderBy('nid', 'DESC')
->range(0, $node_number)
->execute();
// 2b
$list = [];
$node_storage = $this->entityTypeManager->getStorage('node');
// 2c
foreach($result as $record) {
$node = $node_storage->load($record->nid);
$list[] = $node->toLink($node->getTitle())->toRenderable();
}
if (empty($list)) {
$build[] = [
'#markup' => '<h3>' . $this->t('No results found') . '</h3>',
];
} else {
// 2d
$build[] = [
'#theme' => 'item_list',
'#items' => $list,
'#cache' => ['max-age' => 0],
];
}
return $build;
}
- La clase plugin debe implementar ContainerFactoryPluginInterface
- Este ejemplo es un bloque que estaría en la ruta
src/Plugin/Block
Ejemplo:
//...
class HighlightedContentBlock extends BlockBase implements
ContainerFactoryPluginInterface {
protected $database;
protected $currentUser;
public function __construct(array $configuration,
$plugin_id,
$plugin_definition,
AccountInterface $current_user,
Connection $database) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->currentUser = $current_user;
$this->database = $database;
}
public static function create(ContainerInterface $container,
array $configuration,
$plugin_id,
$plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('current_user'),
$container->get('database')
);
}
public function build() {
//...
return $build;
}
// ...
}
Se suele añadir el siguiente método al bloque
protected function blockAccess(AccountInterface $account) {
return AccessResult::allowedIfHasPermission($account, 'access content');
}
- Ejemplos: bloque de búsqueda y el bloque de login de usuario
- Ver Cargar formularios sin ruta