You are here

custom_pub.module in Custom Publishing Options 8

Same filename and directory in other branches
  1. 6 custom_pub.module
  2. 7 custom_pub.module

File

custom_pub.module
View source
<?php

use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Field\Entity\BaseFieldOverride;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\custom_pub\Entity\CustomPublishingOption;

/**
 * Implements hook_help().
 *
 * @param $route_name
 * @param RouteMatchInterface $route_match
 *
 * @return string
 */
function custom_pub_help($route_name, RouteMatchInterface $route_match) {
  switch ($route_name) {
    case 'help.page.custom_pub':
      $output = '<h3>' . t('About') . '</h3>';
      $output .= '<p>' . t('This module allows you to create custom publishing options for nodes.  For more information, see the <a href=":online">online documentation for Custom Publishing Options</a>.', [
        ':online' => 'https://www.drupal.org/project/custom_pub',
      ]) . '</p>';
      $output .= '<dl>';
      $output .= '<dt>' . t('Uses') . '</dt>';
      $output .= '<ol>';
      $output .= '<li>' . t('Install "Custom Publishing Options" from the module list page.') . '</li>';
      $output .= '<li>' . t('Configure the Custom Publishing Options.') . '</li>';
      $output .= '<li>' . t('On each new option created, set the Node types the option should be available from.') . '</li>';
      $output .= '<li>' . t('Go to the Permissions page. Grant permission to each role that should be able to use the new publishing option.') . '</li>';
      $output .= '</ol>';
      $output .= '<dt>' . t('Views') . '</dt>';
      $output .= '<dd>' . t('Using the Views module opens up a whole new avenue of displaying content with Custom Publishing Options. Create your View any way you like, and under Filter you will find all Custom Publishing Options available. Create archived content sections by creating an Archive option, and Filter by that option!') . '</dd>';
      $output .= '<dt>' . t('Additional Features') . '</dt>';
      $output .= '<dd>' . t('If you want greater permissions to allow a role to use custom publishing options or core states (status, sticky, promoted), it is suggested that you also pick up the Override Node Options module. This module adds access control to each publish state at the role level, so \'administer nodes\' is not a requirement.') . '</dd>';
      $output .= '</dl>';
      return $output;
    default:
  }
}

/**
 * Implements hook_form_BASE_FORM_ID_alter().
 *
 * @param $form
 * @param FormStateInterface $form_state
 */
function custom_pub_form_node_type_edit_form_alter(&$form, FormStateInterface $form_state) {
  $node_type = $form_state
    ->getBuildInfo()['callback_object']
    ->getEntity();
  $fields = \Drupal::service('entity_field.manager')
    ->getFieldDefinitions('node', $node_type
    ->id());
  $entities = \Drupal::entityTypeManager()
    ->getStorage('custom_publishing_option')
    ->loadMultiple();

  /**
   * @var  $machine_name
   * @var  CustomPublishingOption $entity
   */
  foreach ($entities as $machine_name => $entity) {

    #$enabled_types = $entity->getNodeTypes();

    #if (in_array($node_type->id(), $enabled_types)) {
    $form['workflow']['options']['#options'][$entity
      ->id()] = t($entity
      ->label());
    if (isset($fields[$entity
      ->id()])) {
      $field_config = $fields[$entity
        ->id()]
        ->getConfig($node_type
        ->id());
      if ($field_config
        ->get('default_value')[0]['value']) {
        $form['workflow']['options']['#default_value'][$entity
          ->id()] = $entity
          ->id();
      }
    }

    #}
  }
  $form['actions']['submit']['#submit'][] = 'custom_pub_node_type_edit_form_submit';
}

/**
 * Implements hook_form_BASE_FORM_ID_alter().
 * Regroup any custom publishing options to be under a grouped tab on the node form.
 *
 * @param $form
 * @param FormStateInterface $form_state
 */
function custom_pub_form_node_form_alter(&$form, FormStateInterface $form_state) {
  $entities = \Drupal::entityTypeManager()
    ->getStorage('custom_publishing_option')
    ->loadMultiple();
  $form_keys = Element::children($form);
  $user = \Drupal::currentUser();
  $custom_publish_options = FALSE;
  foreach ($entities as $machine_name => $entity) {
    if ($entity
      ->isPublishUnderPromoteOptions()) {
      if (in_array($entity
        ->id(), $form_keys)) {
        $form[$entity
          ->id()]['#group'] = 'options';
        $form[$entity
          ->id()]['#access'] = $user
          ->hasPermission('can set node publish state to ' . $entity
          ->id());
        $custom_publish_options = TRUE;
      }
    }
    else {
      if (in_array($entity
        ->id(), $form_keys)) {
        $form[$entity
          ->id()]['#group'] = 'custom_publish_options';
        $form[$entity
          ->id()]['#access'] = $user
          ->hasPermission('can set node publish state to ' . $entity
          ->id());
        $custom_publish_options = TRUE;
      }
    }
  }

  // show the fieldset if we have options the user can use.
  if ($custom_publish_options) {
    $form['custom_publish_options'] = [
      '#type' => 'details',
      '#title' => t('Custom Publish Options'),
      '#group' => 'advanced',
      '#attributes' => [
        'class' => [
          'node-form-custom-publish-options',
        ],
      ],
      '#weight' => 100,
      '#optional' => TRUE,
    ];
  }
}

/**
 * Submit handler for node type forms.
 *
 * @param $form
 * @param FormStateInterface $form_state
 *
 * @see custom_pub_form_node_type_edit_form_alter()
 */
function custom_pub_node_type_edit_form_submit($form, FormStateInterface $form_state) {
  $entities = \Drupal::entityTypeManager()
    ->getStorage('custom_publishing_option')
    ->loadMultiple();
  $values = $form_state
    ->getValues();
  $node_type = $form_state
    ->getBuildInfo()['callback_object']
    ->getEntity();
  $fields = \Drupal::service('entity_field.manager')
    ->getFieldDefinitions('node', $node_type
    ->id());
  foreach ($entities as $machine_name => $entity) {
    if (in_array($entity
      ->id(), $values['options'])) {
      $value = (bool) $values['options'][$entity
        ->id()];
      $fields[$entity
        ->id()]
        ->getConfig($node_type
        ->id())
        ->setDefaultValue($value)
        ->save();
    }
  }
}

/**
 * Implements hook_entity_base_field_info().
 *
 * @param EntityTypeInterface $entity_type
 *
 * @return array
 */
function custom_pub_entity_base_field_info(EntityTypeInterface $entity_type) {
  if ($entity_type
    ->id() === 'node') {
    $entities = \Drupal::entityTypeManager()
      ->getStorage('custom_publishing_option')
      ->loadMultiple();
    $fields = [];
    foreach ($entities as $machine_name => $entity) {
      $fields[$entity
        ->id()] = BaseFieldDefinition::create('boolean')
        ->setLabel(t('@label', [
        '@label' => $entity
          ->label(),
      ]))
        ->setDescription(t('@description', [
        '@description' => $entity
          ->getDescription(),
      ]))
        ->setRevisionable(TRUE)
        ->setTranslatable(TRUE)
        ->setDefaultValue(0)
        ->setDisplayConfigurable('form', TRUE)
        ->setDisplayOptions('form', [
        'type' => 'boolean_checkbox',
        'settings' => [
          'display_label' => TRUE,
        ],
        'weight' => 16,
      ]);
    }
    return $fields;
  }
}

/**
 * Implements hook_entity_presave().
 *
 * @param EntityInterface $entity
 *
 */
function custom_pub_entity_presave(EntityInterface $entity) {
  if ($entity instanceof BaseFieldOverride) {
    $custom_pub_entity = \Drupal::entityTypeManager()
      ->getStorage('custom_publishing_option')
      ->load($entity
      ->getName());
    if ($custom_pub_entity) {
      $dependencies = $entity
        ->get('dependencies');

      // We need to validate if dependency is already added.
      $dependency_name = $custom_pub_entity
        ->getConfigDependencyName();
      if (!in_array($dependency_name, $dependencies['config'])) {
        $dependencies['config'][] = $dependency_name;
        $entity
          ->set('dependencies', $dependencies);
      }
    }
  }
}

Functions

Namesort descending Description
custom_pub_entity_base_field_info Implements hook_entity_base_field_info().
custom_pub_entity_presave Implements hook_entity_presave().
custom_pub_form_node_form_alter Implements hook_form_BASE_FORM_ID_alter(). Regroup any custom publishing options to be under a grouped tab on the node form.
custom_pub_form_node_type_edit_form_alter Implements hook_form_BASE_FORM_ID_alter().
custom_pub_help Implements hook_help().
custom_pub_node_type_edit_form_submit Submit handler for node type forms.