You are here

class AppSettingsForm in Apigee Edge 8

Configuration form builder for general app settings.

Hierarchy

Expanded class hierarchy of AppSettingsForm

1 string reference to 'AppSettingsForm'
apigee_edge.routing.yml in ./apigee_edge.routing.yml
apigee_edge.routing.yml

File

src/Form/AppSettingsForm.php, line 36

Namespace

Drupal\apigee_edge\Form
View source
class AppSettingsForm extends ConfigFormBase {

  /**
   * The entity type manager service.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  private $entityTypeManager;

  /**
   * The renderer.
   *
   * @var \Drupal\Core\Render\RendererInterface
   */
  protected $renderer;

  /**
   * AppSettingsForm constructor.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The factory for configuration objects.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager service.
   * @param \Drupal\Core\Render\RendererInterface $renderer
   *   The renderer.
   */
  public function __construct(ConfigFactoryInterface $config_factory, EntityTypeManagerInterface $entity_type_manager, RendererInterface $renderer) {
    parent::__construct($config_factory);
    $this->entityTypeManager = $entity_type_manager;
    $this->renderer = $renderer;
  }

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

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

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $common_app_settings = $this
      ->config('apigee_edge.common_app_settings');

    // Someone has overridden the default setting.
    if (!$common_app_settings
      ->get('multiple_products')) {
      $this
        ->messenger()
        ->addWarning($this
        ->t('Access to multiple API products will be retained until an app is edited and the developer is prompted to confirm a single API product selection.'));
    }

    /** @var string[] $default_products */
    $default_products = $common_app_settings
      ->get('default_products') ?: [];
    $product_list = [];
    try {

      /** @var \Drupal\apigee_edge\Entity\ApiProduct $product */
      foreach ($this->entityTypeManager
        ->getStorage('api_product')
        ->loadMultiple() as $product) {
        $product_list[$product
          ->id()] = $product
          ->label();
      }
    } catch (EntityStorageException $e) {

      // Apigee Edge credentials are missing/incorrect or something else went
      // wrong. Do not redirect the user to the error page.
      $form['actions']['submit']['#disabled'] = TRUE;
      $this
        ->messenger()
        ->addError($this
        ->t('Unable to retrieve API product list from Apigee Edge. Please ensure that <a href=":link">Apigee Edge connection settings</a> are correct.', [
        ':link' => Url::fromRoute('apigee_edge.settings')
          ->toString(),
      ]));
      return $form;
    }
    $form['api_product'] = [
      '#id' => 'api_product',
      '#type' => 'details',
      '#title' => $this
        ->t('API product association settings'),
      '#open' => TRUE,
    ];
    $form['api_product']['multiple_products'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Allow multiple products'),
      '#description' => $this
        ->t('Allow users to select multiple products.'),
      '#default_value' => $common_app_settings
        ->get('multiple_products'),
    ];
    $form['api_product']['display_as_select'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Display the API Product widget as a select box (instead of checkboxes/radios)'),
      '#default_value' => $common_app_settings
        ->get('display_as_select'),
    ];
    $form['api_product']['user_select'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Let user select the product(s)'),
      '#default_value' => $common_app_settings
        ->get('user_select'),
      '#ajax' => [
        'callback' => '::apiProductListCallback',
        'wrapper' => 'default-api-product-multiple',
        'progress' => [
          'type' => 'throbber',
          'message' => '',
        ],
      ],
    ];

    // It's necessary to add a wrapper because if the ID is added to the
    // checkboxes form element, then that will not be properly rendered
    // (the label gets duplicated).
    $form['api_product']['default_api_product_multiple_container'] = [
      '#type' => 'container',
      '#id' => 'default-api-product-multiple',
    ];
    $form['api_product']['default_api_product_multiple_container']['default_api_product_multiple'] = [
      '#type' => 'checkboxes',
      '#title' => $common_app_settings
        ->get('multiple_products') ? $this
        ->t('Default API products') : $this
        ->t('Default API product'),
      '#options' => $product_list,
      '#default_value' => $default_products,
      '#required' => $form_state
        ->getValue('user_select') === NULL ? !(bool) $common_app_settings
        ->get('user_select') : !(bool) $form_state
        ->getValue('user_select'),
    ];
    return parent::buildForm($form, $form_state);
  }

  /**
   * Ajax callback for the "user_select" checkbox.
   *
   * Set 'default_api_product_multiple' checkboxes form element as required
   * if the 'user_select' is unchecked, else not required.
   * Use AJAX instead of #states because #required in #states is not
   * working properly.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   *
   * @return \Drupal\Core\Ajax\AjaxResponse
   *   The Ajax response.
   *
   * @see https://www.drupal.org/project/drupal/issues/2855139
   */
  public function apiProductListCallback(array &$form, FormStateInterface $form_state) : AjaxResponse {
    $response = new AjaxResponse();
    $response
      ->addCommand(new ReplaceCommand('#default-api-product-multiple', $this->renderer
      ->render($form['api_product']['default_api_product_multiple_container'])));
    return $response;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $this
      ->config('apigee_edge.common_app_settings')
      ->set('multiple_products', $form_state
      ->getValue('multiple_products'))
      ->set('display_as_select', $form_state
      ->getValue('display_as_select'))
      ->set('user_select', $form_state
      ->getValue('user_select'))
      ->set('default_products', array_values(array_filter($form_state
      ->getValue('default_api_product_multiple'))))
      ->save();
    parent::submitForm($form, $form_state);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
AppSettingsForm::$entityTypeManager private property The entity type manager service.
AppSettingsForm::$renderer protected property The renderer.
AppSettingsForm::apiProductListCallback public function Ajax callback for the "user_select" checkbox.
AppSettingsForm::buildForm public function Form constructor. Overrides ConfigFormBase::buildForm
AppSettingsForm::create public static function Instantiates a new instance of this class. Overrides ConfigFormBase::create
AppSettingsForm::getEditableConfigNames protected function Gets the configuration names that will be editable. Overrides ConfigFormBaseTrait::getEditableConfigNames
AppSettingsForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
AppSettingsForm::submitForm public function Form submission handler. Overrides ConfigFormBase::submitForm
AppSettingsForm::__construct public function AppSettingsForm constructor. Overrides ConfigFormBase::__construct
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.
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.