You are here

class SettingsForm in Entity Print 8

Same name and namespace in other branches
  1. 8.2 src/Form/SettingsForm.php \Drupal\entity_print\Form\SettingsForm

Defines a form that configures Entity Print settings.

Hierarchy

Expanded class hierarchy of SettingsForm

1 string reference to 'SettingsForm'
entity_print.routing.yml in ./entity_print.routing.yml
entity_print.routing.yml

File

src/Form/SettingsForm.php, line 16

Namespace

Drupal\entity_print\Form
View source
class SettingsForm extends ConfigFormBase {

  /**
   * The Pdf engine plugin manager.
   *
   * @var \Drupal\entity_print\Plugin\EntityPrintPluginManager
   */
  protected $pluginManager;

  /**
   * The entity config storage.
   *
   * @var \Drupal\Core\Entity\EntityStorageInterface
   */
  protected $storage;

  /**
   * Constructs a \Drupal\system\ConfigFormBase object.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The factory for configuration objects.
   * @param \Drupal\entity_print\Plugin\EntityPrintPluginManager $plugin_manager
   *   The plugin manager object.
   * @param \Drupal\Core\Entity\EntityStorageInterface $entity_storage
   *   The config storage.
   */
  public function __construct(ConfigFactoryInterface $config_factory, EntityPrintPluginManager $plugin_manager, EntityStorageInterface $entity_storage) {
    parent::__construct($config_factory);
    $this->pluginManager = $plugin_manager;
    $this->storage = $entity_storage;
  }

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

  /**
   * {@inheritdoc}
   */
  public function getFormID() {
    return 'entity_print_admin_settings_form';
  }

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, Request $request = NULL) {
    $disabled_engines = [];
    $pdf_engines = [];
    foreach ($this->pluginManager
      ->getDefinitions() as $plugin_id => $definition) {

      /** @var \Drupal\entity_print\Plugin\PdfEngineInterface $class */
      $class = $definition['class'];
      if ($class::dependenciesAvailable()) {
        $pdf_engines[$plugin_id] = $definition['label'];
      }
      else {
        $disabled_engines[$plugin_id] = $definition['label'];

        // Show the user which PDF engines are disabled, but only for the page load
        // not on AJAX requests.
        if (!$request
          ->isXmlHttpRequest()) {
          drupal_set_message($this
            ->t('@name is not available because it is not configured. @installation.', [
            '@name' => $definition['label'],
            '@installation' => $class::getInstallationInstructions(),
          ]), 'warning');
        }
      }
    }
    $config = $this
      ->config('entity_print.settings');
    $form['entity_print'] = [
      '#type' => 'fieldset',
      '#title' => $this
        ->t('Entity Print Config'),
    ];
    $form['entity_print']['default_css'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Enable Default CSS'),
      '#description' => $this
        ->t('Provides some very basic font and padding styles.'),
      '#default_value' => $config
        ->get('default_css'),
    ];
    $form['entity_print']['force_download'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Force Download'),
      '#description' => $this
        ->t('This option will attempt to force the browser to download the PDF with a filename from the node title.'),
      '#default_value' => $config
        ->get('force_download'),
    ];
    $form['entity_print']['pdf_engine'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Pdf Engine'),
      '#description' => $this
        ->t('Select the PDF engine to render the PDF'),
      '#options' => $pdf_engines,
      '#default_value' => $config
        ->get('pdf_engine'),
      '#empty_option' => $this
        ->t('- None -'),
      '#ajax' => [
        'callback' => '::ajaxPluginFormCallback',
        'wrapper' => 'pdf-engine-config',
        'effect' => 'fade',
      ],
    ];
    $form['entity_print']['pdf_engine_config'] = [
      '#type' => 'container',
      '#id' => 'pdf-engine-config',
    ];

    // If we have a pdf_engine in the form_state then use that otherwise, fall
    // back to what was saved as this is a fresh form. Check explicitly for NULL
    // in case they selected the None option which is false'y.
    $plugin_id = !is_null($form_state
      ->getValue('pdf_engine')) ? $form_state
      ->getValue('pdf_engine') : $config
      ->get('pdf_engine');

    // If we have a plugin id and the plugin hasn't since been disabled then we
    // load the config for the plugin.
    if ($plugin_id && !in_array($plugin_id, array_keys($disabled_engines), TRUE)) {
      $form['entity_print']['pdf_engine_config'][$plugin_id] = $this
        ->getPluginForm($plugin_id, $form_state);
    }
    return parent::buildForm($form, $form_state);
  }

  /**
   * Ajax form callback.
   */
  public function ajaxPluginFormCallback(&$form, FormStateInterface $form_state) {
    return $form['entity_print']['pdf_engine_config'];
  }

  /**
   * Gets a configuration form for the given plugin.
   *
   * @param string $plugin_id
   *   The plugin id for which we want the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state object.
   *
   * @return array
   *   The sub form structure for this plugin.
   */
  protected function getPluginForm($plugin_id, FormStateInterface $form_state) {
    $plugin = $this->pluginManager
      ->createInstance($plugin_id);
    $form = [
      '#type' => 'fieldset',
      '#title' => $this
        ->t('@engine Settings', [
        '@engine' => $plugin
          ->getPluginDefinition()['label'],
      ]),
    ];
    return $form + $plugin
      ->buildConfigurationForm([], $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    parent::validateForm($form, $form_state);
    if ($plugin_id = $form_state
      ->getValue('pdf_engine')) {

      // Load the config entity, submit the relevant plugin form and then save
      // it.
      $entity = $this
        ->loadConfigEntity($plugin_id);

      /** @var \Drupal\entity_print\Plugin\PdfEngineInterface $plugin */
      $plugin = $entity
        ->getPdfEnginePluginCollection()
        ->get($entity
        ->id());
      $plugin
        ->validateConfigurationForm($form, $form_state);
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    if ($plugin_id = $form_state
      ->getValue('pdf_engine')) {

      // Load the config entity, submit the relevant plugin form and then save
      // it.
      $entity = $this
        ->loadConfigEntity($plugin_id);

      /** @var \Drupal\entity_print\Plugin\PdfEngineInterface $plugin */
      $plugin = $entity
        ->getPdfEnginePluginCollection()
        ->get($entity
        ->id());
      $plugin
        ->submitConfigurationForm($form, $form_state);
      $entity
        ->save();
    }

    // Save the global settings.
    $values = $form_state
      ->getValues();
    $this
      ->config('entity_print.settings')
      ->set('default_css', $values['default_css'])
      ->set('force_download', $values['force_download'])
      ->set('pdf_engine', $values['pdf_engine'])
      ->save();
  }

  /**
   * Gets the config entity backing the specified plugin.
   *
   * @param string $plugin_id
   *   The PDF engine plugin id.
   *
   * @return \Drupal\entity_print\Entity\PdfEngine
   *   The loaded config object backing the plugin.
   */
  protected function loadConfigEntity($plugin_id) {
    if (!($entity = $this->storage
      ->load($plugin_id))) {
      $entity = $this->storage
        ->create([
        'id' => $plugin_id,
      ]);
    }
    return $entity;
  }

}

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.
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.
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.
SettingsForm::$pluginManager protected property The Pdf engine plugin manager.
SettingsForm::$storage protected property The entity config storage.
SettingsForm::ajaxPluginFormCallback public function Ajax form callback.
SettingsForm::buildForm public function Form constructor. Overrides ConfigFormBase::buildForm
SettingsForm::create public static function Instantiates a new instance of this class. Overrides ConfigFormBase::create
SettingsForm::getEditableConfigNames protected function Gets the configuration names that will be editable. Overrides ConfigFormBaseTrait::getEditableConfigNames
SettingsForm::getFormID public function
SettingsForm::getPluginForm protected function Gets a configuration form for the given plugin.
SettingsForm::loadConfigEntity protected function Gets the config entity backing the specified plugin.
SettingsForm::submitForm public function Form submission handler. Overrides ConfigFormBase::submitForm
SettingsForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
SettingsForm::__construct public function Constructs a \Drupal\system\ConfigFormBase 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.