You are here

function simplenews_form_node_type_submit in Simplenews 3.x

Same name and namespace in other branches
  1. 8.2 simplenews.module \simplenews_form_node_type_submit()
  2. 8 simplenews.module \simplenews_form_node_type_submit()

Submit callback to add the simplenews_issue field to node types.

1 string reference to 'simplenews_form_node_type_submit'
simplenews_form_node_type_form_alter in ./simplenews.module
Implements hook_form_FORM_ID_alter().

File

./simplenews.module, line 246
Simplenews node handling, sent email, newsletter block and general hooks.

Code

function simplenews_form_node_type_submit(array $form, FormStateInterface $form_state) {
  $checked = $form_state
    ->getValue('simplenews_content_type');
  $node_type = $form_state
    ->getFormObject()
    ->getEntity();

  // Get the default based on the existence of the simplenews_issue field.
  $fields = \Drupal::service('entity_field.manager')
    ->getFieldDefinitions('node', $node_type
    ->id());
  $exists = isset($fields['simplenews_issue']);
  if ($checked && !$exists) {

    // If checked and the field does not exist yet, create it.
    $field_storage = FieldStorageConfig::loadByName('node', 'simplenews_issue');
    $field = FieldConfig::create([
      'field_storage' => $field_storage,
      'label' => t('Issue'),
      'bundle' => $node_type
        ->id(),
      'translatable' => TRUE,
    ]);
    $field
      ->save();

    // Set the default widget.
    \Drupal::service('entity_display.repository')
      ->getFormDisplay('node', $node_type
      ->id())
      ->setComponent($field
      ->getName())
      ->save();
  }
  elseif (!$checked && $exists) {

    // @todo Consider deleting the field or find a way to disable it. Maybe
    //   do not allow to disable the checkbox and point to removing the field
    //   manually? Or remove this feature completely and rely on the field only.
  }
}