You are here

function nopremium_form_alter in Node Option Premium 8

Same name and namespace in other branches
  1. 6 nopremium.module \nopremium_form_alter()

Implements hook_form_alter().

Alters the following forms:

  • node add/edit forms;
  • node type add/edit forms.

File

./nopremium.module, line 29
Hook implementations.

Code

function nopremium_form_alter(array &$form, FormStateInterface $form_state) {
  $form_object = $form_state
    ->getFormObject();

  // Alter node add/edit forms.
  if ($form_object instanceof NodeForm) {
    $user = \Drupal::currentUser();
    $node_type_id = $form_state
      ->getBuildInfo()['callback_object']
      ->getEntity()
      ->getType();
    $form['premium']['#group'] = 'premium_publish_options';
    $form['premium']['#access'] = $user
      ->hasPermission('override premium option of any content type') || $user
      ->hasPermission('override ' . $node_type_id . ' premium content');
    $form['premium_publish_options'] = [
      '#type' => 'details',
      '#title' => t('Premium Options'),
      '#group' => 'advanced',
      '#attributes' => [
        'class' => [
          'node-form-premium-publish-options',
        ],
      ],
      '#weight' => 1000,
      '#optional' => TRUE,
    ];
  }

  // Alter node type add/edit forms.
  if ($form_object instanceof NodeTypeForm) {
    $form['workflow']['options']['#options']['premium'] = t('Premium content');
    $form['actions']['submit']['#submit'][] = 'nopremium_node_type_edit_form_submit';

    // Set the checkbox value when active.
    $node_type = $form_state
      ->getBuildInfo()['callback_object']
      ->getEntity();
    if ($node_type
      ->id()) {
      $fields = \Drupal::service('entity_field.manager')
        ->getFieldDefinitions('node', $node_type
        ->id());
      if (isset($fields['premium'])) {
        $field_config = $fields['premium']
          ->getConfig($node_type
          ->id());
        if ($field_config
          ->get('default_value')[0]['value']) {
          $form['workflow']['options']['#default_value']['premium'] = 'premium';
        }
      }
    }
  }
}