Last active
June 14, 2019 07:49
-
-
Save PSF1/ae4518df24fcbdd4c087ad4029385efa to your computer and use it in GitHub Desktop.
How to alter the content of a custom text field in a view in Drupal 8.7.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* @file | |
* Primary module hooks for alter_custom_text_views_field module. | |
* | |
* To use in a module called "alter_custom_text_views", in Drupal 8. | |
* | |
* @DCG | |
* This file is no longer required in Drupal 8. | |
* @see https://www.drupal.org/node/2217931 | |
*/ | |
use Drupal\views\Plugin\views\cache\CachePluginBase; | |
use Drupal\views\ViewExecutable; | |
/** | |
* Prepare the custom field to be changed. | |
* | |
* Implements hook_views_pre_render(); | |
* | |
* @see https://drupal8.ovh/en/tutoriels/238/alter-a-view-edit-view-result-programmatically | |
* @see https://www.jeffgeerling.com/blog/2019/rendering-twig-templates-programmatically-drupal-8 | |
*/ | |
function alter_custom_text_views_field_views_pre_render(ViewExecutable $view) { | |
if ($view->id() == 'view_machine_name' && $view->current_display == 'view_display_machine_name') { | |
$customField = $view->field['field_machine_name']; | |
// Don't render original template. | |
$customField->options["alter"]["text"] = 'empty'; | |
} | |
} | |
/** | |
* Alter custom text field content. | |
* | |
* Implements hook_views_post_render(); | |
*/ | |
function alter_custom_text_views_field_views_post_render(ViewExecutable $view, &$output, CachePluginBase $cache) { | |
if ($view->id() == 'view_machine_name' && $view->current_display == 'view_display_machine_name') { | |
// In this example I alter a leafleft display map. | |
$points = &$output["#rows"]["#attached"]["drupalSettings"]["leaflet"]["leaflet-map-view-beacons-list-attachment-1"]["features"]; | |
foreach ($points as &$point) { | |
// We load the template to render by myself. | |
$markup = twig_render_template(drupal_get_path('module', 'alter_custom_text_views_field') . '/templates/pop-up-content.html.twig', [ | |
// Add here the twig variables to be enabled. | |
'nid' => $point['entity_id'], | |
'field_display_title_1' => 'field_display_title_1', | |
'field_beacon_link' => 'field_beacon_link', | |
// Needed to prevent notices when Twig debugging is enabled. | |
'theme_hook_original' => 'not-applicable', | |
]); | |
// Cast to string since twig_render_template returns a Markup object. | |
$point['popup'] = (string) $markup; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment