You are here

class BetterFieldDescriptionsFieldsForm in Better Field Descriptions 8

Displays the better_field_descriptions_fields settings form.

Hierarchy

Expanded class hierarchy of BetterFieldDescriptionsFieldsForm

1 string reference to 'BetterFieldDescriptionsFieldsForm'
better_field_descriptions.routing.yml in ./better_field_descriptions.routing.yml
better_field_descriptions.routing.yml

File

src/Form/BetterFieldDescriptionsFieldsForm.php, line 16

Namespace

Drupal\better_field_descriptions\Form
View source
class BetterFieldDescriptionsFieldsForm extends ConfigFormBase {

  /**
   * EntityFieldManagerservices object.
   *
   * @var \Drupal\Core\Entity\EntityFieldManager
   */
  private $entityFieldManager;

  /**
   * The bundle info service.
   *
   * @var \Drupal\Core\Entity\EntityTypeBundleInfoInterface
   */
  protected $bundleInfoService;

  /**
   * {@inheritdoc}
   */
  public function __construct(ConfigFactoryInterface $config_factory, EntityFieldManager $entityFieldManager, EntityTypeBundleInfoInterface $bundle_info_service) {
    parent::__construct($config_factory);
    $this->entityFieldManager = $entityFieldManager;
    $this->bundleInfoService = $bundle_info_service;
  }

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

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

  /**
   * Implements \Drupal\Core\Form\FormInterface::getFormID().
   */
  public function getFormId() {
    return 'better_field_descriptions_fields_form';
  }

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

    // Get better descriptions settings.
    $bfds = $this
      ->config('better_field_descriptions.settings')
      ->get('better_field_descriptions_settings');

    // Get existing descriptions for fields.
    $bfd = $this
      ->config('better_field_descriptions.settings')
      ->get('better_field_descriptions');

    // Use default template if not configured.
    if (isset($bfd['template']) == FALSE || empty($bfd['template'])) {
      $bfd['template'] = 'better-field-descriptions-text';
    }

    // Fetching template files from this module.
    $path = drupal_get_path('module', 'better_field_descriptions');
    $files = glob("{$path}/templates/*.html.twig", GLOB_BRACE);
    $templates = [];
    foreach ($files as $key => $value) {
      $templates[] = basename($value, ".html.twig");
    }
    $form['#templates'] = $templates;

    // Collects all templates found into array for select list.
    $better_descriptions_templates = [];
    foreach ($templates as $template) {

      // Removing the '.html.twig' if exists.
      if (($pos = strpos($template, '.')) !== FALSE) {
        $template = substr($template, 0, $pos);
      }
      $better_descriptions_templates[$template] = $template;
    }

    // Possible positions for the better description.
    $positions = [
      0 => $this
        ->t('Above title and input'),
      1 => $this
        ->t('Below title and input'),
      2 => $this
        ->t('Between title and input'),
    ];
    $form['descriptions'] = [
      '#type' => 'markup',
      '#markup' => $this
        ->t('Add/edit better descriptions to the fields below.'),
    ];
    $form['bundles'] = [
      '#type' => 'item',
      '#prefix' => '<div id="better-field-descriptions-form-id-wrapper">',
      '#suffix' => '</div>',
      '#tree' => TRUE,
    ];

    // Template selection.
    $form['bundles']['template'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Select template for the descriptions'),
      '#options' => $better_descriptions_templates,
      '#default_value' => $bfd['template'],
      '#description' => $this
        ->t('Changing this value will trigger a theme registry rebuild. You can also provide your own template, consult the documentation.'),
    ];

    // Setting label, default if not set.
    if (isset($bfd['default_label']) == FALSE) {
      $default_label = $this
        ->t('Description');
    }
    else {
      $default_label = $bfd['default_label'];
    }
    $form['bundles']['default_label'] = [
      '#type' => 'textfield',
      '#title' => 'Default label for all field descriptions.',
      '#default_value' => $default_label,
      '#description' => $this
        ->t('This label will be used if not set in each of the fields below.'),
    ];

    // Get info on bundles.
    $all_bundles = $this->bundleInfoService
      ->getAllBundleInfo();
    foreach ($bfds as $entity_type => $entity_bundles) {

      // Wrapping each bundle in a collapsed fieldset.
      $form['bundles'][$entity_type] = [
        '#type' => 'details',
        '#title' => $entity_type,
      ];
      foreach ($entity_bundles as $bundle_machine_name => $fields) {

        // Array to hold fields in the node.
        $fields_instances = [];

        // Get info on pseudo fields, like title.
        $extra_fields = $this->entityFieldManager
          ->getExtraFields($entity_type, $bundle_machine_name, 'form');
        if (isset($extra_fields['title'])) {
          $fields_instances['title'] = $extra_fields['title'];
        }

        // Get info on regular fields to the bundle.
        $fields_instances += $this->entityFieldManager
          ->getFieldDefinitions($entity_type, $bundle_machine_name);

        // Wrapping each bundle in a collapsed fieldset.
        $form['bundles'][$entity_type][$bundle_machine_name] = [
          '#type' => 'details',
          '#title' => $all_bundles[$entity_type][$bundle_machine_name]['label'],
        ];
        foreach ($fields as $field_machine_name) {

          // Skip if field no longer exists.
          if (!isset($fields_instances[$field_machine_name])) {
            continue;
          }

          // Descriptions.
          $bfd_description = '';
          if (isset($bfd[$entity_type][$bundle_machine_name][$field_machine_name]['description'])) {
            $bfd_description = $bfd[$entity_type][$bundle_machine_name][$field_machine_name]['description'];
          }
          $form['bundles'][$entity_type][$bundle_machine_name][$field_machine_name]['description'] = [
            '#type' => 'textarea',
            '#title' => $fields_instances[$field_machine_name]
              ->getLabel() . ' (' . $field_machine_name . ')',
            '#default_value' => FieldFilteredMarkup::create($bfd_description),
            '#description' => $this
              ->t('Add description for @machine_name.', [
              '@machine_name' => $fields_instances[$field_machine_name]
                ->getLabel(),
            ]),
          ];

          // Label.
          $bfd_label = '';
          if (isset($bfd[$entity_type][$bundle_machine_name][$field_machine_name]['label'])) {
            $bfd_label = $bfd[$entity_type][$bundle_machine_name][$field_machine_name]['label'];
          }
          $form['bundles'][$entity_type][$bundle_machine_name][$field_machine_name]['label'] = [
            '#type' => 'textfield',
            '#title' => 'Label for this field description',
            '#default_value' => FieldFilteredMarkup::create($bfd_label),
            '#description' => $this
              ->t('Label for this field description.'),
          ];
          $position = 1;
          if (isset($bfd[$entity_type][$bundle_machine_name][$field_machine_name]['position'])) {
            $position = $bfd[$entity_type][$bundle_machine_name][$field_machine_name]['position'];
          }

          // Position of description.
          $form['bundles'][$entity_type][$bundle_machine_name][$field_machine_name]['position'] = [
            '#type' => 'radios',
            '#title' => 'Position of description.',
            '#options' => $positions,
            '#default_value' => $position,
            '#description' => $this
              ->t('Position the description field above or below the input field. Using the between-option can cause unexpected results: any label set above will replace the label of the field, and for some kinds of fields the title may also be duplicated. Please review the relevant content form after saving these settings.'),
          ];
        }
      }
    }
    return parent::buildForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $bfd = $this
      ->config('better_field_descriptions.settings')
      ->get('better_field_descriptions');
    $template_bundle = $form_state
      ->getValue('bundles');
    $path = drupal_get_path('module', 'better_field_descriptions');
    $template = $template_bundle['template'];
    $template_uri = $path . '/templates/' . $template . '.html.twig';
    $form_state
      ->setValue([
      'bundles',
      'template_uri',
    ], $template_uri);

    // If the template is changed, do a theme registry rebuild.
    if (isset($bfd['template']) && $template != $bfd['template']) {
      drupal_theme_rebuild();
    }

    // Setting variables.
    $config = $this
      ->config('better_field_descriptions.settings')
      ->set('better_field_descriptions', $form_state
      ->getValue('bundles'));
    $config
      ->save();
    parent::submitForm($form, $form_state);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
BetterFieldDescriptionsFieldsForm::$bundleInfoService protected property The bundle info service.
BetterFieldDescriptionsFieldsForm::$entityFieldManager private property EntityFieldManagerservices object.
BetterFieldDescriptionsFieldsForm::buildForm public function Form constructor. Overrides ConfigFormBase::buildForm
BetterFieldDescriptionsFieldsForm::create public static function Instantiates a new instance of this class. Overrides ConfigFormBase::create
BetterFieldDescriptionsFieldsForm::getEditableConfigNames protected function Gets the configuration names that will be editable. Overrides ConfigFormBaseTrait::getEditableConfigNames
BetterFieldDescriptionsFieldsForm::getFormId public function Implements \Drupal\Core\Form\FormInterface::getFormID(). Overrides FormInterface::getFormId
BetterFieldDescriptionsFieldsForm::submitForm public function Form submission handler. Overrides ConfigFormBase::submitForm
BetterFieldDescriptionsFieldsForm::__construct public function Constructs a \Drupal\system\ConfigFormBase object. Overrides ConfigFormBase::__construct
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.
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.
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.