You are here

function content_calendar_form_node_form_alter in Content Planner 8

Implements hook_form_BASE_FORM_ID_alter().

File

modules/content_calendar/content_calendar.module, line 73
Contains content_calendar.module.

Code

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

  // If the user is on a form to add a new node.
  if (\Drupal::routeMatch()
    ->getRouteName() == 'node.add') {

    // Get Node Type from Route.
    $node_type = \Drupal::routeMatch()
      ->getParameter('node_type');

    /**
     * @var $content_type_config_service \Drupal\content_calendar\ContentTypeConfigService
     */
    $content_type_config_service = \Drupal::service('content_calendar.content_type_config_service');

    // If there is a creation date in the query string.
    if ($content_type_config_service
      ->loadEntityByContentType($node_type
      ->id()) && \Drupal::request()->query
      ->has('publish_on')) {

      // Get date from query string.
      $date = \Drupal::request()->query
        ->get('publish_on');

      // If the date is a valid MySQL Date.
      if (DateTimeHelper::dateIsMySQLDateOnly($date)) {

        // Check scheduler for default time
        $scheduler_config = \Drupal::config('scheduler.settings');
        $default_time = FALSE;
        if ($scheduler_config
          ->get('allow_date_only')) {
          $default_time = $scheduler_config
            ->get('default_time');
        }

        // Create DrupalDateTime object.
        if ($default_time) {
          $datetime = DrupalDateTime::createFromFormat('Y-m-d H:i:s', $date . ' ' . $default_time);
        }
        else {
          $datetime = DrupalDateTime::createFromFormat('Y-m-d', $date);
        }

        // Assign date to the created field.
        $form['created']['widget'][0]['value']['#default_value'] = $datetime;

        // Assign date to the scheduler date, if it exists.
        if (\Drupal::currentUser()
          ->hasPermission('schedule publishing of nodes')) {
          if (array_key_exists('publish_on', $form)) {
            $form['publish_on']['widget'][0]['value']['#default_value'] = $datetime;
          }
        }
      }
    }
  }
}