You are here

class SettingsForm in Dynamic Layouts 8

Provides a generic settings form for the DynamicLayouts.

Hierarchy

Expanded class hierarchy of SettingsForm

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

File

src/Form/SettingsForm.php, line 17

Namespace

Drupal\dynamic_layouts\Form
View source
class SettingsForm extends FormBase {

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

  /**
   * EditRowModalForm constructor.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entityTypeManager
   *   The entity type manager.
   */
  public function __construct(EntityTypeManagerInterface $entityTypeManager) {
    $this->entityTypeManager = $entityTypeManager;
  }

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

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

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

    /** @var \Drupal\dynamic_layouts\Entity\DynamicLayoutSettings $settings */
    $frontend_library_default = '';
    $column_prefix = '';
    $grid_column_count = '';
    if ($settings = $this->entityTypeManager
      ->getStorage('dynamic_layout_settings')
      ->load('settings')) {
      $frontend_library_default = $settings
        ->getFrontendLibrary();
      $column_prefix = $settings
        ->getColumnPrefix();
      $grid_column_count = $settings
        ->getGridColumnCount();
    }
    if ($frontend_library_default) {
      $this
        ->messenger()
        ->addWarning($this
        ->t('When changing the settings, all configured "Column width classes" will be purged.'));
    }
    $form[Constants::FRONTEND_LIBRARY] = array(
      '#type' => 'select',
      '#title' => t('Frontend library'),
      '#description' => t('Choose which frontend library you want to use for your layout.'),
      '#required' => TRUE,
      '#options' => [
        Constants::BOOTSTRAP => 'Bootstrap (v4)',
        Constants::CUSTOM => 'Custom..',
      ],
      '#default_value' => $frontend_library_default,
    );
    $form['column_prefix'] = array(
      '#type' => 'textfield',
      '#title' => t('Column prefix'),
      '#description' => t('Fill in you column prefix. As an example; Bootstrap uses "col" for prefix. A dash (-) will be added as a suffix.'),
      '#default_value' => $column_prefix,
      '#states' => [
        'visible' => [
          'select[name="frontend_library"]' => [
            'value' => Constants::CUSTOM,
          ],
        ],
        'required' => [
          'select[name="frontend_library"]' => [
            'value' => Constants::CUSTOM,
          ],
        ],
      ],
    );
    $form['grid_column_count'] = array(
      '#type' => 'select',
      '#title' => t('Grid column count'),
      '#description' => t('What is your column count in your grid?'),
      '#options' => [
        '6' => '6 columns grid',
        '8' => '8 columns grid',
        '12' => '12 columns grid',
      ],
      '#default_value' => $grid_column_count,
      '#states' => [
        'visible' => [
          'select[name="frontend_library"]' => [
            'value' => Constants::CUSTOM,
          ],
        ],
        'required' => [
          'select[name="frontend_library"]' => [
            'value' => Constants::CUSTOM,
          ],
        ],
      ],
    );
    $form['actions']['#type'] = 'actions';
    $form['actions']['submit'] = array(
      '#type' => 'submit',
      '#value' => $this
        ->t('Save'),
      '#button_type' => 'primary',
    );
    return $form;
  }

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

    /** @var \Drupal\dynamic_layouts\DynamicLayoutSettingsInterface $settings */
    if (!($settings = $this->entityTypeManager
      ->getStorage('dynamic_layout_settings')
      ->load('settings'))) {
      return NULL;
    }
    if ($form_state
      ->getValue(Constants::FRONTEND_LIBRARY) == Constants::BOOTSTRAP) {
      $url = Url::fromUri('https://www.drupal.org/project/bootstrap_library');
      $link = Link::fromTextAndUrl(t('bootstrap_library'), $url)
        ->toString();

      // Display a message.
      $this
        ->messenger()
        ->addWarning(t('You have selected Bootstrap, to display the layout properly in the frontend: install the @link module & select version 4.x or implement Bootstrap (v4) in your theme.', [
        '@link' => $link,
      ]));
    }
    $old_frontend_library = $settings
      ->getFrontendLibrary();

    // Display a message to create a layout,
    // only when we had no frontend library.
    if (!$old_frontend_library) {
      $new_layout_link = Link::fromTextAndUrl(t('click here'), Url::fromRoute('dynamic_layout.dynamic_layout_add'))
        ->toString();

      // Display a message.
      $this
        ->messenger()
        ->addStatus(t('Settings have been saved, @link to add a Dynamic Layout!', array(
        '@link' => $new_layout_link,
      )));
    }
    $new_column_prefix = $form_state
      ->getValue('column_prefix');
    $new_grid_column_count = $form_state
      ->getValue('grid_column_count');

    // Set the form values.
    if ($new_frontend_library = $form_state
      ->getValue(Constants::FRONTEND_LIBRARY)) {

      // Get the last column number, we set this after purging the old ones.
      $last_column_number = $settings
        ->getLastColumnNumber($new_frontend_library, $new_column_prefix, $new_grid_column_count);
      if ($new_frontend_library == Constants::BOOTSTRAP) {
        $new_column_prefix = 'col';
      }
      $this
        ->updateValues($new_column_prefix, $new_grid_column_count, $last_column_number, $old_frontend_library, $new_frontend_library, $settings);
    }
    $settings
      ->save();
  }

  /**
   * Update the setting values.
   *
   * @param string $new_column_prefix
   *   The new column prefix.
   * @param int $new_grid_column_count
   *   The new grid column count.
   * @param int $last_column_number
   *   The last column number.
   * @param object $old_frontend_library
   *   The old frontend library.
   * @param object $new_frontend_library
   *   The new frontend library.
   * @param \Drupal\dynamic_layouts\DynamicLayoutSettingsInterface $settings
   *   The settings object.
   */
  public function updateValues($new_column_prefix, $new_grid_column_count, $last_column_number, $old_frontend_library, $new_frontend_library, DynamicLayoutSettingsInterface $settings) {

    // Column prefix changed?
    if ($new_column_prefix) {
      $old_column_prefix = $settings
        ->getColumnPrefix();
      if ($old_column_prefix != $new_column_prefix) {
        $settings
          ->purgeColumnWidthNumbers($last_column_number, $new_column_prefix);
      }
      $settings
        ->setColumnPrefix($new_column_prefix);
    }

    // Grid column count changed?
    if ($new_grid_column_count) {
      $old_grid_column_count = $settings
        ->getGridColumnCount();
      if ($old_grid_column_count != $new_grid_column_count) {
        $settings
          ->purgeColumnWidthNumbers($last_column_number);
      }
      $settings
        ->setGridColumnCount($new_grid_column_count);
    }

    // Frontend library changed?
    if ($old_frontend_library != $new_frontend_library) {
      $settings
        ->purgeColumnWidthNumbers($last_column_number, $new_column_prefix);
      if ($old_frontend_library) {
        $this
          ->messenger()
          ->addError($this
          ->t('All column widths have been purged, please reconfigure your layouts!'));
      }
      $settings
        ->setFrontendLibrary($new_frontend_library);
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
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::config protected function Retrieves a configuration object.
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.
SettingsForm::$entityTypeManager protected property The entity type manager.
SettingsForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
SettingsForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
SettingsForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
SettingsForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
SettingsForm::updateValues public function Update the setting values.
SettingsForm::__construct public function EditRowModalForm constructor.
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.