You are here

abstract class QuickNodeCloneEntitySettingsForm in Quick Node Clone 8

Abstract class to configure how entities are cloned.

@todo write the interface.

Hierarchy

Expanded class hierarchy of QuickNodeCloneEntitySettingsForm

File

src/Form/QuickNodeCloneEntitySettingsForm.php, line 18

Namespace

Drupal\quick_node_clone\Form
View source
abstract class QuickNodeCloneEntitySettingsForm extends ConfigFormBase implements QuickNodeCloneEntitySettingsFormInterface {

  /**
   * The Entity Field Manager.
   *
   * @var \Drupal\Core\Entity\EntityFieldManagerInterface
   */
  protected $entityFieldManager;

  /**
   * The Config Factory.
   *
   * @var \Drupal\Core\Config\ConfigFactoryInterface
   */
  protected $configFactory;

  /**
   * The Entity Bundle Type Info.
   *
   * @var \Drupal\Core\Entity\EntityTypeBundleInfoInterface
   */
  protected $entityTypeBundleInfo;

  /**
   * The machine name of the entity type.
   *
   * @var string
   *   The entity type i.e. node
   */
  protected $entityTypeId = '';

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('config.factory'), $container
      ->get('entity_field.manager'), $container
      ->get('entity_type.bundle.info'));
  }

  /**
   * {@inheritdoc}
   */
  public function setEntityType($entityTypeId) {
    $this->entityTypeId = $entityTypeId;
  }

  /**
   * {@inheritdoc}
   */
  public function getEntityTypeId() {
    return $this->entityTypeId;
  }

  /**
   * {@inheritdoc}
   */
  public function getEditableConfigNames() {
    return [
      'quick_node_clone.settings',
    ];
  }

  /**
   * QuickNodeCloneEntitySettingsForm constructor.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $configFactory
   *   The config factory.
   * @param \Drupal\Core\Entity\EntityFieldManagerInterface $entityFieldManager
   *   The entity field manager service.
   * @param \Drupal\Core\Entity\EntityTypeBundleInfoInterface $entityTypeBundleInfo
   *   The entity type bundle info provider.
   */
  public function __construct(ConfigFactoryInterface $configFactory, EntityFieldManagerInterface $entityFieldManager, EntityTypeBundleInfoInterface $entityTypeBundleInfo) {
    parent::__construct($configFactory);
    $this->configFactory = $configFactory;
    $this->entityFieldManager = $entityFieldManager;
    $this->entityTypeBundleInfo = $entityTypeBundleInfo;
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['exclude'] = [
      '#type' => 'fieldset',
      '#title' => $this
        ->t('Exclusion list'),
    ];
    $form['exclude']['description'] = [
      '#markup' => $this
        ->t('You can select fields that you do not want to be included when the node is cloned.'),
    ];
    $config_name = 'exclude.' . $this
      ->getEntityTypeId();
    if (!is_null($this
      ->getSettings($config_name))) {
      $value = $this
        ->getSettings($config_name);
      if (empty($form_state
        ->getValue('bundle_names'))) {
        $form_state
          ->setValue('bundle_names', $value);
      }
    }
    $bundle_names = [];
    foreach ($this
      ->getEntityBundles() as $bundle => $item) {
      $bundle_names[$bundle] = $item['label'];
    }
    $form['exclude']['bundle_names'] = [
      '#type' => 'checkboxes',
      '#title' => $this
        ->t('Entity Types'),
      '#options' => $bundle_names,
      '#default_value' => array_keys($form_state
        ->getValue('bundle_names') ?: []),
      '#description' => $this
        ->t('Select entity types above and you will see a list of fields that can be excluded.'),
      '#ajax' => [
        'callback' => 'Drupal\\quick_node_clone\\Form\\QuickNodeCloneEntitySettingsForm::fieldsCallback',
        'wrapper' => 'fields-list-' . $this
          ->getEntityTypeId(),
        'method' => 'replace',
      ],
    ];
    $form['exclude']['fields'] = [
      '#type' => 'details',
      '#open' => TRUE,
      '#title' => $this
        ->t('Fields'),
      '#description' => $this
        ->getDescription($form_state),
      '#prefix' => '<div id="fields-list-' . $this
        ->getEntityTypeId() . '">',
      '#suffix' => '</div>',
    ];
    if ($selected_bundles = $this
      ->getSelectedBundles($form_state)) {
      $selected_bundles = $this
        ->getSelectedBundles($form_state);
      foreach ($bundle_names as $bundle_name => $bundle_label) {
        if (!empty($selected_bundles[$bundle_name])) {
          $options = [];
          $field_definitions = $this->entityFieldManager
            ->getFieldDefinitions($this
            ->getEntityTypeId(), $bundle_name);
          foreach ($field_definitions as $field) {
            if ($field instanceof FieldConfig) {
              $options[$field
                ->getName()] = $field
                ->getLabel();
            }
          }
          $form['exclude']['fields']['bundle_' . $bundle_name] = [
            '#type' => 'details',
            '#title' => $bundle_name,
            '#open' => TRUE,
          ];
          $form['exclude']['fields']['bundle_' . $bundle_name][$bundle_name] = [
            '#type' => 'checkboxes',
            '#title' => $this
              ->t('Fields for @bundle_name', [
              '@bundle_name' => $bundle_name,
            ]),
            '#default_value' => $this
              ->getDefaultFields($bundle_name),
            '#options' => $options,
          ];
        }
      }
    }
    return parent::buildForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $form_state
      ->cleanValues();
    $form_values = $form_state
      ->getValues();

    // Build an array of excluded fields for each bundle.
    $bundle_names = [];
    foreach (array_filter($form_values['bundle_names']) as $type) {
      if (!empty(array_filter($form_values[$type]))) {
        $bundle_names[$type] = array_values(array_filter($form_values[$type]));
      }
    }

    // Save config.
    $this
      ->config('quick_node_clone.settings')
      ->set('exclude.' . $this
      ->getEntityTypeId(), $bundle_names)
      ->save();
  }

  /**
   * AJAX callback function to return the excluded fields part of the form.
   *
   * @param array $form
   *   The form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current form state.
   *
   * @return array
   *   The excluded fields form array.
   */
  public static function fieldsCallback(array $form, FormStateInterface $form_state) {
    return $form['exclude']['fields'];
  }

  /**
   * {@inheritdoc}
   */
  public function getEntityBundles() {
    static $bundles;
    if (!isset($bundles)) {
      $bundles = $this->entityTypeBundleInfo
        ->getBundleInfo($this
        ->getEntityTypeId());
    }
    return $bundles;
  }

  /**
   * {@inheritdoc}
   */
  public function getSelectedBundles(FormStateInterface $form_state) {
    $selected_types = NULL;
    $config_name = 'exclude.' . $this
      ->getEntityTypeId();
    if (!empty($form_state
      ->getValue('bundle_names'))) {
      $selected_types = $form_state
        ->getValue('bundle_names');
    }
    elseif (!empty($this
      ->getSettings($config_name)) && array_filter($this
      ->getSettings($config_name))) {
      $selected_types = $this
        ->getSettings($config_name);
    }
    return $selected_types;
  }

  /**
   * {@inheritdoc}
   */
  public function getDescription(FormStateInterface $form_state) {
    $desc = $this
      ->t('No content types selected');
    $config_name = 'exclude.' . $this
      ->getEntityTypeId();
    if (!empty($form_state
      ->getValue('bundle_names')) && array_filter($form_state
      ->getValue('bundle_names'))) {
      $desc = '';
    }
    elseif (!empty($this
      ->getSettings($config_name)) && array_filter($this
      ->getSettings($config_name))) {
      $desc = '';
    }
    return $desc;
  }

  /**
   * {@inheritdoc}
   */
  public function getDefaultFields($value) {
    $default_fields = [];
    $config_name = 'exclude.' . $this
      ->getEntityTypeId() . '.' . $value;
    if (!empty($this
      ->getSettings($config_name))) {
      $default_fields = $this
        ->getSettings($config_name);
    }
    return $default_fields;
  }

  /**
   * {@inheritdoc}
   */
  public function getSettings($value) {
    $settings = $this->configFactory
      ->get('quick_node_clone.settings')
      ->get($value);
    return $settings;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ConfigFormBaseTrait::config protected function Retrieves a configuration object.
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::configFactory protected function Gets the config factory for this form. 1
FormBase::container private function Returns the service container.
FormBase::currentUser protected function Gets the current user.
FormBase::getRequest protected function Gets the request object.
FormBase::getRouteMatch protected function Gets the route match.
FormBase::logger protected function Gets the logger for a specific channel.
FormBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
FormBase::resetConfigFactory public function Resets the configuration factory.
FormBase::setConfigFactory public function Sets the config factory for this form.
FormBase::setRequestStack public function Sets the request stack object to use.
FormBase::validateForm public function Form validation handler. Overrides FormInterface::validateForm 62
FormInterface::getFormId public function Returns a unique string identifying the form. 236
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
QuickNodeCloneEntitySettingsForm::$configFactory protected property The Config Factory. Overrides FormBase::$configFactory
QuickNodeCloneEntitySettingsForm::$entityFieldManager protected property The Entity Field Manager.
QuickNodeCloneEntitySettingsForm::$entityTypeBundleInfo protected property The Entity Bundle Type Info.
QuickNodeCloneEntitySettingsForm::$entityTypeId protected property The machine name of the entity type. 2
QuickNodeCloneEntitySettingsForm::buildForm public function Form constructor. Overrides ConfigFormBase::buildForm 1
QuickNodeCloneEntitySettingsForm::create public static function Instantiates a new instance of this class. Overrides ConfigFormBase::create
QuickNodeCloneEntitySettingsForm::fieldsCallback public static function AJAX callback function to return the excluded fields part of the form.
QuickNodeCloneEntitySettingsForm::getDefaultFields public function Returns the default fields. Overrides QuickNodeCloneEntitySettingsFormInterface::getDefaultFields
QuickNodeCloneEntitySettingsForm::getDescription public function Returns the description field. Overrides QuickNodeCloneEntitySettingsFormInterface::getDescription
QuickNodeCloneEntitySettingsForm::getEditableConfigNames public function Gets the configuration names that will be editable. Overrides ConfigFormBaseTrait::getEditableConfigNames
QuickNodeCloneEntitySettingsForm::getEntityBundles public function Returns the bundles for the entity. Overrides QuickNodeCloneEntitySettingsFormInterface::getEntityBundles
QuickNodeCloneEntitySettingsForm::getEntityTypeId public function Returns the entity type Id. i.e. article. Overrides QuickNodeCloneEntitySettingsFormInterface::getEntityTypeId
QuickNodeCloneEntitySettingsForm::getSelectedBundles public function Returns the selected bundles on the form. Overrides QuickNodeCloneEntitySettingsFormInterface::getSelectedBundles
QuickNodeCloneEntitySettingsForm::getSettings public function Return the configuration. Overrides QuickNodeCloneEntitySettingsFormInterface::getSettings
QuickNodeCloneEntitySettingsForm::setEntityType public function Sets the entity type the settings form is for. Overrides QuickNodeCloneEntitySettingsFormInterface::setEntityType
QuickNodeCloneEntitySettingsForm::submitForm public function Form submission handler. Overrides ConfigFormBase::submitForm 1
QuickNodeCloneEntitySettingsForm::__construct public function QuickNodeCloneEntitySettingsForm constructor. Overrides ConfigFormBase::__construct
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.