1

I would like to display a node as a block in Drupal 8, but I don't know how to do this. I know in Drupal 7 I could use the Nodeblock module to accomplish this task, but there isn't a Drupal 8 version of it (and it looks like that there never will be).

Can this be accomplished using another module that I am not aware of?

  • 5
    Create a view of content items. Filter by the node. Make a block display. – mradcliffe Dec 12 '16 at 2:36
2

You can add a file to your module at src/Plugin/Block/YourBlock.php

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

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

  /**
   * {@inheritdoc}
   */
  public function build() {

    $nid = 2;
    $entity_type = 'node';
    $view_mode = 'teaser';

    $view_builder = \Drupal::entityTypeManager()->getViewBuilder($entity_type);
    $storage = \Drupal::entityManager()->getStorage($entity_type);
    $node = $storage->load($nid);
    $build = $view_builder->view($node, $view_mode);

    return $build;

  }

  ...

I'm sure with a little effort you can continue this by using blockForm, blockSubmit to set the node id/type/view_mode etc.

  • Thanks, this looks pretty straight forward to implement. I am surprised no one has created a module for this already. – user5013 Dec 12 '16 at 4:35
  • 2
    @user5013 I am surprised no one has created a module for this already. It's called Views. – No Sssweat Dec 12 '16 at 8:29
  • @NoSssweat Yes you can do it in views, but it is not very user friendly for site editors to use (and gives them too much power). I am looking for something that allow site editors to use easily. – user5013 Dec 12 '16 at 18:55
  • Here is detailed tutorial for developing a "nodeblock" like module for Drupal 8 : sitepoint.com/… – Renrhaf Jun 10 '17 at 7:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.