You are here

public function GrantsForm::submitForm in Nodeaccess 8

Same name and namespace in other branches
  1. 8.2 src/Form/GrantsForm.php \Drupal\nodeaccess\Form\GrantsForm::submitForm()

Form submission handler.

Parameters

array $form: An associative array containing the structure of the form.

\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.

Overrides FormInterface::submitForm

File

src/Form/GrantsForm.php, line 308

Class

GrantsForm
Builds the configuration form.

Namespace

Drupal\nodeaccess\Form

Code

public function submitForm(array &$form, FormStateInterface $form_state) {
  $db = \Drupal::database();

  // Update configuration.
  $values = $form_state
    ->getValues();
  $nid = $values['nid'];
  $grants = [];
  $node = Node::load($nid);
  foreach ([
    'uid',
    'rid',
  ] as $type) {
    $realm = 'nodeaccess_' . $type;
    if (isset($values[$type]) && is_array($values[$type])) {
      foreach ($values[$type] as $gid => $line) {
        $grant = [
          'gid' => $gid,
          'realm' => $realm,
          'grant_view' => empty($line['grant_view']) ? 0 : $line['grant_view'],
          'grant_update' => empty($line['grant_update']) ? 0 : $line['grant_update'],
          'grant_delete' => empty($line['grant_delete']) ? 0 : $line['grant_delete'],
        ];
        if ($grant['grant_view'] || $grant['grant_update'] || $grant['grant_delete']) {
          $grants[] = $grant;
        }
      }
    }
  }

  // Save role and user grants to our own table.
  $db
    ->delete('nodeaccess')
    ->condition('nid', $nid)
    ->execute();
  foreach ($grants as $grant) {
    $id = $db
      ->insert('nodeaccess')
      ->fields([
      'nid' => $nid,
      'gid' => $grant['gid'],
      'realm' => $grant['realm'],
      'grant_view' => $grant['grant_view'],
      'grant_update' => $grant['grant_update'],
      'grant_delete' => $grant['grant_delete'],
    ])
      ->execute();
  }
  \Drupal::entityTypeManager()
    ->getAccessControlHandler('node')
    ->acquireGrants($node);
  \Drupal::messenger()
    ->addMessage($this
    ->t('Grants saved.'));
  $tags = [
    'node:' . $node
      ->id(),
  ];
  Cache::invalidateTags($tags);
}