You are here

class BackgroundImageSettingsForm in Background Image 2.0.x

Same name and namespace in other branches
  1. 8 src/Form/BackgroundImageSettingsForm.php \Drupal\background_image\Form\BackgroundImageSettingsForm
  2. 2.x src/Form/BackgroundImageSettingsForm.php \Drupal\background_image\Form\BackgroundImageSettingsForm

Class BackgroundImageSettingsForm.

Hierarchy

Expanded class hierarchy of BackgroundImageSettingsForm

1 string reference to 'BackgroundImageSettingsForm'
background_image.routing.yml in ./background_image.routing.yml
background_image.routing.yml

File

src/Form/BackgroundImageSettingsForm.php, line 17

Namespace

Drupal\background_image\Form
View source
class BackgroundImageSettingsForm extends ConfigFormBase {
  use BackgroundImageFormTrait;

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

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form = parent::buildForm($form, $form_state);
    $form['#attached']['library'][] = 'background_image/admin';
    $inline_entity_form = \Drupal::moduleHandler()
      ->moduleExists('inline_entity_form');
    $inline_entity_form_tip = $this
      ->t('The Inline Entity Form module is required to embed forms.');
    $background_image_manager = BackgroundImageManager::service();
    $supported_entity_types = $background_image_manager
      ->getSupportedEntityTypes();
    $config = $this
      ->config('background_image.settings');
    $form['vertical_tabs'] = [
      '#type' => 'vertical_tabs',
    ];

    // Enabled Entities.
    $form['entities'] = [
      '#group' => 'vertical_tabs',
      '#type' => 'details',
      '#title' => $this
        ->t('Entities'),
      '#description' => $this
        ->t('Configure how entities and bundles are associated with background images. Only the "full" view mode of an entity will trigger the condition in which the associated background image will be used.'),
      '#open' => TRUE,
    ];
    if (!$inline_entity_form) {
      $form['entities']['inline_entity_form']['#markup'] = $this
        ->t('If you wish to embed the background image form while editing an entity, you will need install the @inline_entity_form module.', [
        '@inline_entity_form' => Link::fromTextAndUrl('Inline Entity Form', Url::fromUri('https://www.drupal.org/project/inline_entity_form'))
          ->toString(),
      ]);
    }

    // Iterate over each supported entity type.
    $form['entities']['table'] = [
      '#type' => 'table',
      '#sticky' => TRUE,
      '#attributes' => [
        'class' => [
          'entities',
        ],
      ],
      '#header' => [
        [
          'data' => $this
            ->t('Entity/Bundle'),
        ],
        [
          'data' => $this
            ->t('Enable'),
          'class' => [
            'small',
          ],
        ],
        [
          'data' => $this
            ->t('Embed'),
          'class' => [
            'small',
          ],
        ],
        [
          'data' => $this
            ->t('Require'),
          'class' => [
            'small',
          ],
        ],
      ],
      '#tree' => FALSE,
    ];
    $rows = [];
    foreach ($supported_entity_types as $type => $entity_type) {
      $row = [];
      $row[] = [
        'data' => $entity_type
          ->getLabel(),
        'colspan' => 5,
        'class' => [
          'entity-type',
        ],
      ];
      $rows[] = $row;
      if ($bundles = $background_image_manager
        ->getEntityTypeBundles($entity_type)) {
        foreach ($bundles as $bundle => $info) {
          $row = [];
          $row[] = [
            'data' => $info['label'],
            'class' => [
              'entity-bundle',
            ],
          ];

          // Enable.
          $form["entities-{$type}-{$bundle}-enable"] = [
            '#type' => 'checkbox',
            '#parents' => [
              'entities',
              $type,
              $bundle,
              'enable',
            ],
            '#default_value' => !!$config
              ->get(implode('.', [
              'entities',
              $type,
              $bundle,
              'enable',
            ])),
          ];

          // Embed/group.
          $form["entities-{$type}-{$bundle}-embed"] = [
            '#type' => 'container',
          ];
          $form["entities-{$type}-{$bundle}-embed"]['embed'] = [
            '#type' => 'checkbox',
            '#parents' => [
              'entities',
              $type,
              $bundle,
              'embed',
            ],
            '#default_value' => !!$config
              ->get(implode('.', [
              'entities',
              $type,
              $bundle,
              'embed',
            ])),
          ];
          $form["entities-{$type}-{$bundle}-embed"]['group'] = [
            '#type' => 'select',
            '#parents' => [
              'entities',
              $type,
              $bundle,
              'group',
            ],
            '#default_value' => $config
              ->get(implode('.', [
              'entities',
              $type,
              $bundle,
              'group',
            ])),
            '#attributes' => [
              'title' => $this
                ->t('The group in which the background image form will be embedded into (if it exists).'),
            ],
            '#options' => [
              '' => $this
                ->t('Default'),
              'advanced' => $this
                ->t('Advanced'),
            ],
          ];
          if (!$inline_entity_form) {
            $form["entities-{$type}-{$bundle}-embed"]['embed']['#disabled'] = TRUE;
            $form["entities-{$type}-{$bundle}-embed"]['embed']['#default_value'] = FALSE;
            $form["entities-{$type}-{$bundle}-embed"]['embed']['#attributes']['title'] = $inline_entity_form_tip;
            $form["entities-{$type}-{$bundle}-embed"]['group']['#disabled'] = TRUE;
            $form["entities-{$type}-{$bundle}-embed"]['group']['#default_value'] = '';
          }
          else {
            self::addState($form["entities-{$type}-{$bundle}-embed"]['embed'], [
              'enabled',
            ], $form["entities-{$type}-{$bundle}-enable"], [
              '*' => [
                'checked' => TRUE,
              ],
            ]);
            self::addState($form["entities-{$type}-{$bundle}-embed"]['group'], [
              'enabled',
            ], $form["entities-{$type}-{$bundle}-enable"], [
              '*' => [
                'checked' => TRUE,
              ],
            ]);
            self::addState($form["entities-{$type}-{$bundle}-embed"]['group'], [
              'enabled',
            ], $form["entities-{$type}-{$bundle}-embed"], [
              '*' => [
                'checked' => TRUE,
              ],
            ]);
          }

          // Require
          $form["entities-{$type}-{$bundle}-require"] = [
            '#type' => 'checkbox',
            '#parents' => [
              'entities',
              $type,
              $bundle,
              'require',
            ],
            '#default_value' => !!$config
              ->get(implode('.', [
              'entities',
              $type,
              $bundle,
              'require',
            ])),
          ];
          self::addState($form["entities-{$type}-{$bundle}-require"], [
            'enabled',
          ], $form["entities-{$type}-{$bundle}-enable"], [
            '*' => [
              'checked' => TRUE,
            ],
          ]);

          // Add the form elements to the row.
          foreach ([
            'enable',
            'embed',
            'require',
          ] as $property) {
            $row[] = [
              'data' => &$form["entities-{$type}-{$bundle}-{$property}"],
              'class' => [
                'small',
              ],
            ];
            $form["entities-{$type}-{$bundle}-{$property}"]['#printed'] = TRUE;
          }

          // Add the row to the rows.
          $rows[] = $row;
        }
      }
    }
    $form['entities']['table']['#rows'] = $rows;
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    parent::submitForm($form, $form_state);
    $this
      ->config('background_image.settings')
      ->merge(array_filter($form_state
      ->cleanValues()
      ->getValues()))
      ->save();
  }

}

Members

Namesort descending Modifiers Type Description Overrides
BackgroundImageFormTrait::$backgroundImageManager protected static property
BackgroundImageFormTrait::$elementInfoManager protected static property
BackgroundImageFormTrait::$form protected property
BackgroundImageFormTrait::$formState protected property
BackgroundImageFormTrait::$subform protected property
BackgroundImageFormTrait::$subformState protected property
BackgroundImageFormTrait::$subformValues protected property
BackgroundImageFormTrait::$tokenEntityMapper protected static property
BackgroundImageFormTrait::$tokenExists protected static property
BackgroundImageFormTrait::addState public static function Provides a way to add #states to an element, but in a deferred way.
BackgroundImageFormTrait::addTokenBrowser public static function Adds a "Browse available tokens" link to the specified element.
BackgroundImageFormTrait::appendCallback public static function Appends a callback to an element.
BackgroundImageFormTrait::arrayFilter public static function Filters a nested array recursively, from the bottom up.
BackgroundImageFormTrait::attachSubmitHandler public static function Attaches a submit handler to the given form.
BackgroundImageFormTrait::attachValidationHandler public static function Attaches a submit handler to the given form.
BackgroundImageFormTrait::createGroup public static function Creates a new group in the form, assigning child elements as needed.
BackgroundImageFormTrait::findFirstInput public static function Retrieves first available #input element, going through children if needed.
BackgroundImageFormTrait::getBackgroundImageManager public static function Retrieves the Background Image Manager service.
BackgroundImageFormTrait::getElementInfo public static function Retrieves default element info or a property from it.
BackgroundImageFormTrait::getElementInfoManager public static function Retrieves the Element Info Manager service.
BackgroundImageFormTrait::getSubformValue public function Retrieves a subform value.
BackgroundImageFormTrait::getSubformValues public function
BackgroundImageFormTrait::getTokenEntityMapper public static function Retrieves the Token Entity Mapper service.
BackgroundImageFormTrait::getValues public function Implements \Drupal\Core\Form\FormStateInterface::getValues() Overrides FormStateValuesTrait::getValues
BackgroundImageFormTrait::initForm public static function Retrieves existing instance or creates new one from form state.
BackgroundImageFormTrait::initSubform public static function Retrieves existing instance or creates new one from form state.
BackgroundImageFormTrait::initWithFormState public static function Retrieves existing instance or creates new one from form state.
BackgroundImageFormTrait::mapStatesConditions public static function Recursively maps a selector for a set of #states conditions.
BackgroundImageFormTrait::prependCallback public static function Prepends a callback to an element.
BackgroundImageFormTrait::preRenderStates public static function The #pre_render callback for ::addState.
BackgroundImageFormTrait::setForm public function Sets the form.
BackgroundImageFormTrait::setFormState public function Sets the current FormState object.
BackgroundImageFormTrait::setSubform public function Sets a subform element.
BackgroundImageFormTrait::setSubformState public function Sets the subform state, if one exists.
BackgroundImageFormTrait::setSubformValue public function Implements \Drupal\Core\Form\FormStateInterface::setValue()
BackgroundImageFormTrait::setSubformValues public function Implements \Drupal\Core\Form\FormStateInterface::setValues()
BackgroundImageFormTrait::tokenExists public static function Determines if the "token" module exists.
BackgroundImageFormTrait::unsetSubformValue public function Implements \Drupal\Core\Form\FormStateInterface::unsetValue()
BackgroundImageSettingsForm::buildForm public function Form constructor. Overrides ConfigFormBase::buildForm
BackgroundImageSettingsForm::getEditableConfigNames protected function Gets the configuration names that will be editable. Overrides ConfigFormBaseTrait::getEditableConfigNames
BackgroundImageSettingsForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
BackgroundImageSettingsForm::submitForm public function Form submission handler. Overrides ConfigFormBase::submitForm
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
FormStateValuesTrait::getValue public function Implements \Drupal\Core\Form\FormStateInterface::getValue()
FormStateValuesTrait::hasValue public function Implements \Drupal\Core\Form\FormStateInterface::hasValue()
FormStateValuesTrait::isValueEmpty public function Implements \Drupal\Core\Form\FormStateInterface::isValueEmpty()
FormStateValuesTrait::setValue public function Implements \Drupal\Core\Form\FormStateInterface::setValue()
FormStateValuesTrait::setValueForElement public function Implements \Drupal\Core\Form\FormStateInterface::setValueForElement()
FormStateValuesTrait::setValues public function Implements \Drupal\Core\Form\FormStateInterface::setValues()
FormStateValuesTrait::unsetValue public function Implements \Drupal\Core\Form\FormStateInterface::unsetValue()
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.
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.