Custom blocks not working in Drupal 8

2019-08-13 18:10发布

I'm building a module with custom block in Drupal 8 beta 9. When I create a block in my module I'm placing it in src\Plugin\Block directory. The block show in 'Block structure' list, but when I press link to add it, nothing happens. I reviewed my code 10 times, tried to put my files into core module's directories (only for test obviously), tried to put some core block files to my directory, to copy-paste code. None of this works. Here is a code of my block file:

<?php
/**
 * @file
 * Contains \Drupal\internetdevels\Plugin\Block\TestBlock.
 */

namespace Drupal\internetdevels\Plugin\Block;
use Drupal\Core\Block\BlockBase;

/**
 * Provides 'my custom' block.
 *
 * @Block(
 *   id = "my_custom_block",
 *   admin_label = @Translation("My Custom Block"),
 *   category = @Translation("System"),
 * )
 */
class TestBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
    return array('#markup' => 'hello world');
  }

}

7条回答
Luminary・发光体
2楼-- · 2019-08-13 19:03

For future visitors:
For me the problem was solved when I changed the class name to EXACTLY the same as the file name (provided the file name is only small letters or underscore, otherwise first rename the file then match the class name to the file name.)

Example: WRONG FILENAME & class name:
*/TestBlock.php

<?php
// import & dependancy code
class TestBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
    return array('#markup' => 'hello world');
  }

}

RIGHT FILENAME & class name:
*/test_block.php

<?php
// code
class test_block extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
    return array('#markup' => 'hello world');
  }

}
查看更多
登录 后发表回答