You are here

class FieldFormBase in Display Suite 8.4

Same name and namespace in other branches
  1. 8.2 src/Form/FieldFormBase.php \Drupal\ds\Form\FieldFormBase
  2. 8.3 src/Form/FieldFormBase.php \Drupal\ds\Form\FieldFormBase

Base form for fields.

Hierarchy

Expanded class hierarchy of FieldFormBase

File

src/Form/FieldFormBase.php, line 19

Namespace

Drupal\ds\Form
View source
class FieldFormBase extends ConfigFormBase implements ContainerInjectionInterface {

  /**
   * Holds the entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManager
   */
  protected $entityTypeManager;

  /**
   * Holds the cache invalidator.
   *
   * @var \Drupal\Core\Cache\CacheTagsInvalidatorInterface
   */
  protected $cacheInvalidator;

  /**
   * Drupal module handler.
   *
   * @var \Drupal\Core\Extension\ModuleHandler
   */
  protected $moduleHandler;

  /**
   * The field properties.
   *
   * @var array
   */
  protected $field;

  /**
   * Constructs a \Drupal\system\CustomFieldFormBase object.
   *
   * @param \Drupal\Core\Config\ConfigFactory $config_factory
   *   The factory for configuration objects.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   * @param \Drupal\Core\Cache\CacheTagsInvalidatorInterface $cache_invalidator
   *   The cache invalidator.
   * @param \Drupal\Core\Extension\ModuleHandler $module_handler
   *   The module handler.
   */
  public function __construct(ConfigFactory $config_factory, EntityTypeManagerInterface $entity_type_manager, CacheTagsInvalidatorInterface $cache_invalidator, ModuleHandler $module_handler) {
    parent::__construct($config_factory);
    $this->entityTypeManager = $entity_type_manager;
    $this->cacheInvalidator = $cache_invalidator;
    $this->moduleHandler = $module_handler;
  }

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

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

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

    // Initialize field.
    $field = [];

    // Fetch field if it already exists.
    if (!empty($field_key)) {
      $field = $this
        ->config('ds.field.' . $field_key)
        ->get();
    }

    // Save the field for future reuse.
    $this->field = $field;
    $form['name'] = [
      '#title' => $this
        ->t('Label'),
      '#type' => 'textfield',
      '#default_value' => isset($field['label']) ? $field['label'] : '',
      '#description' => $this
        ->t('The human-readable label of the field.'),
      '#maxlength' => 128,
      '#required' => TRUE,
      '#size' => 30,
    ];
    $form['id'] = [
      '#type' => 'machine_name',
      '#default_value' => isset($field['id']) ? $field['id'] : '',
      '#maxlength' => 32,
      '#description' => $this
        ->t('The machine-readable name of this field. This name must contain only lowercase letters and underscores. This name must be unique.'),
      '#disabled' => !empty($field['id']),
      '#machine_name' => [
        'exists' => [
          $this,
          'uniqueFieldName',
        ],
        'source' => [
          'name',
        ],
      ],
    ];
    $entity_options = [];
    $entities = $this->entityTypeManager
      ->getDefinitions();
    foreach ($entities as $entity_type => $entity_info) {
      if ($entity_info
        ->get('field_ui_base_route') || $entity_type == 'ds_views') {
        $entity_options[$entity_type] = Unicode::ucfirst(str_replace('_', ' ', $entity_type));
      }
    }
    $form['entities'] = [
      '#title' => $this
        ->t('Entities'),
      '#description' => $this
        ->t('Select the entities for which this field will be made available.'),
      '#type' => 'checkboxes',
      '#required' => TRUE,
      '#options' => $entity_options,
      '#default_value' => isset($field['entities']) ? $field['entities'] : [],
    ];
    $form['ui_limit'] = [
      '#title' => $this
        ->t('Limit field'),
      '#description' => $this
        ->t('Limit this field on field UI per bundles and/or view modes. The values are in the form of $bundle|$view_mode, where $view_mode may be either a view mode set to use custom settings, or \'default\'. You may use * to select all, e.g article|*, *|full or *|*. Enter one value per line.'),
      '#type' => 'textarea',
      '#default_value' => isset($field['ui_limit']) ? $field['ui_limit'] : '',
    ];
    $form['submit'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Save'),
      '#weight' => 100,
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $field = [];
    $field['id'] = $form_state
      ->getValue('id');
    $field['label'] = $form_state
      ->getValue('name');
    $field['ui_limit'] = $form_state
      ->getValue('ui_limit');
    $field['properties'] = $this
      ->getProperties($form_state);
    $field['type'] = $this
      ->getType();
    $field['type_label'] = $this
      ->getTypeLabel();
    $entities = $form_state
      ->getValue('entities');
    foreach ($entities as $key => $value) {
      if ($key !== $value) {
        unset($entities[$key]);
      }
    }
    $field['entities'] = $entities;

    // Save field to property.
    $this->field = $field;

    // Save field values.
    $this
      ->config('ds.field.' . $field['id'])
      ->setData($field)
      ->save();

    // Clear caches and redirect.
    $this
      ->finishSubmitForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    if (isset($this->field, $this->field['id'])) {
      return [
        'ds.field.' . $this->field['id'],
      ];
    }
    else {
      return [];
    }
  }

  /**
   * Returns the properties for the custom field.
   */
  public function getProperties(FormStateInterface $form_state) {
    return [];
  }

  /**
   * Returns the type of the field.
   */
  public function getType() {
    return '';
  }

  /**
   * Returns the admin label for the field on the field overview page.
   */
  public function getTypeLabel() {
    return '';
  }

  /**
   * Returns whether a field machine name is unique.
   */
  public function uniqueFieldName($name) {
    $value = strtr($name, [
      '-' => '_',
    ]);
    $config = $this
      ->configFactory()
      ->get('ds.field.' . $value);
    if ($config
      ->get()) {
      return TRUE;
    }
    return FALSE;
  }

  /**
   * Finishes the submit.
   */
  public function finishSubmitForm(array &$form, FormStateInterface $form_state) {
    $field = $this->field;

    // Save field and clear ds_fields_info cache.
    $this->cacheInvalidator
      ->invalidateTags([
      'ds_fields_info',
    ]);

    // Also clear the ds plugin cache.
    \Drupal::service('plugin.manager.ds')
      ->clearCachedDefinitions();

    // Redirect.
    $url = new Url('ds.fields_list');
    $form_state
      ->setRedirectUrl($url);
    $this
      ->messenger()
      ->addMessage($this
      ->t('The field %field has been saved.', [
      '%field' => $field['label'],
    ]));
  }

}

Members

Namesort descending Modifiers Type Description Overrides
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
FieldFormBase::$cacheInvalidator protected property Holds the cache invalidator.
FieldFormBase::$entityTypeManager protected property Holds the entity type manager.
FieldFormBase::$field protected property The field properties.
FieldFormBase::$moduleHandler protected property Drupal module handler.
FieldFormBase::buildForm public function Form constructor. Overrides ConfigFormBase::buildForm 5
FieldFormBase::create public static function Instantiates a new instance of this class. Overrides ConfigFormBase::create 1
FieldFormBase::finishSubmitForm public function Finishes the submit.
FieldFormBase::getEditableConfigNames protected function Gets the configuration names that will be editable. Overrides ConfigFormBaseTrait::getEditableConfigNames
FieldFormBase::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId 4
FieldFormBase::getProperties public function Returns the properties for the custom field. 4
FieldFormBase::getType public function Returns the type of the field. 4
FieldFormBase::getTypeLabel public function Returns the admin label for the field on the field overview page. 4
FieldFormBase::submitForm public function Form submission handler. Overrides ConfigFormBase::submitForm 2
FieldFormBase::uniqueFieldName public function Returns whether a field machine name is unique.
FieldFormBase::__construct public function Constructs a \Drupal\system\CustomFieldFormBase object. Overrides ConfigFormBase::__construct 1
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.