You are here

answers.module in Answers 8

Contains answers.module.

File

answers.module
View source
<?php

/**
 * @file
 * Contains answers.module.
 */
use Drupal\Core\Entity\EntityInterface;

/**
 * Implements hook_preprocess_HOOK().
 */
function answers_preprocess_node(&$variables) {
  if ($variables['node']
    ->bundle() == 'answers_question') {
    $values = [
      'title' => format_string('Answer to Question :nid', [
        ':nid' => $variables['node']
          ->id(),
      ]),
      'type' => 'answers_answer',
      'answers_related_question' => [
        $variables['node']
          ->id(),
      ],
    ];
    $node = \Drupal::entityTypeManager()
      ->getStorage('node')
      ->create($values);
    $form = \Drupal::entityTypeManager()
      ->getFormObject('node', 'default')
      ->setEntity($node);
    $form_array = \Drupal::formBuilder()
      ->getForm($form);
    $form_array['title']['widget'][0]['value']['#type'] = 'hidden';
    $variables['answer_form'] = drupal_render($form_array);
    $answers = views_embed_view('answers', 'block_1', $variables['node']
      ->id());
    $variables['answer_list'] = drupal_render($answers);
    $date_formatter = \Drupal::service('date.formatter');
    $variables['ago'] = $date_formatter
      ->formatTimeDiffSince($variables['node']
      ->getCreatedTime(), [
      'granularity' => 1,
    ]);
  }
  if ($variables['node']
    ->bundle() == 'answers_answer') {
    $date_formatter = \Drupal::service('date.formatter');
    $variables['ago'] = $date_formatter
      ->formatTimeDiffSince($variables['node']
      ->getCreatedTime(), [
      'granularity' => 1,
    ]);
  }
}

/**
 * Implements hook_menu_alter().
 */
function answers_menu_alter(&$items) {

  // Remove 'answers' from the 'add content' menu item in the 'navigation' menu.
  // Thanks to http://drupal.stackexchange.com/questions/17643/how-to-hide-a-content-type-on-the-node-add-page
  if (isset($items['node/add/answers-answer'])) {
    $items['node/add/answers-answer']['type'] = MENU_DEFAULT_LOCAL_TASK;
  }
}

/**
 * Implements hook_entity_delete().
 */
function answers_entity_delete(EntityInterface $entity) {
  if ($entity
    ->getEntityTypeId() == 'node' && $entity
    ->bundle() == 'answers_question') {
    $result = \Drupal::entityQuery('node')
      ->condition('type', 'answers_answer')
      ->condition('answers_related_question.target_id', $entity
      ->id())
      ->execute();
    entity_delete_multiple('node', $result);
  }
}

Functions

Namesort descending Description
answers_entity_delete Implements hook_entity_delete().
answers_menu_alter Implements hook_menu_alter().
answers_preprocess_node Implements hook_preprocess_HOOK().