You are here

class StockConfigForm in Commerce Stock 8

The stock configuration form.

Hierarchy

Expanded class hierarchy of StockConfigForm

1 string reference to 'StockConfigForm'
commerce_stock.routing.yml in ./commerce_stock.routing.yml
commerce_stock.routing.yml

File

src/Form/StockConfigForm.php, line 17

Namespace

Drupal\commerce_stock\Form
View source
class StockConfigForm extends ConfigFormBase {

  /**
   * A list of purchasable entity types and bundles.
   *
   * @var array
   */
  protected $purchasableEntityTypes;

  /**
   * The Stock Service Manager.
   *
   * @var \Drupal\commerce_stock\StockServiceManager
   */
  protected $stockServiceManager;

  /**
   * The Stock Service Manager.
   *
   * @var \Drupal\commerce_stock\StockEventsManager
   */
  protected $stockEventsManager;

  /**
   * Constructs a StockConfigForm object.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The factory for configuration objects.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   * @param \Drupal\Core\Entity\EntityTypeBundleInfoInterface $entity_type_bundle_info
   *   The entity type bundle info service.
   * @param \Drupal\commerce_stock\StockServiceManagerInterface $stock_service_manager
   *   The stock service manager.
   * @param \Drupal\commerce_stock\StockEventsManager $stock_events_manager
   *   The stock events plugin manager.
   */
  public function __construct(ConfigFactoryInterface $config_factory, EntityTypeManagerInterface $entity_type_manager, EntityTypeBundleInfoInterface $entity_type_bundle_info, StockServiceManagerInterface $stock_service_manager, StockEventsManager $stock_events_manager) {
    parent::__construct($config_factory);
    $this->stockServiceManager = $stock_service_manager;
    $this->stockEventsManager = $stock_events_manager;

    // Prepare the list of purchasable entity types and bundles.
    $entity_types = $entity_type_manager
      ->getDefinitions();
    $purchasable_entity_types = array_filter($entity_types, function ($entity_type) {
      return $entity_type
        ->isSubclassOf('\\Drupal\\commerce\\PurchasableEntityInterface');
    });
    $purchasable_entity_types = array_map(function ($entity_type) {
      return $entity_type
        ->getLabel();
    }, $purchasable_entity_types);
    foreach ($purchasable_entity_types as $type => $label) {
      $this->purchasableEntityTypes[$type] = [
        'label' => $label,
        'bundles' => [],
      ];
      foreach ($entity_type_bundle_info
        ->getBundleInfo($type) as $bundle_id => $bundle_info) {
        $this->purchasableEntityTypes[$type]['bundles'][$bundle_id] = $bundle_info['label'];
      }
    }
  }

  /**
   * {@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('commerce_stock.service_manager'), $container
      ->get('plugin.manager.stock_events'));
  }

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

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

    // Get the default service.
    $config = $this
      ->config('commerce_stock.service_manager');
    $default_service_id = $config
      ->get('default_service_id');
    $stock_service_manager = $this->stockServiceManager;
    $service_options = $stock_service_manager
      ->listServiceIds();
    $form['service_manager'] = [
      '#type' => 'fieldset',
      '#title' => $this
        ->t('Stock services'),
    ];
    $form['service_manager']['default_service_id'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Default service'),
      '#options' => $service_options,
      '#default_value' => $default_service_id,
    ];
    $form['service_manager']['services'] = [
      '#type' => 'fieldset',
      '#title' => $this
        ->t('Services per entity type'),
    ];
    $service_options = array_merge([
      'use_default' => $this
        ->t('- Use default -'),
    ], $service_options);
    foreach ($this->purchasableEntityTypes as $entity_type_id => $entity_type_info) {
      $form['service_manager']['services'][$entity_type_id] = [
        '#type' => 'fieldset',
        '#title' => $entity_type_info['label'],
      ];
      foreach ($entity_type_info['bundles'] as $bundle_id => $bundle_name) {
        $config_key = $entity_type_id . '_' . $bundle_id . '_service_id';
        $form['service_manager']['services'][$entity_type_id][$config_key] = [
          '#type' => 'select',
          '#title' => $bundle_name,
          '#options' => $service_options,
          '#default_value' => $config
            ->get($config_key) ?: 'use_default',
        ];
      }
    }

    // Event manager
    // Get the default event plugin.
    $selected_plugin_id = $config
      ->get('stock_events_plugin_id') ?: 'core_stock_events';

    // Get the list of available plugins.
    $type = $this->stockEventsManager;
    $plugin_definitions = $type
      ->getDefinitions();
    $plugin_list = [];
    foreach ($plugin_definitions as $plugin_definition) {
      $id = $plugin_definition['id'];
      $description = $plugin_definition['description']
        ->render();
      $plugin_list[$id] = $description;
    }

    // Select the stock event plugin.
    $form['event_manager'] = [
      '#type' => 'fieldset',
      '#title' => $this
        ->t('Event Handler'),
    ];
    $form['event_manager']['selected_event_plugin'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Selected plugin'),
      '#options' => $plugin_list,
      '#default_value' => $selected_plugin_id,
    ];

    // Plugin options to be displayed in a field group.
    $form['event_manager']['options'] = [
      '#type' => 'vertical_tabs',
      '#default_tab' => 'edit-publication',
    ];

    // Cycle the plugins.
    foreach ($plugin_definitions as $plugin_definition) {
      $id = $plugin_definition['id'];
      $description = $plugin_definition['description']
        ->render();
      $plugin_list[$id] = $description;

      // Create the form elements for each one.
      $form[$id] = [
        '#type' => 'details',
        '#title' => $description,
        '#group' => 'options',
      ];
      $plugin = $type
        ->createInstance($id);
      $event_option = $plugin
        ->configFormOptions();
      $form[$id]['config'] = $event_option;
    }
    return parent::buildForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   *
   * @throws \Drupal\Component\Plugin\Exception\PluginException
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $values = $form_state
      ->getValues();
    $config = $this
      ->config('commerce_stock.service_manager');
    $config
      ->set('default_service_id', $values['default_service_id']);
    foreach ($this->purchasableEntityTypes as $entity_type_id => $entity_type_info) {
      foreach (array_keys($entity_type_info['bundles']) as $bundle_id) {
        $key = $entity_type_id . '_' . $bundle_id . '_service_id';
        $value = $values[$key];
        if ($value !== 'use_default') {
          $config
            ->set($key, $value);
        }
        else {
          $config
            ->clear($key);
        }
      }
    }

    // Events manager.
    $config
      ->set('stock_events_plugin_id', $values['selected_event_plugin']);
    $config
      ->save();

    // Update all plugin options.
    $type = $this->stockEventsManager;
    $plugin_definitions = $type
      ->getDefinitions();
    foreach ($plugin_definitions as $plugin_definition) {
      $id = $plugin_definition['id'];
      $plugin = $type
        ->createInstance($id);
      $plugin
        ->SaveconfigFormOptions($form, $form_state);
    }
    $this
      ->messenger()
      ->addMessage($this
      ->t('Stock configuration updated.'));
  }

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

}

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::$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.
StockConfigForm::$purchasableEntityTypes protected property A list of purchasable entity types and bundles.
StockConfigForm::$stockEventsManager protected property The Stock Service Manager.
StockConfigForm::$stockServiceManager protected property The Stock Service Manager.
StockConfigForm::buildForm public function Form constructor. Overrides ConfigFormBase::buildForm
StockConfigForm::create public static function Instantiates a new instance of this class. Overrides ConfigFormBase::create
StockConfigForm::getEditableConfigNames protected function Gets the configuration names that will be editable. Overrides ConfigFormBaseTrait::getEditableConfigNames
StockConfigForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
StockConfigForm::submitForm public function Overrides ConfigFormBase::submitForm
StockConfigForm::__construct public function Constructs a StockConfigForm object. Overrides ConfigFormBase::__construct
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.