You are here

class FormatConfigurationFormPdf in Printer and PDF versions for Drupal 8+ 2.x

Same name and namespace in other branches
  1. 8 src/Form/FormatConfigurationFormPdf.php \Drupal\printable\Form\FormatConfigurationFormPdf

Provides shared configuration form for all printable formats.

Hierarchy

Expanded class hierarchy of FormatConfigurationFormPdf

1 string reference to 'FormatConfigurationFormPdf'
printable.routing.yml in ./printable.routing.yml
printable.routing.yml

File

src/Form/FormatConfigurationFormPdf.php, line 16

Namespace

Drupal\printable\Form
View source
class FormatConfigurationFormPdf extends FormBase {

  /**
   * The printable entity manager.
   *
   * @var \Drupal\printable\PrintableEntityManagerInterface
   */
  protected $printableEntityManager;

  /**
   * The config factory service.
   *
   * @var \Drupal\Core\Config\ConfigFactory
   */
  protected $configFactory;

  /**
   * The messenger service.
   *
   * @var \Drupal\Core\Messenger\MessengerInterface
   */
  protected $messenger;

  /**
   * Constructs a new form object.
   *
   * @param \Drupal\printable\PrintableEntityManagerInterface $printable_entity_manager
   *   The printable entity manager.
   * @param \Drupal\Core\Config\ConfigFactory $configFactory
   *   Defines the configuration object factory.
   * @param \Drupal\Core\Messenger\MessengerInterface $messenger
   *   The messenger service.
   * @param \Drupal\Core\Extension\ModuleHandler $moduleHandler
   *   The module handler service.
   */
  public function __construct(PrintableEntityManagerInterface $printable_entity_manager, ConfigFactory $configFactory, MessengerInterface $messenger, ModuleHandler $moduleHandler) {
    $this->printableEntityManager = $printable_entity_manager;
    $this->configFactory = $configFactory;
    $this->messenger = $messenger;
    $this->moduleHandler = $moduleHandler;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('printable.entity_manager'), $container
      ->get('config.factory'), $container
      ->get('messenger'), $container
      ->get('module_handler'));
  }

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, $printable_format = NULL) {
    $wkhtmltopdf_present = class_exists('mikehaertl\\wkhtmlto\\Pdf');
    $mpdf_present = class_exists('Mpdf\\Mpdf');
    $tcpdf_present = class_exists('TCPDF');
    $dompdf_present = class_exists('Dompdf\\Dompdf');
    if ($wkhtmltopdf_present || $mpdf_present || $tcpdf_present || $dompdf_present) {
      $form['settings']['print_pdf_pdf_tool'] = [
        '#type' => 'radios',
        '#title' => $this
          ->t('PDF generation tool'),
        '#options' => [],
        '#default_value' => $this
          ->config('printable.settings')
          ->get('pdf_tool'),
        '#description' => $this
          ->t('This option selects the PDF generation tool being used by this module to create the PDF version.'),
      ];
    }
    else {
      $this
        ->messenger()
        ->addStatus($this
        ->t('You are seeing no PDF generating tool because you have not installed any third party library using composer.'));
    }
    if ($mpdf_present) {
      $form['settings']['print_pdf_pdf_tool']['#options'] += [
        'mPDF' => 'mPDF',
      ];
    }
    if ($tcpdf_present) {
      $form['settings']['print_pdf_pdf_tool']['#options'] += [
        'TCPDF' => 'TCPDF',
      ];
    }
    if ($wkhtmltopdf_present) {
      $form['settings']['print_pdf_pdf_tool']['#options'] += [
        'wkhtmltopdf' => 'wkhtmltopdf',
      ];
    }
    if ($dompdf_present) {
      $form['settings']['print_pdf_pdf_tool']['#options'] += [
        'dompdf' => 'dompdf',
      ];
    }
    $form['settings']['print_pdf_content_disposition'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Save the pdf'),
      '#description' => $this
        ->t('Save the pdf instead of showing inline'),
      '#default_value' => $this
        ->config('printable.settings')
        ->get('save_pdf'),
    ];
    $form['settings']['print_pdf_ignore_warnings'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Ignore warnings'),
      '#description' => $this
        ->t('Use the generated PDF even if warnings are indicated'),
      '#default_value' => $this
        ->config('printable.settings')
        ->get('ignore_warnings'),
    ];
    $form['settings']['print_pdf_paper_size'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Paper size'),
      '#options' => [],
      '#default_value' => (string) $this
        ->config('printable.settings')
        ->get('paper_size'),
      '#description' => $this
        ->t('Choose the paper size of the generated PDF.'),
    ];
    $paper_sizes = [
      'A0',
      'A1',
      'A2',
      'A3',
      'A4',
      'A5',
      'A6',
      'A7',
      'A8',
      'A9',
      'B0',
      'B1',
      'B10',
      'B2',
      'B3',
      'B4',
      'B5',
      'B6',
      'B7',
      'B8',
      'B9',
      'C5E',
      'Comm10E',
      'DLE',
      'Executive',
      'Folio',
      'Ledger',
      'Legal',
      'Letter',
      'Tabloid',
    ];
    foreach ($paper_sizes as $sizes) {
      $form['settings']['print_pdf_paper_size']['#options'][$sizes] = $sizes;
    }
    $form['settings']['print_pdf_page_orientation'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Page orientation'),
      '#options' => [
        'portrait' => $this
          ->t('Portrait'),
        'landscape' => $this
          ->t('Landscape'),
      ],
      '#default_value' => $this
        ->config('printable.settings')
        ->get('page_orientation'),
      '#description' => $this
        ->t('Choose the page orientation of the generated PDF.'),
    ];
    $token_help = '';
    $token_args = [];
    if ($this->moduleHandler
      ->moduleExists('token')) {
      $build = [
        '#type' => 'container',
        'token_tree_link' => [
          '#theme' => 'token_tree_link',
          '#token_types' => [
            'all',
          ],
          '#click_insert' => TRUE,
          '#dialog' => TRUE,
        ],
      ];
      $token_args = [
        '@browse_tokens_link' => \Drupal::service('renderer')
          ->render($build),
      ];
      $token_help = ' This field supports tokens: @browse_tokens_link';
    }
    $form['settings']['print_pdf_filename'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('PDF filename'),
      '#default_value' => $this
        ->config('printable.settings')
        ->get('pdf_location'),
      '#description' => t("Filename with its location can be entered. If left empty and Save the pdf option has been selected the generated filename defaults to the node's path.The .pdf extension will be appended automatically." . $token_help, $token_args),
    ];
    $form['settings']['print_pdf_filename']['#element_validate'][] = 'token_element_validate';
    $form['settings']['print_pdf_filename'] += [
      '#token_types' => [
        'all',
      ],
    ];
    if ($wkhtmltopdf_present) {
      $form['settings']['path_to_binary'] = [
        '#type' => 'textfield',
        '#title' => $this
          ->t('Path to binary file'),
        '#default_value' => $this
          ->config('printable.settings')
          ->get('path_to_binary'),
        '#description' => $this
          ->t("Enter the path to binary file for wkhtmltopdf over here."),
        '#states' => [
          'visible' => [
            'input[name="print_pdf_pdf_tool"]' => [
              'value' => 'wkhtmltopdf',
            ],
          ],
        ],
      ];
      $form['settings']['print_pdf_use_xvfb_run'] = [
        '#type' => 'checkbox',
        '#title' => $this
          ->t('Use Xvfb-run'),
        '#description' => $this
          ->t('Enable this option if you get an error "QXcbConnection: Could not connect to display Aborted (core dumped)" when seeking to generate PDFs.'),
        '#default_value' => $this
          ->config('printable.settings')
          ->get('print_pdf_use_xvfb_run'),
        '#states' => [
          'visible' => [
            'input[name="print_pdf_pdf_tool"]' => [
              'value' => 'wkhtmltopdf',
            ],
          ],
        ],
      ];
      $form['settings']['path_to_xfb_run'] = [
        '#type' => 'textfield',
        '#title' => $this
          ->t('Path to Xvfb-run binary file'),
        '#default_value' => $this
          ->config('printable.settings')
          ->get('path_to_xfb_run'),
        '#description' => $this
          ->t("Enter the path to binary file for Xvfb-run over here."),
        '#states' => [
          'visible' => [
            'input[name="print_pdf_pdf_tool"]' => [
              'value' => 'wkhtmltopdf',
            ],
            'input[name="print_pdf_use_xvfb_run"]' => [
              'checked' => TRUE,
            ],
          ],
        ],
      ];
    }
    $form['settings']['submit'] = [
      '#type' => 'submit',
      '#value' => 'Submit',
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $pdf_tool = $this
      ->config('printable.settings')
      ->get('pdf_tool');
    $this->configFactory
      ->getEditable('printable.settings')
      ->set('pdf_tool', $form_state
      ->getValue('print_pdf_pdf_tool'))
      ->set('save_pdf', $form_state
      ->getValue('print_pdf_content_disposition'))
      ->set('ignore_warnings', $form_state
      ->getValue('print_pdf_ignore_warnings'))
      ->set('paper_size', (string) $form_state
      ->getValue('print_pdf_paper_size'))
      ->set('page_orientation', $form_state
      ->getValue('print_pdf_page_orientation'))
      ->set('pdf_location', $form_state
      ->getValue('print_pdf_filename'))
      ->save();
    if (class_exists('mikehaertl\\wkhtmlto\\Pdf') && $pdf_tool == 'wkhtmltopdf') {
      $this->configFactory
        ->getEditable('printable.settings')
        ->set('path_to_binary', $form_state
        ->getValue('path_to_binary'))
        ->set('print_pdf_use_xvfb_run', $form_state
        ->getValue('print_pdf_use_xvfb_run'))
        ->set('path_to_xfb_run', $form_state
        ->getValue('path_to_xfb_run'))
        ->save();
    }
    $this
      ->messenger()
      ->addStatus($this
      ->t('The configuration option has been saved'));
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property
DependencySerializationTrait::$_serviceIds protected property
DependencySerializationTrait::__sleep public function 2
DependencySerializationTrait::__wakeup public function 2
FormatConfigurationFormPdf::$configFactory protected property The config factory service. Overrides FormBase::$configFactory
FormatConfigurationFormPdf::$messenger protected property The messenger service. Overrides MessengerTrait::$messenger
FormatConfigurationFormPdf::$printableEntityManager protected property The printable entity manager.
FormatConfigurationFormPdf::buildForm public function Form constructor. Overrides FormInterface::buildForm
FormatConfigurationFormPdf::create public static function Instantiates a new instance of this class. Overrides FormBase::create
FormatConfigurationFormPdf::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
FormatConfigurationFormPdf::submitForm public function Form submission handler. Overrides FormInterface::submitForm
FormatConfigurationFormPdf::__construct public function Constructs a new form object.
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::config protected function Retrieves a configuration object.
FormBase::configFactory protected function Gets the config factory for this form. 3
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.
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 72
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 public function Gets the messenger. 27
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. 4
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.