7

I created a view with a "Custom text" field and want to get this field programmatically in Drupal 8.

I have:

$view = Views::getView('my_view');
$view->execute();
foreach($view->result as $row){
    $node = Node::load($row->nid);
    // Get here the view custom field with label "An example view field".
}

The $row field doesn't have the fields, nor the $node.

A screenshot of the view: enter image description here

I now have:

$customField = $view->field['nothing'];

customField is an instance of Drupal\views\Plugin\views\field\Custom.

dpm($customField->render($row));

This returns class Drupal\views\Render\ViewsRenderPipelineMarkup with protectecd string with the same markup: {{ title }} test.

Thanks,

6 Answers 6

2

Please install the devel module

Go to /drupal8/devel/php

You can try:

$view = \Drupal\views\Views::getView('my_view');
$view->execute();

foreach($view->result as $row){
dpm($row->_entity->get('Custom text')->getValue());
}

note: change "Custom text" by machine name of the field

if your result is similar to:

Array
(
    [0] => Array
        (
            [value] => 43
        )

)

you can access the field with

$row->_entity->get('Custom text')->value

if your result is similar to:

Array
(
    [0] => Array
        (
            [target_id] => 1
        )

)

you can access the field with

$row->_entity->get('Custom text')->target_id
2
  • 2
    Hi, I want to get the custom field of the row generated by the field. Not the field of the node itself. See screenshot in my post.
    – s3go11
    Nov 27, 2017 at 20:30
  • @s3go11, i feel your pain. I am trying to find the D8 version of views_get_view_result (which exists in D8 but doesn't do anything useful like in D7). All the answers here referring to $node; do not understand the question.
    – liquidcms
    Dec 2, 2019 at 6:04
2

You should have something like

//already loaded
$node = $row->_entity;

Best way to get properties easily is probably to inspect variables with xdebug

If it is some king of header/footer, you can get the rendered array this way :

$view = \Drupal\views\Views::getView('Your view');
$view->execute();
/* @var $area \Drupal\views\Plugin\views\area\Text */
$area = reset($view->header); // $view->header['area'] or something else
$rendered = $area->render(); // rendered array

Ok, then :

$view = \Drupal\views\Views::getView('YOUR VIEW');
$view->execute('YOUR DISPLAY ID OR DEFAULT');
$nothing = $view->getHandler('YOUR DISPLAY ID OR DEFAULT','field', 'nothing');
$text = $nothing['alter']['text'];
7
  • Could you get nid with $row->_entity->id() ? Nov 27, 2017 at 12:38
  • No way to get the information from _entiity using print_r (memory exhausted). Something with bundle perhaps. I require something like \Drupal::entityManager()->getFieldDefinitions($entity_type_id, $bundle), but for views.
    – s3go11
    Nov 27, 2017 at 12:55
  • You should be able to get your text with something like : $row->_entity->get('field_text')->value, what about the id above ? Nov 27, 2017 at 12:58
  • I understand, you are not requiring $node's custom text but views custom text, right ? Nov 27, 2017 at 13:14
  • Hi, correct. When I inspect in the elements (HTML) of the results in view, I got "nothing" as unique class. There should be a way to get that "nothing" field value.
    – s3go11
    Nov 27, 2017 at 15:17
2

You can also use hook_preprocess_views_view_field in order to change your custom text field:

function hook_preprocess_views_view_field(&$variables) {
  if ($variables["view"]->id() == "VIEW_ID" && $variables["field"]->options["id"] == "nothing") {
    $doYourCalculation = "New Text";
    $variables["output"] = ViewsRenderPipelineMarkup::create($doYourCalculation);
  }
}
0

This is what I have, however, I feel there must be a better way to do this.

Some notes:

  • $view->render(); is critical, without it, it doesn't work
  • 'nothing' is the default name of custom field, adding additional fields will result 'nothing_1', 'nothing_2', etc. You can see the name when hovering over the field (in the link) or in the replacement patterns.
  • The value returned with a lot of \n in it. I'm replacing them here, but this can have unwanted side effects.

The code:

// The machine name of your view.
$viewname = 'name_of_the_view';

// Get the view.
$view = \Drupal\views\Views::getView($viewname);

// Display machine name.
$view->setDisplay('default');

// Execute the view.
$view->preExecute();
$view->execute();
$view->render();

foreach(array_keys($view->result) as $row_index){
  $custom_field = str_replace("\n", '', $view->field['nothing']->tokenizeValue((string)$view->field['nothing']->original_value, $row_index));
}
-2

I had a similar problem and the only way worked for me was the following:

function MODULENAME_preprocess_views_view_fields(&$vars) {
  $view = $vars['view'];
  if(isset($view) && $view->id() === 'test') {
    foreach ($view->field as $id => $field) {
      // change the global custom text content for a specific
      // result row.
      if ($vars['row']->nid == 149) {
        $vars['fields']['nothing']->content = 'some new text';
      }
    }
  }
}
1
  • The posted question is how to get a view's rendered field in code. Not within a view's hooks.
    – liquidcms
    Dec 2, 2019 at 6:01
-2
  $view = \Drupal\views\Views::getView( 'view_name' );
  $view->execute();
  foreach ($view->result as $row) {
  kint($row->_entity->get( 'nid' )->getValue()[0]['value']);
  }
1
  • Hey, could you please add some explanation of what this code actually does. Or what else you are trying to suggest. It's hard to distinguish if you have the same problem or if this is an actual answer ;)
    – leymannx
    Aug 2, 2018 at 12:38

Your Answer

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

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