Why Gemfury? Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Debian packages RPM packages NuGet packages

Repository URL to install this package:

Details    
novicell/custom_forms / src / Form / CustomFormGroupForm.php
Size: Mime:
<?php

namespace Drupal\custom_forms\Form;

use Drupal\Component\Datetime\Time;
use Drupal\Core\Entity\EntityStorageException;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Drupal\custom_forms\CustomFormItem;
use Drupal\custom_forms\CustomFormItemFactory;
use Drupal\custom_forms\CustomFormsGroupTypeManager;
use Drupal\custom_forms\Entity\CustomForm;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Class CustomFormGroupForm
 *
 * The form for adding a new group to the custom form.
 *
 * @package Drupal\custom_forms\Form
 */
class CustomFormGroupForm extends FormBase {

  /**
   * The custom forms group type manager.
   *
   * @var \Drupal\custom_forms\CustomFormsGroupTypeManager $groupTypeManager
   */
  protected $groupTypeManager;

  /**
   * The factory in charge of CRUD operations for custom form items.
   *
   * @var \Drupal\custom_forms\CustomFormItemFactory
   */
  protected $itemFactory;

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('plugin.manager.custom_forms_group_types'),
      $container->get('custom_forms.factory.item')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function __construct(CustomFormsGroupTypeManager $group_type_manager, CustomFormItemFactory $item_factory) {
    $this->groupTypeManager = $group_type_manager;
    $this->itemFactory = $item_factory;
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'custom_form_group_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {

    $attributes = \Drupal::request()->attributes;

    /** @var CustomForm $custom_form */
    $custom_form = $attributes->get('custom_form');

    $available_groups = $this->itemFactory->getCompatibleGroups($custom_form);

    if (!empty($available_groups) && count($available_groups) > 0) {

      $form['form'] = [
        '#type' => 'value',
        '#value' => $custom_form
      ];

      $form['label'] = [
        '#type' => 'textfield',
        '#title' => $this->t('Label'),
        '#placeholder' => $this->t('Label'),
        '#description' => $this->t('The label for the group.'),
        '#required' => TRUE,
        '#weight' => -100,
      ];

      $form['machine_name'] = [
        '#type' => 'machine_name',
        '#maxlength' => EntityTypeInterface::BUNDLE_MAX_LENGTH,
        '#machine_name' => [
          'exists' => '\Drupal\custom_forms\CustomFormItemFactory::itemMachineNameExists',
          'source' => ['label'],
        ],
        '#weight' => -99,
        '#description' => $this->t('A unique machine-readable name for this group. It must only contain lowercase letters, numbers, and underscores.'),
      ];

      $form['message'] = ['#markup' => $this->t('Please select the group type you want to use in the form. <br>The next page will contain the settings of the selected group type, so that you can adjust them.')];

      $form['group_type'] = [
        '#type' => 'select',
        '#title' => $this->t('Group type'),
        '#description' => $this->t('Select the group type to use.'),
        '#required' => TRUE,
        '#empty_option' => '- ' . $this->t('Choose group type') . ' -',
        '#options' => $available_groups,
      ];

    } else {

      $messages = [];
      if (count($available_groups) <= 0) {
        $messages[] = $this->t('No group type plugins found.');
      }

      $form['message'] = [
        '#type' => 'markup',
        '#markup' => $this->t('Unable to load form, see reason(s) below.'),
        'reasons' => [
          '#theme' => 'item_list',
          '#list_type' => 'ul',
          '#items' => $messages,
        ]
      ];
    }
    $form['actions'] = [
      '#type' => 'actions',
    ];

    if (count($available_groups) > 0) {
      $form['actions']['create'] = [
        '#type' => 'submit',
        '#value' => $this->t('Create'),
        '#attributes' => [
          'class' => [
            'button',
            'button-action',
            'button--primary',
          ]
        ],
      ];
    }

    $form['actions']['cancel'] = [
      '#type' => 'link',
      '#title' => $this->t('Cancel'),
      '#url' => Url::fromRoute('entity.custom_form.fields_form', ['custom_form' => $custom_form->id()]),
      '#attributes' => [
        'class' => [
          'button',
          'button-action',
          'button--secondary',
        ],
      ],
      '#limit_validation_errors' => [],
    ];

    if (count($available_groups) <= 0) {
      $form['actions']['cancel']['#title'] = $this->t('Back');
      $form['actions']['cancel']['#attributes']['style'][] = 'margin-left: 0;';
      $form['actions']['cancel']['#attributes']['class'] = [
        'button',
        'button-action',
        'button--primary',
      ];
    }

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $attributes = \Drupal::request()->attributes;
    $values = $form_state->cleanValues()->getValues();

    /** @var CustomForm $custom_form */
    $custom_form = $attributes->get('custom_form');
    $group_definition = $this->groupTypeManager->getDefinition($values['group_type']);

    /** @var Time $time */
    $time = \Drupal::service('datetime.time');
    $timestamp = $time->getCurrentTime();

    $settings = [
      'label' => $values['label'],
      'machine_name' => $values['machine_name']
    ];
    if (isset($group_definition['root']) && (boolean) $group_definition['root']) {
      $settings['is_root_item'] = TRUE;
    }

    // Create a new custom form revision since we are modifying it by adding a new field.
    $revision_saved = FALSE;
    $custom_form->setNewRevision(TRUE);
    $custom_form->setRevisionTranslationAffected(TRUE); // for some reason required for log messages to show up?
    $custom_form->setRevisionLogMessage($this->t('Added new group: @group-label', ['@group-label' => $values['label']]));
    $custom_form->setRevisionCreationTime(\Drupal::time()->getRequestTime());
    $custom_form->setRevisionUserId(\Drupal::currentUser()->id());
    try {
      $custom_form->save();
      $revision_saved = TRUE;
    } catch (EntityStorageException $e) {
      $error_message = $this->t('Failed during creation of new revision. Message = %message', [
        '%message' => $e->getMessage()
      ]);
      \Drupal::logger('Custom Forms')->error($error_message);
      $this->messenger()->addError($this->t('Failed during creation of new revision, please try again. If it continues please contact an administrator.'));
    }

    // We only want to create the new group if the revision was able to be saved.
    if ($revision_saved) {
      $item = new CustomFormItem($custom_form->id(), $custom_form->getLoadedRevisionId(), $timestamp, $timestamp, $custom_form->language()->getId(), 'group', $values['group_type'], $values['machine_name'], serialize($settings));

      try {
        $item->save();
      } catch (\Exception $e) {
        $error_message = $this->t('Group saving failed. Message = %message', [
          '%message' => $e->getMessage()
        ]);
        \Drupal::logger('Custom Forms')->error($error_message);
        $this->messenger()->addError($this->t('Failed during creation of new group, please try again. If it continues please contact an administrator.'));
      }
    }

    $form_state->setRedirect('entity.custom_form.fields_form', ['custom_form' => $custom_form->id()]);
  }
}