You are here

public function RequiredByRole::requiredFormElement in Required by role 8

Form element to build the required property.

Parameters

\Drupal\Core\Field\FieldDefinitionInterface $field: The field instance

Return value

array Form element

File

src/Plugin/Required/RequiredByRole.php, line 74
Contains \Drupal\required_by_role\Plugin\Required\RequiredByRole.

Class

RequiredByRole
Plugin annotation @Required( id = "required_by_role", admin_label = @Translation("Required by role"), label = @Translation("Required by role"), description = @Translation("Required based on current user roles.") )

Namespace

Drupal\required_by_role\Plugin\Required

Code

public function requiredFormElement(FieldDefinitionInterface $field) {
  $roles = user_roles();
  $default_value = $field
    ->getThirdPartySetting('required_api', 'required_plugin_options') ?: [];
  unset($roles[AccountInterface::AUTHENTICATED_ROLE]);
  $options = [];
  foreach ($roles as $role) {
    $options[$role
      ->id()] = [
      'name' => $role
        ->label(),
    ];
  }
  $header = [
    'name' => [
      'data' => t('Role'),
    ],
  ];
  $element = [
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $options,
    '#default_value' => $default_value,
    '#js_select' => TRUE,
    '#multiple' => TRUE,
    '#empty' => t('No roles available.'),
    '#attributes' => [
      'class' => [
        'tableselect-required-by-role',
      ],
    ],
  ];
  return $element;
}