You are here

class EntityExportCsvSettings in Entity Export CSV 8

Define entity export csv settings form.

Hierarchy

Expanded class hierarchy of EntityExportCsvSettings

1 string reference to 'EntityExportCsvSettings'
entity_export_csv.routing.yml in ./entity_export_csv.routing.yml
entity_export_csv.routing.yml

File

src/Form/EntityExportCsvSettings.php, line 18

Namespace

Drupal\entity_export_csv\Form
View source
class EntityExportCsvSettings extends ConfigFormBase {

  /**
   * Drupal\Core\Entity\EntityTypeManagerInterface definition.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * Drupal\Core\Entity\EntityTypeBundleInfoInterface definition.
   *
   * @var \Drupal\Core\Entity\EntityTypeBundleInfoInterface
   */
  protected $entityTypeBundleInfo;

  /**
   * Drupal\Core\Entity\EntityFieldManagerInterface definition.
   *
   * @var \Drupal\Core\Entity\EntityFieldManagerInterface
   */
  protected $entityFieldManager;

  /**
   * The entity export csv manager.
   *
   * @var \Drupal\entity_export_csv\EntityExportCsvManagerInterface
   */
  protected $manager;

  /**
   * {@inheritdoc}
   */
  public function __construct(ConfigFactoryInterface $config_factory, EntityTypeManagerInterface $entity_type_manager, EntityTypeBundleInfoInterface $entity_type_bundle_info, EntityFieldManagerInterface $entity_field_manager, EntityExportCsvManagerInterface $entity_export_csv_manager) {
    parent::__construct($config_factory);
    $this->entityTypeManager = $entity_type_manager;
    $this->entityTypeBundleInfo = $entity_type_bundle_info;
    $this->entityFieldManager = $entity_field_manager;
    $this->manager = $entity_export_csv_manager;
  }

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

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

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $config = $this
      ->getConfiguration();
    $private_system_file = PrivateStream::basePath();
    if (!$private_system_file) {
      $this
        ->messenger()
        ->addWarning($this
        ->t('The private system file is not configured. It is highly recommended to configure it. If not available, exports will use the temporary system file.'));
    }
    $form['entity_types'] = [
      '#type' => 'fieldset',
      "#title" => $this
        ->t('Entity types'),
      '#description' => $this
        ->t('Enable the entity types on which you want allow users be able to export them.'),
      '#tree' => TRUE,
    ];
    $entity_types = $this->manager
      ->getSupportedContentEntityTypes(TRUE);

    // We do not use here a checkboxes to be able later to
    // enable / disable per bundle too.

    /** @var \Drupal\Core\Entity\ContentEntityTypeInterface $entity_type */
    foreach ($entity_types as $entity_type_id => $entity_type) {
      $form['entity_types'][$entity_type_id] = [
        '#type' => 'container',
        '#tree' => TRUE,
        '#prefix' => '<div id="' . $entity_type_id . '">',
        '#suffix' => '</div>',
      ];
      $form['entity_types'][$entity_type_id]['enable'] = [
        '#type' => 'checkbox',
        '#title' => $entity_type
          ->getLabel(),
        '#default_value' => $config
          ->get('entity_types.' . $entity_type_id . '.enable'),
      ];
      $bundles_entity_type = $this->manager
        ->getBundlesPerEntityType($entity_type_id, TRUE);
      $default_bundles = $config
        ->get('entity_types.' . $entity_type_id . '.limit_per_bundle') ?: [];
      $default_bundles = array_filter($default_bundles);
      $bundles = $this
        ->getElementPropertyValue([
        'entity_types',
        $entity_type_id,
        'limit_per_bundle',
      ], $form_state, $default_bundles);
      $bundles = array_filter($bundles);
      $form['entity_types'][$entity_type_id]['limit_per_bundle'] = [
        '#type' => 'checkboxes',
        "#title" => $this
          ->t('Limit bundles for @entity_type', [
          '@entity_type' => $entity_type
            ->getLabel(),
        ]),
        "#description" => $this
          ->t('Leave empty to select all.'),
        '#options' => $bundles_entity_type,
        '#default_value' => $bundles,
        '#attributes' => [
          'class' => [
            'inline-checkboxes',
          ],
        ],
        '#states' => [
          'visible' => [
            ':input[name="entity_types[' . $entity_type_id . '][enable]"]' => [
              'checked' => TRUE,
            ],
          ],
        ],
        '#ajax' => [
          'event' => 'change',
          'method' => 'replace',
          'wrapper' => 'bundles-' . $entity_type_id,
          'callback' => [
            $this,
            'ajaxReplaceEntityTypeBundlesCallback',
          ],
        ],
      ];
      $form['entity_types'][$entity_type_id]['bundles'] = [
        '#type' => 'container',
        '#prefix' => '<div id="bundles-' . $entity_type_id . '">',
        '#suffix' => '</div>',
        '#tree' => TRUE,
      ];
      if (!empty($bundles)) {
        foreach ($bundles as $bundle) {
          $bundle_default_fields = $config
            ->get('entity_types.' . $entity_type_id . '.bundles.' . $bundle) ?: [];
          $bundle_default_fields_value = $this
            ->getElementPropertyValue([
            'entity_types',
            $entity_type_id,
            'bundles',
            $bundle,
            'wrapper',
          ], $form_state, $bundle_default_fields);
          $form['entity_types'][$entity_type_id]['bundles'][$bundle] = [
            '#type' => 'details',
            '#title' => $this
              ->t('Fields for bundle @label (machine name: @bundle)', [
              '@label' => $bundles_entity_type[$bundle],
              '@bundle' => $bundle,
            ]),
            '#description' => $this
              ->t('Select the fields you want to be exportable. Leave empty to select all.'),
            "#open" => (bool) (!empty(array_filter($bundle_default_fields_value))),
          ];
          $form['entity_types'][$entity_type_id]['bundles'][$bundle]['wrapper'] = [
            '#type' => 'checkboxes',
            "#title" => $this
              ->t('Fields'),
            '#options' => $this->manager
              ->getBundleFields($entity_type_id, $bundle),
            '#default_value' => $bundle_default_fields_value,
            '#attributes' => [
              'class' => [
                'inline-checkboxes',
              ],
            ],
          ];
        }
      }
    }
    $form['multiple'] = [
      '#type' => 'fieldset',
      "#title" => $this
        ->t('Multiple fields'),
      '#tree' => TRUE,
    ];
    $form['multiple']['columns'] = [
      '#type' => 'select',
      "#title" => $this
        ->t('Number of columns'),
      '#options' => $this
        ->getColumnsOptions(),
      '#default_value' => $config
        ->get('multiple.columns'),
      '#description' => $this
        ->t('Select the maximum number of columns a user can select to export a multiple field into several columns.'),
      '#required' => TRUE,
    ];
    $form['#attached']['library'][] = 'entity_export_csv/admin';
    return parent::buildForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $values = $form_state
      ->cleanValues()
      ->getValues();
    $this
      ->massageValues($values);
    $this
      ->getConfiguration()
      ->setData($values)
      ->save();
    parent::submitForm($form, $form_state);
  }

  /**
   * Massage the values.
   *
   * @param array $values
   *   The values.
   */
  protected function massageValues(array &$values) {
    foreach ($values['entity_types'] as $entity_type_id => $entity_type_value) {
      if (!empty($entity_type_value['limit_per_bundle'])) {
        $limit_per_bundle = $entity_type_value['limit_per_bundle'];
        $values['entity_types'][$entity_type_id]['limit_per_bundle'] = array_filter($limit_per_bundle);
      }
      if (!empty($entity_type_value['bundles'])) {
        foreach ($entity_type_value['bundles'] as $bundle => $bundle_value) {
          $wrapper = $bundle_value['wrapper'];
          unset($values['entity_types'][$entity_type_id]['bundles'][$bundle]['wrapper']);
          $values['entity_types'][$entity_type_id]['bundles'][$bundle] = array_filter($wrapper);
        }
      }
    }
  }

  /**
   * Ajax replace callback.
   *
   * @param array $form
   *   The form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state.
   *
   * @return array
   *   The bundles form.
   */
  public function ajaxReplaceEntityTypeBundlesCallback(array &$form, FormStateInterface &$form_state) {
    $triggering_element = $form_state
      ->getTriggeringElement();
    $entity_type_id = $triggering_element['#parents'][1];
    return $form['entity_types'][$entity_type_id]['bundles'];
  }

  /**
   * Get element property value.
   *
   * @param array|string $property
   *   The property.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state.
   * @param mixed $default
   *   The default value.
   *
   * @return array|mixed|null
   *   The property value.
   */
  protected function getElementPropertyValue($property, FormStateInterface $form_state, $default = '') {
    $test = $form_state
      ->hasValue($property) ? $form_state
      ->getValue($property) : '';
    return $form_state
      ->hasValue($property) ? $form_state
      ->getValue($property) : $default;
  }

  /**
   * Get the columns options.
   *
   * @return array
   *   An array of columns options.
   */
  protected function getColumnsOptions() {
    $options = [
      '1' => '1 column',
      '2' => '2 columns',
      '3' => '3 columns',
      '4' => '4 columns',
      '5' => '5 columns',
      '6' => '6 columns',
      '7' => '7 columns',
      '8' => '8 columns',
      '9' => '9 columns',
      '10' => '10 columns',
    ];
    return $options;
  }

  /**
   * Get configuration object.
   *
   * @return \Drupal\Core\Config\Config|\Drupal\Core\Config\ImmutableConfig
   *   The configuration object.
   */
  protected function getConfiguration() {
    return $this
      ->config('entity_export_csv.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
EntityExportCsvSettings::$entityFieldManager protected property Drupal\Core\Entity\EntityFieldManagerInterface definition.
EntityExportCsvSettings::$entityTypeBundleInfo protected property Drupal\Core\Entity\EntityTypeBundleInfoInterface definition.
EntityExportCsvSettings::$entityTypeManager protected property Drupal\Core\Entity\EntityTypeManagerInterface definition.
EntityExportCsvSettings::$manager protected property The entity export csv manager.
EntityExportCsvSettings::ajaxReplaceEntityTypeBundlesCallback public function Ajax replace callback.
EntityExportCsvSettings::buildForm public function Form constructor. Overrides ConfigFormBase::buildForm
EntityExportCsvSettings::create public static function Instantiates a new instance of this class. Overrides ConfigFormBase::create
EntityExportCsvSettings::getColumnsOptions protected function Get the columns options.
EntityExportCsvSettings::getConfiguration protected function Get configuration object.
EntityExportCsvSettings::getEditableConfigNames protected function Gets the configuration names that will be editable. Overrides ConfigFormBaseTrait::getEditableConfigNames
EntityExportCsvSettings::getElementPropertyValue protected function Get element property value.
EntityExportCsvSettings::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
EntityExportCsvSettings::massageValues protected function Massage the values.
EntityExportCsvSettings::submitForm public function Form submission handler. Overrides ConfigFormBase::submitForm
EntityExportCsvSettings::__construct public function Constructs a \Drupal\system\ConfigFormBase object. Overrides ConfigFormBase::__construct
FormBase::$configFactory protected property The config factory. 1
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
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.
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.