You are here

class Settings in CKEditor Bootstrap Grid 2.0.x

Configuration for CKEditor BS Grid.

Hierarchy

Expanded class hierarchy of Settings

1 string reference to 'Settings'
ckeditor_bs_grid.routing.yml in ./ckeditor_bs_grid.routing.yml
ckeditor_bs_grid.routing.yml

File

src/Form/Settings.php, line 13

Namespace

Drupal\ckeditor_bs_grid\Form
View source
class Settings extends ConfigFormBase {

  // Config item.
  const CONFIG_NAME = 'ckeditor_bs_grid.settings';

  /**
   * {@inheritDoc}
   */
  protected function getEditableConfigNames() {
    return [
      self::CONFIG_NAME,
    ];
  }

  /**
   * {@inheritDoc}
   */
  public function getFormId() {
    return 'ckeditor_bs_grid.settings';
  }

  /**
   * Helper to grab existing BS breakpoints.
   *
   * @todo make these configurable in the case of custom.
   *
   * @return array[]
   *   The available Breakpoints.
   */
  protected function getBreakpoints() {
    $breakpoints = [
      'xs' => [
        'bs_label' => $this
          ->t('Extra Smaill (xs)'),
        'prefix' => 'none',
      ],
      'sm' => [
        'bs_label' => $this
          ->t('Small (sm)'),
        'prefix' => 'sm',
      ],
      'md' => [
        'bs_label' => $this
          ->t('Medium (md)'),
        'prefix' => 'md',
      ],
      'lg' => [
        'bs_label' => $this
          ->t('Large (lg)'),
        'prefix' => 'lg',
      ],
      'xl' => [
        'bs_label' => $this
          ->t('Extra large (xl)'),
        'prefix' => 'xl',
      ],
      'xxl' => [
        'bs_label' => $this
          ->t('Extra extra large (xxl)'),
        'prefix' => 'xxl',
      ],
    ];
    return $breakpoints;
  }

  /**
   * {@inheritDoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $breakpoints = $this
      ->getBreakpoints();
    $config = $this
      ->configFactory()
      ->get(self::CONFIG_NAME)
      ->get('breakpoints');
    $message = $this
      ->t('Breakpoints and Number of columns can be enabled/disabled per text format in the @link.', [
      '@link' => Link::createFromRoute('editor settings page', 'filter.admin_overview')
        ->toString(),
    ]);
    $form['prefix'] = [
      '#type' => 'markup',
      '#markup' => Markup::create("<div class='messages messages--warning'>" . $message . "</div>"),
      '#weight' => -100,
    ];

    // Column Options. @todo make this configurable.
    $cols = [];
    for ($i = 1; $i <= 12; $i++) {
      $cols[$i] = $i;
    }
    $form['#tree'] = TRUE;
    foreach ($breakpoints as $break => $data) {
      $form[$break] = [
        '#title' => $data['bs_label'],
        '#type' => 'details',
        '#open' => FALSE,
      ];
      $form[$break]['label'] = [
        '#title' => $this
          ->t('Label'),
        '#type' => 'textfield',
        '#default_value' => $config[$break]['label'],
        '#required' => TRUE,
      ];
      $form[$break]['prefix'] = [
        '#title' => $this
          ->t('Prefix'),
        '#type' => 'textfield',
        '#default_value' => $data['prefix'],
        '#disabled' => TRUE,
        '#required' => TRUE,
      ];
      $form[$break]['columns'] = [
        '#title' => $this
          ->t('Available Column Layouts'),
        '#type' => 'details',
        '#description' => $this
          ->t('In the format of key|value, where the key is the attribute to add to each column, separated by a comma. Special tags are "auto" and "equal"'),
      ];
      $options = [
        'equal' => $this
          ->t('Equal'),
        'auto' => $this
          ->t('Auto'),
      ] + $cols;

      // For now this is static to 12.
      foreach ($cols as $col) {
        $form[$break]['columns'][$col]['layouts'] = [
          '#title' => $this
            ->t('@num Column Layout', [
            '@num' => $col,
          ]),
          '#type' => 'details',
          '#prefix' => '<div id="fieldset-wrapper-' . $break . '-' . $col . '">',
          '#suffix' => '</div>',
          '#open' => FALSE,
        ];
        $num_layouts = $form_state
          ->get('num_ ' . $break . '_' . $col);
        if ($num_layouts === NULL) {
          $num = count($config[$break]['columns'][$col]['layouts']);
          $form_state
            ->set('num_ ' . $break . '_' . $col, $num);
          $num_layouts = $num;
        }
        for ($i = 0; $i < $num_layouts; $i++) {
          $form[$break]['columns'][$col]['layouts']['option_' . $i]['label'] = [
            '#title' => $this
              ->t('Label'),
            '#type' => 'textfield',
            '#required' => TRUE,
            '#default_value' => $config[$break]['columns'][$col]['layouts']['option_' . $i]['label'] ?? $this
              ->t('Equal Width'),
          ];
          $form[$break]['columns'][$col]['layouts']['option_' . $i]['settings'] = [
            '#type' => 'container',
            '#attributes' => [
              'class' => [
                'container-inline',
              ],
            ],
          ];
          for ($j = 1; $j <= $col; $j++) {
            $form[$break]['columns'][$col]['layouts']['option_' . $i]['settings']['col-' . $j] = [
              '#title' => $j,
              '#type' => 'select',
              '#options' => $options,
              '#default_value' => $config[$break]['columns'][$col]['layouts']['option_' . $i]['settings']['col-' . $j],
            ];
          }

          // If there is more than one name, add the remove button.
          if ($num_layouts > 1) {
            $form[$break]['columns'][$col]['layouts']['option_' . $i]['settings']['remove'] = [
              '#type' => 'submit',
              '#value' => $this
                ->t('Remove'),
              '#submit' => [
                '::removeCallback',
              ],
              '#ajax' => [
                'callback' => '::ajaxCallback',
                'wrapper' => 'fieldset-wrapper-' . $break . '-' . $col,
              ],
              '#name' => 'remove-' . $break . '-' . $col,
            ];
          }
        }
        $form[$break]['columns'][$col]['layouts']['actions'] = [
          '#type' => 'actions',
        ];
        $form[$break]['columns'][$col]['layouts']['add_name'] = [
          '#type' => 'submit',
          '#value' => $this
            ->t('Add More'),
          '#submit' => [
            '::addOne',
          ],
          '#ajax' => [
            'callback' => '::ajaxCallback',
            'wrapper' => 'fieldset-wrapper-' . $break . '-' . $col,
          ],
          '#name' => 'add-' . $break . '-' . $col,
        ];
      }
    }
    return parent::buildForm($form, $form_state);
  }

  /**
   * {@inheritDoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    parent::submitForm($form, $form_state);
    $values = $form_state
      ->cleanValues()
      ->getValues();
    unset($values['actions']);
    $this
      ->configFactory()
      ->getEditable(self::CONFIG_NAME)
      ->set('breakpoints', $values)
      ->save();
  }

  /**
   * Callback for both ajax-enabled buttons.
   *
   * Selects and returns the fieldset with the names in it.
   */
  public function ajaxCallback(array &$form, FormStateInterface $form_state) {
    $trigger = $this
      ->getTriggerKey($form_state);
    $form[$trigger['break']]['columns'][$trigger['col']]['layouts']['#open'] = TRUE;
    return $form[$trigger['break']]['columns'][$trigger['col']]['layouts'];
  }

  /**
   * Submit handler for the "add-one-more" button.
   *
   * Increments the max counter and causes a rebuild.
   */
  public function addOne(array &$form, FormStateInterface $form_state) {
    $trigger = $this
      ->getTriggerKey($form_state);
    $value_key = 'num_ ' . $trigger['break'] . '_' . $trigger['col'];
    $num_layouts = $form_state
      ->get($value_key);
    $form_state
      ->set($value_key, $num_layouts + 1);
    $form_state
      ->setRebuild();
  }

  /**
   * Submit handler for the "remove one" button.
   *
   * Decrements the max counter and causes a form rebuild.
   */
  public function removeCallback(array &$form, FormStateInterface $form_state) {
    $trigger = $this
      ->getTriggerKey($form_state);
    $value_key = 'num_ ' . $trigger['break'] . '_' . $trigger['col'];
    $num_layouts = $form_state
      ->get($value_key);
    $form_state
      ->set($value_key, $num_layouts - 1);
    $form_state
      ->setRebuild();
  }

  /**
   * Helper to find the name of the trigger item.
   *
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state.
   *
   * @return array
   *   The keys to look for.
   */
  protected function getTriggerKey(FormStateInterface $form_state) {
    $trigger = $form_state
      ->getTriggeringElement();
    $parts = explode('-', $trigger['#name']);
    return [
      'break' => $parts[1],
      'col' => $parts[2],
    ];
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ConfigFormBase::create public static function Instantiates a new instance of this class. Overrides FormBase::create 18
ConfigFormBase::__construct public function Constructs a \Drupal\system\ConfigFormBase object. 16
ConfigFormBaseTrait::config protected function Retrieves a configuration object.
DependencySerializationTrait::$_entityStorages protected property
DependencySerializationTrait::$_serviceIds protected property
DependencySerializationTrait::__sleep public function 2
DependencySerializationTrait::__wakeup public function 2
FormBase::$configFactory protected property The config factory. 3
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. 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 protected property The messenger. 27
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.
Settings::addOne public function Submit handler for the "add-one-more" button.
Settings::ajaxCallback public function Callback for both ajax-enabled buttons.
Settings::buildForm public function Form constructor. Overrides ConfigFormBase::buildForm
Settings::CONFIG_NAME constant
Settings::getBreakpoints protected function Helper to grab existing BS breakpoints.
Settings::getEditableConfigNames protected function Gets the configuration names that will be editable. Overrides ConfigFormBaseTrait::getEditableConfigNames
Settings::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
Settings::getTriggerKey protected function Helper to find the name of the trigger item.
Settings::removeCallback public function Submit handler for the "remove one" button.
Settings::submitForm public function Form submission handler. Overrides ConfigFormBase::submitForm
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.