You are here

function onlyone_form_node_form_alter in Allow a content type only once (Only One) 8

Same name and namespace in other branches
  1. 7 onlyone.module \onlyone_form_node_form_alter()

Implements hook_form_BASE_FORM_ID_alter() for node_form.

File

./onlyone.module, line 186
Contains onlyone.module.

Code

function onlyone_form_node_form_alter(&$form, FormStateInterface &$form_state, $form_id) {

  // Getting the configured content types.
  $onlyone_content_types = \Drupal::config('onlyone.settings')
    ->get('onlyone_node_types');
  $onlyone_redirect = \Drupal::config('onlyone.settings')
    ->get('onlyone_redirect');

  // Getting the node.
  $node = $form_state
    ->getFormObject()
    ->getEntity();

  // Verifying if the new node should by onlyone and if we are trying to create
  // a new node.
  if (isset($onlyone_content_types) && in_array($node
    ->getType(), $onlyone_content_types) && $node
    ->isNew()) {

    // If we have one node, then redirect to the edit page.
    $nid = \Drupal::service('onlyone')
      ->existsNodesContentType($node
      ->getType());
    if ($nid) {

      // Creating the url.
      if ($onlyone_redirect) {
        $route = 'entity.node.edit_form';
      }
      else {
        $route = 'entity.node.canonical';
      }
      $url = Url::fromRoute($route, [
        'node' => $nid,
      ])
        ->toString();

      // Redirecting to edit the only one node for this content type.
      $response = new RedirectResponse($url);
      $response
        ->send();
    }
  }
}