<?php

/**
 * @file
 * Provides a configuration option for the title of the node add pages.
 */

/**
 * Implements of hook_form_alter().
 */
function node_add_title_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'node_type_form') {
    // Add configuration options to the content type configuration form.
    $form['submission']['node_add_title'] = array(
      '#type' => 'textfield',
      '#title' => t('Node Add page title'),
      '#default_value' => variable_get('node_add_title_' . $form['#node_type']->type, ''),
      '#description' => t('Sets the title of the page where new nodes are created. Leave blank to use Drupal\'s default.'),
      '#weight' => 49,
    );
    $form['submission']['node_add_title_edit'] = array(
      '#type' => 'textfield',
      '#title' => t('Node Edit page title'),
      '#default_value' => variable_get('node_add_title_edit_' . $form['#node_type']->type, ''),
      '#description' => t('Sets the title of the page where existing nodes are edited. You can use [NODETITLE] including the square brackets as a wildcard. Leave blank to use Drupal\'s default.'),
      '#weight' => 50,
    );
  }
  if (isset($form['#node_edit_form'])) {
    // We are editing or adding new node.
    $node_add_title = variable_get('node_add_title_' . $form['#node']->type, '');
    if (!isset($form['#node']->nid) && isset($form['#node']) && !empty($node_add_title)) {
      // New node.
      drupal_set_title($node_add_title);
    }
    $node_add_title_edit = variable_get('node_add_title_edit_' . $form['#node']->type, '');
    if (isset($form['#node']->nid) && !empty($node_add_title_edit)) {
      // Editing an existing node.
      if (strpos($node_add_title_edit, '[NODETITLE]') !== FALSE) {
        // There is a wildcard for the title.
        $node_add_title_edit = str_replace('[NODETITLE]', $form['#node']->title, $node_add_title_edit);
      }
      drupal_set_title($node_add_title_edit);
    }
  }
}
