RoleBasedGlobalText.php in Views Role Based Global Text 8
File
src/RoleBasedGlobalText.php
View source
<?php
namespace Drupal\views_role_based_global_text;
use Drupal\Core\Form\FormStateInterface;
use Drupal\views\Plugin\views\area\Text;
class RoleBasedGlobalText extends Text {
protected function defineOptions() {
$options = parent::defineOptions();
$options['roles_fieldset']['default'] = FALSE;
return $options;
}
public function buildOptionsForm(&$form, FormStateInterface $form_state) {
parent::buildOptionsForm($form, $form_state);
$form['roles_fieldset'] = [
'#type' => 'details',
'#title' => $this
->t('Roles'),
];
$form['roles_fieldset']['roles'] = [
'#title' => $this
->t('Select Roles'),
'#type' => 'checkboxes',
'#options' => user_role_names(),
'#default_value' => $this->options['roles_fieldset']['roles'] ?? [],
'#description' => $this
->t('Only the checked roles will be able to access this value. If no role is selected, available to all.'),
];
}
public function render($empty = FALSE) {
$checked_roles = $this->options['roles_fieldset'] && is_array($this->options['roles_fieldset']['roles']) ? array_filter($this->options['roles_fieldset']['roles']) : [];
$user_roles = \Drupal::currentUser()
->getRoles();
if (empty($checked_roles) || array_intersect($user_roles, $checked_roles)) {
return parent::render($empty);
}
return [];
}
}