Drupal 8 access views field from a custom views field handler

Public

From the Enzo's post here http://enzolutions.com/articles/2015/10/11/how-to-include-php-code-in-dr... After you created your module and your custom views field handler with drupal console command $ drupal generate:plugin:views:field now you may wondering how can I access to my drupal views fields ?
Now here's how:

</> CopyGet raw version
php
  1. /**
  2.   * {@inheritdoc}
  3.   */
  4. public function render(ResultRow $values) {
  5. dpm(array_keys($this->view->field));
  6. /*
  7. * The following attributes match exact the same views fields.
  8. *
  9. Array
  10. (
  11.   [0] => nid
  12.   [1] => field_image
  13.   [2] => title
  14.   [3] => field_short_description
  15.   [4] => sub_service_more_info_link_views_field
  16.   [5] => phpviews_field
  17. )
  18. */
  19. // To access each field use:
  20. dpm($this->view->field['nid']->original_value->__toString()); ///< Output: 37
  21. dpm($this->view->field['title']->original_value->__toString()); ///< Output: Title Article A
  22. dpm($this->view->field['field_image']->original_value->__toString()); ///< Output: <img src... html...
  23. dpm($this->view->field['field_short_description']->original_value->__toString()); ///< Ouput: Loreum Ipsum generate Text
  24. dpm($this->view->field['sub_service_more_info_link_views_field']->original_value__toString()); ///< Output: (in my case I return ['#markup' => 'Hello World']; so it prints 'hello world' message
  25. /* Note! use defensive programming like if (!empty($this->view->field['field_image']->original_value)) Because value may be empty! and if you don't use it you may encounter a fatal error */
  26. }

Comments