0

I want to create a view in Drupal 11, but I want to add the values for that view through code. How could this be done? I’ve tried it, but the view appears empty and I can’t see the values. Here’s a simple example:

File: custom_simple_data.module

<?php
/**
 * @file
 * Custom Simple Data - expose hard-coded rows to Views.
 */

/**
 * Implement hook_views_data().
 */
function custom_simple_data_views_data() {
  $data = [];

  $data['custom_simple_data']['table']['group'] = t('Custom Simple Data');
  $data['custom_simple_data']['table']['provider'] = 'custom_simple_data';
  $data['custom_simple_data']['table']['base'] = [
    'field' => 'id',
    'title' => t('Simple data'),
    'help' => t('Rows defined in code (id, name, count).'),
    // El query_id debe coincidir con el id del plugin ViewsQuery.
    'query_id' => 'custom_simple_data_query',
  ];

  // Campo ID (numérico)
  $data['custom_simple_data']['id'] = [
    'title' => t('ID'),
    'help' => t('Identifier'),
    'field' => ['id' => 'numeric'],
    'filter' => ['id' => 'numeric'],
    'sort' => ['id' => 'standard'],
  ];

  // Campo Name (string)
  $data['custom_simple_data']['name'] = [
    'title' => t('Name'),
    'help' => t('Nombre (string)'),
    'field' => ['id' => 'standard'],
    'filter' => ['id' => 'string'],
    'sort' => ['id' => 'standard'],
  ];

  // Campo Count (int)
  $data['custom_simple_data']['count'] = [
    'title' => t('Count'),
    'help' => t('Número entero'),
    'field' => ['id' => 'numeric'],
    'filter' => ['id' => 'numeric'],
    'sort' => ['id' => 'standard'],
  ];

  return $data;
}

File: CustomSimpleDataQuery:

<?php

namespace Drupal\custom_simple_data\Plugin\views\query;

use Drupal\views\ResultRow;
use Drupal\views\ViewExecutable;
use Drupal\views\Plugin\views\query\QueryPluginBase;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * @ViewsQuery(
 *   id = "custom_simple_data_query",
 *   title = @Translation("Custom simple data query"),
 *   help = @Translation("Provides rows defined in code (id, name, count).")
 * )
 */
class CustomSimpleDataQuery extends QueryPluginBase {

  public function __construct(array $configuration, $plugin_id, $plugin_definition) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
  }

  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static($configuration, $plugin_id, $plugin_definition);
  }

  /**
   * No hay tablas SQL reales.
   */
  public function ensureTable($table, $relationship = NULL) {
    return '';
  }

  /**
   * addField no necesita hacer nada especial para los campos virtuales.
   */
  public function addField($table, $field, $alias = '', $params = []) {
    return $field;
  }

  /**
   * Ejecuta la "consulta" y pone los ResultRow en $view->result.
   */
  public function execute(ViewExecutable $view) {
    $rows = [
      ['id' => 1, 'name' => 'Alpha', 'count' => 10],
      ['id' => 2, 'name' => 'Beta', 'count' => 25],
      ['id' => 3, 'name' => 'Gamma', 'count' => 42],
    ];

    foreach ($rows as $r) {
      $view_row = [
        'id' => $r['id'],
        'name' => $r['name'],
        'count' => $r['count'],
      ];

      $view->result[] = new ResultRow($view_row);
    }

    \Drupal::logger('custom_simple_data')->notice('Final $view->result: <pre>@result</pre>', ['@result' => print_r($view->result, TRUE),
    ]);
  }
}

Drupal::logger output ($view->result):

    Final $view->result:
Array
(
    [0] => Drupal\views\ResultRow Object
        (
            [_entity] => 
            [_relationship_entities] => Array
                (
                )

            [index] => 
            [id] => 1
            [name] => Alpha
            [count] => 10
        )

    [1] => Drupal\views\ResultRow Object
        (
            [_entity] => 
            [_relationship_entities] => Array
                (
                )

            [index] => 
            [id] => 2
            [name] => Beta
            [count] => 25
        )

    [2] => Drupal\views\ResultRow Object
        (
            [_entity] => 
            [_relationship_entities] => Array
                (
                )

            [index] => 
            [id] => 3
            [name] => Gamma
            [count] => 42
        )

)

The view was created using the new 'Simple data' option, and the new fields defined in the code were added.

enter image description here

enter image description here

But the view appears empty; nothing is displayed. I’ve tried many methods I found online. How can I display those values on a view page? Thanks.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.