I am creating a custom views field and need it to have JS attached to it's on click functionality. When I get one views result, it works perfectly, but when I have multiple results, it only attaches to one of them. How do I get this to attach to all the result rows?
Below is the code for rendering the field and the js that gets attached. Any help is appreciated.
<?php
/**
* @file
* Contains \Drupal\msul_views_alert_management\Plugin\views\area\alertManagement.
*/
namespace Drupal\msul_views_alert_management\Plugin\views\field;
use Drupal\Core\Form\FormStateInterface;
use Drupal\views\Render\ViewsRenderPipelineMarkup;
use Drupal\views\ResultRow;
use Drupal\views\ViewExecutable;
use Drupal\views\Plugin\views\field\FieldPluginBase;
/**
* Defines a views field plugin.
*
* @ingroup views_field_handlers
*
* @ViewsField("alertFieldManagement")
*/
class alertFieldManagement extends FieldPluginBase {
/**
* {@inheritdoc}
*/
public function render(ResultRow $values) {
$output = array();
$uuid=((array)($values->_entity))[chr(0).'*'.chr(0).'values']['uuid']['x-default'];
$body=((array)($values->_entity))[chr(0).'*'.chr(0).'values']['body']['x-default'];
if(!isset($_COOKIE['EUA-'.$uuid]) || $_COOKIE['EUA-'.$uuid]!="Hidden"){
$output = [
'userAlert' => [
'#type' => 'container',
'#attributes' => [
'class' => ['user-alert'],
],
'userAlertClose' => [
'#type' => 'container',
'#attributes' => [
'uuid' => $uuid,
'class' => ['user-alert-close-button'],
],
'tempButton' => ['#markup' => 'X'],
],
'alertText' => [
'#markup' => check_markup($body[0]['value'],$body[0]['format']),
],
],
'#attached' => [
'library' => ['msul_views_alert_management/alert_field_management-js'],
'drupalSettings' => [
'msul_views_alert_management' => [
'uuid' => $uuid,
],
],
],
];
}
return $output;
}
//... other code here ...
}
( function ($, Drupal, drupalSettings){
uuid = drupalSettings.msul_views_alert_management.uuid;
while($('[uuid="'+uuid+'"]').length > 1){
$('[uuid="'+uuid+'"]').last().closest(".views-row").remove();
}
$('[uuid="'+uuid+'"]').on('click',
function() {
$(this).closest(".views-row").remove();
document.cookie = "EUA-"+uuid+"=Hidden;path=/;";
}
);
})(jQuery, Drupal, drupalSettings)