定义一个Block
假设你的模块名叫: nice_menus
你需要创建以下目录: nice_menus/src/Plugin/Block/ 并且文件名要包含类名比如: NiceMenusBlock (nice_menus/src/Plugin/Block/NiceMenusBlock.php)
定义BLock代码
/** * @file * Contains \Drupal\nice_menus\Plugin\Block\NiceMenusBlock. */ namespace Drupal\nice_menus\Plugin\Block; use Drupal\block\BlockBase; use Drupal\Component\Annotation\Plugin; use Drupal\Core\Annotation\Translation; // Drupal 8中的Block信息是以注释的方式来定义的, 以下这段注释里面就是定义此Block信息 /** * Provides a Nice menus block. * * @Block( * id = "nice_menus_block", * admin_label = @Translation("Nice menus"), * module = "nice_menus" * ) */ class NiceMenusBlock extends BlockBase { }
ID属性是Block的机器名, 也是此BLock的唯一标示符,
设置表单配置
/** * @file * Contains \Drupal\nice_menus\Plugin\Block\NiceMenusBlock. */ namespace Drupal\nice_menus\Plugin\Block; use Drupal\block\BlockBase; use Drupal\Component\Annotation\Plugin; use Drupal\Core\Annotation\Translation; /** * Provides a Nice menus block. * * @Block( * id = "nice_menus_block", * admin_label = @Translation("Nice menus"), * ) */ class NiceMenusBlock extends BlockBase { /** * 定义表单 * Overrides \Drupal\block\BlockBase::blockForm(). */ public function blockForm($form, &$form_state) { // 读取配置. $configuration = $this->configuration; $form['testfield'] = array( '#type' => 'textfield', '#title' => t('Menu name'), '#default_value' => isset($configuration['testfield']) ? $configuration['testfield'] : '', ); return $form; } /** * 保存表单配置的值 * Overrides \Drupal\block\BlockBase::blockSubmit(). */ public function blockSubmit($form, &$form_state) { $this->setConfigurationValue('testfield', $form_state['values']['testfield']); } }
BLOCK的输出
/** * @file * Contains \Drupal\nice_menus\Plugin\Block\NiceMenusBlock. */ namespace Drupal\nice_menus\Plugin\Block; use Drupal\block\BlockBase; use Drupal\Component\Annotation\Plugin; use Drupal\Core\Annotation\Translation; /** * Provides a Nice menus block. * * @Block( * id = "nice_menus_block", * admin_label = @Translation("Nice menus"), * ) */ class NiceMenusBlock extends BlockBase { /** * 定义表单 * Overrides \Drupal\block\BlockBase::blockForm(). */ public function blockForm($form, &$form_state) { // 读取配置. $configuration = $this->configuration; $form['testfield'] = array( '#type' => 'textfield', '#title' => t('Menu name'), '#default_value' => isset($configuration['testfield']) ? $configuration['testfield'] : '', ); return $form; } /** * 保存表单配置的值 * Overrides \Drupal\block\BlockBase::blockSubmit(). */ public function blockSubmit($form, &$form_state) { $this->setConfigurationValue('testfield', $form_state['values']['testfield']); } /** * BLock输出, 这里只输出配置的值 * {@inheritdoc} */ public function build() { return $this->configuration['testfield']; } }
Taxonomy upgrade extras