Skip to content
Snippets Groups Projects

Add a views field handle rthat is NOT broken and will handle all computed fields for nodes

3 files
+ 128
0
Compare changes
  • Side-by-side
  • Inline
Files
3
+ 93
0
<?php
/**
* @file
* Definition of Drupal\computed_field\Plugin\views\field\NodeComputedField
*/
namespace Drupal\computed_field\Plugin\views\field;
use Drupal\Core\Form\FormStateInterface;
use Drupal\computed_field\Entity\ComputedField;
use Drupal\views\Plugin\views\field\FieldPluginBase;
use Drupal\views\ResultRow;
use Stringable;
/**
* Field handler to display a selected computed field.
*
* @ingroup views_field_handlers
*
* @ViewsField("node_computed_field")
*/
class NodeComputedField extends FieldPluginBase {
/**
* @{inheritdoc}
*/
public function query() {
// Leave empty to avoid a query on this field.
}
/**
* Define the available options
* @return array
*/
protected function defineOptions() {
$options = parent::defineOptions();
$options['computed_field'] = ['default' => ''];
return $options;
}
/**
* Provide the options form.
*/
public function buildOptionsForm(&$form, FormStateInterface $form_state) {
/** @var \Drupal\computed_field\ComputedFieldManager $computedFieldManager */
$computedFieldManager = \Drupal::service('plugin.manager.computed_field');
// $entity_type_node = \Drupal::entityTypeManager()->getDefinition('node');
// $automatic_plugins = $computedFieldManager->getAutomaticPlugins($entity_type_node);
$plugins = $computedFieldManager->getDefinitions();
$options = [];
foreach ($plugins as $id => $definition) {
$options[$id] = $definition['label'];
}
$form['computed_field'] = array(
'#title' => $this->t('Computed field to use'),
'#type' => 'select',
'#default_value' => $this->options['computed_field'],
'#options' => $options,
'#description' => $this->t('Computed fields not relevant to the content types available on this view will still be shown here but will not work. No configuration for the computed field is currently possible.')
);
parent::buildOptionsForm($form, $form_state);
}
/**
* @{inheritdoc}
*/
public function render(ResultRow $values) {
$node = $this->getEntity($values);
$computed_field_plugin_id = $this->options['computed_field'];
$computedFieldManager = \Drupal::service('plugin.manager.computed_field');
$instance = $computedFieldManager->createInstance($computed_field_plugin_id);
$computed = $instance->computeValue($node, new ComputedField([], 'computed_field'));
$build = [];
foreach ($computed as $index => $value) {
if (is_string($value) || is_object($value)) {
// Protect from fatal errors by making sure any object we get is stringable.
if (is_object($value) && !($value instanceof Stringable)) {
continue;
}
// All strings need to be renderable arrays.
$build[$index] = ['#markup' => $value];
}
else {
// It is probably a render array or hopefully somehow renderable.
$build[$index] = $value;
}
}
return $build;
}
}
Loading