You are here

function vapn_form_node_form_alter in View access per node 8

Implements hook_form_FORM_ID_alter().

File

./vapn.module, line 30
Contains vapn.module.

Code

function vapn_form_node_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

  // Make sure it's a valid type.
  if (!\Drupal::service('vapn.handler')
    ->checkIfContentTypeEnabled()) {

    // Not a VAPN form.
    return;
  }
  $form['vapn'] = array(
    '#type' => 'details',
    '#title' => t('View access per node'),
    '#group' => 'advanced',
    '#open' => FALSE,
  );
  $form['vapn']['description'] = array(
    '#prefix' => '<div class="form-item">',
    '#suffix' => '</div>',
    '#markup' => t('Select which roles can view this node.  Select none for default.'),
  );

  // Get the default roles.
  $default_roles = \Drupal::service('vapn.handler')
    ->getDefaultsForNode($form_state);
  $default_roles = $default_roles ? $default_roles : array();

  // Role checkboxes.
  $form['vapn']['vapn_roles'] = array(
    '#type' => 'checkboxes',
    '#title' => t('Select roles'),
    '#title_display' => 'invisible',
    '#options' => array(),
    '#default_value' => $default_roles,
  );

  // Get all user roles.
  $user_roles = user_roles(FALSE);

  // Get users that can bypass access control (skip anon - that would be weird).
  $user_node_bypass = user_roles(TRUE, 'bypass node access');
  $user_vapn_bypass = user_roles(FALSE, 'bypass vapn');

  // Remove the users that can bypass access control.
  $remain_user_roles = array_diff_key($user_roles, $user_node_bypass, $user_vapn_bypass);

  // Each non-bypass role.
  $defaults = [];
  foreach ($remain_user_roles as $role_id => $role_obj) {
    $form['vapn']['vapn_roles']['#options'][$role_id] = $role_obj
      ->label();
  }

  // Add submission handler.
  $form['actions']['submit']['#submit'][] = 'vapn_node_form_submit';
}