0

I thank you first for reading my question.

I want to make a query to the database and display data in a custom block in Drupal 8.

I have tried different ways without success:

<?php

namespace Drupal\mi_modulo\Plugin\Block;

use Drupal\Core\Block\BlockBase;

/**
 * Bloque que muestra una lista de productos
 * @Block(
 *   id = "get_products",
 *   admin_label = @Translation("get productos")
 * )
 */
class getProducts extends BlockBase {
    /**
     * {@inheritdoc}
     */

    public function build() {
        $db = \Drupal::database();
        $data = $db->select('products','t')->fields('t')->execute();

        return array(
            '#theme' => 'mi_modulo',
            '#descripcion' => 'Lista de productos',
            '#nodos' => $data
        );
    }
}
baikho
  • 5,203
  • 4
  • 40
  • 47
Brian
  • 1,295
  • 14
  • 25
  • Is there a specific reason to use the db->select() ? If it's content you want you can just use the EntityTypeManager – VJamie Sep 07 '16 at 07:32
  • Possible duplicate of [How to create a query in Drupal 8](http://stackoverflow.com/questions/33944735/how-to-create-a-query-in-drupal-8) – VJamie Sep 07 '16 at 12:37
  • I did not have some concepts about drupal 8 fix my problem using content types and views of drupal – Brian Sep 07 '16 at 13:43
  • You're gonna have to be more specific. Are "products" custom entities, content types, taxonomies? – VJamie Sep 07 '16 at 14:35
  • I created a new content type called "products", customize the required fields, after publishing information (content and image), I created a new view (admin / structure / views) and personalize as wanted it to look on the page. without modifying the core of drupal! – Brian Sep 07 '16 at 15:35

1 Answers1

0

Alright if I understand correctly you want to get your view into your block. Now there are a couple of options here:

  1. You can just go to the view and create your block there, then put it where you please.
  2. If you really want to have it in a custom block you can use the views_embed_view('view_name') function. I'll explain option 2 in code below.

This will embed the view into your block and display it just as you configured it in the view.

public function build(){
   return views_embed_view('name_of_your_view');
}
VJamie
  • 616
  • 3
  • 14