You are here

class WSFieldAddFieldForm in Web Service Data 8

Same name and namespace in other branches
  1. 2.0.x modules/wsdata_field/src/Form/WSFieldAddFieldForm.php \Drupal\wsdata_field\Form\WSFieldAddFieldForm

Provides a form for the "field storage" add page.

Hierarchy

Expanded class hierarchy of WSFieldAddFieldForm

File

modules/wsdata_field/src/Form/WSFieldAddFieldForm.php, line 13

Namespace

Drupal\wsdata_field\Form
View source
class WSFieldAddFieldForm extends FieldStorageAddForm {

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, $entity_type_id = NULL, $bundle = NULL) {
    if (!$form_state
      ->get('entity_type_id')) {
      $form_state
        ->set('entity_type_id', $entity_type_id);
    }
    if (!$form_state
      ->get('bundle')) {
      $form_state
        ->set('bundle', $bundle);
    }
    $this->entityTypeId = $form_state
      ->get('entity_type_id');
    $this->bundle = $form_state
      ->get('bundle');

    // Gather valid field types.
    $field_type_options = [];
    foreach ($this->fieldTypePluginManager
      ->getGroupedDefinitions($this->fieldTypePluginManager
      ->getUiDefinitions()) as $category => $field_types) {
      foreach ($field_types as $name => $field_type) {
        $field_type_options[$category][$name] = $field_type['label'];
      }
    }
    $form['add'] = [
      '#type' => 'container',
      '#attributes' => [
        'class' => [
          'form--inline',
          'clearfix',
        ],
      ],
    ];
    $form['add']['new_storage_type'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Add a new field'),
      '#options' => $field_type_options,
      '#empty_option' => $this
        ->t('- Select a field type -'),
    ];

    // Field label and field_name.
    $form['new_storage_wrapper'] = [
      '#type' => 'container',
      '#states' => [
        '!visible' => [
          ':input[name="new_storage_type"]' => [
            'value' => '',
          ],
        ],
      ],
    ];
    $form['new_storage_wrapper']['label'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Label'),
      '#size' => 15,
    ];
    $field_prefix = $this
      ->config('field_ui.settings')
      ->get('field_prefix');
    $form['new_storage_wrapper']['field_name'] = [
      '#type' => 'machine_name',
      // This field should stay LTR even for RTL languages.
      '#field_prefix' => '<span dir="ltr">' . $field_prefix,
      '#field_suffix' => '</span>&lrm;',
      '#size' => 15,
      '#description' => $this
        ->t('A unique machine-readable name containing letters, numbers, and underscores.'),
      // Calculate characters depending on the length of the field prefix
      // setting. Maximum length is 32.
      '#maxlength' => FieldStorageConfig::NAME_MAX_LENGTH - strlen($field_prefix),
      '#machine_name' => [
        'source' => [
          'new_storage_wrapper',
          'label',
        ],
        'exists' => [
          $this,
          'fieldNameExists',
        ],
      ],
      '#required' => FALSE,
    ];

    // Place the 'translatable' property as an explicit value so that contrib
    // modules can form_alter() the value for newly created fields. By default
    // we create field storage as translatable so it will be possible to enable
    // translation at field level.
    $form['translatable'] = [
      '#type' => 'value',
      '#value' => TRUE,
    ];
    $form['actions'] = [
      '#type' => 'actions',
    ];
    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Save and continue'),
      '#button_type' => 'primary',
    ];
    $form['#attached']['library'][] = 'field_ui/drupal.field_ui';
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $error = FALSE;
    $values = $form_state
      ->getValues();
    $destinations = [];
    $entity_type = $this->entityManager
      ->getDefinition($this->entityTypeId);

    // Create new field.
    if ($values['new_storage_type']) {
      $field_storage_values = [
        'field_name' => $values['field_name'],
        'entity_type' => $this->entityTypeId,
        'type' => $values['new_storage_type'],
        'translatable' => $values['translatable'],
        'custom_storage' => TRUE,
      ];
      $field_values = [
        'field_name' => $values['field_name'],
        'entity_type' => $this->entityTypeId,
        'bundle' => $this->bundle,
        'label' => $values['label'],
        // Field translatability should be explicitly enabled by the users.
        'translatable' => FALSE,
      ];
      $widget_id = $formatter_id = NULL;

      // Check if we're dealing with a preconfigured field.
      if (strpos($field_storage_values['type'], 'field_ui:') !== FALSE) {
        list(, $field_type, $option_key) = explode(':', $field_storage_values['type'], 3);
        $field_storage_values['type'] = $field_type;
        $field_type_class = $this->fieldTypePluginManager
          ->getDefinition($field_type)['class'];
        $field_options = $field_type_class::getPreconfiguredOptions()[$option_key];

        // Merge in preconfigured field storage options.
        if (isset($field_options['field_storage_config'])) {
          foreach ([
            'cardinality',
            'settings',
          ] as $key) {
            if (isset($field_options['field_storage_config'][$key])) {
              $field_storage_values[$key] = $field_options['field_storage_config'][$key];
            }
          }
        }

        // Merge in preconfigured field options.
        if (isset($field_options['field_config'])) {
          foreach ([
            'required',
            'settings',
          ] as $key) {
            if (isset($field_options['field_config'][$key])) {
              $field_values[$key] = $field_options['field_config'][$key];
            }
          }
        }
        $widget_id = isset($field_options['entity_form_display']['type']) ? $field_options['entity_form_display']['type'] : NULL;
        $formatter_id = isset($field_options['entity_view_display']['type']) ? $field_options['entity_view_display']['type'] : NULL;
      }

      // Create the field storage and field.
      try {
        $this->entityManager
          ->getStorage('field_storage_config')
          ->create($field_storage_values)
          ->save();
        $field = $this->entityManager
          ->getStorage('field_config')
          ->create($field_values);
        $field
          ->save();
        $this
          ->configureEntityFormDisplay($values['field_name'], $widget_id);
        $this
          ->configureEntityViewDisplay($values['field_name'], $formatter_id);

        // Always show the field settings step, as the cardinality needs to be
        // configured for new fields.
        $route_parameters = [
          'field_config' => $field
            ->id(),
        ] + FieldUI::getRouteBundleParameter($entity_type, $this->bundle);
        $destinations[] = [
          'route_name' => "entity.field_config.{$this->entityTypeId}_wsfield_edit_form",
          'route_parameters' => $route_parameters,
        ];
        $destinations[] = [
          'route_name' => "entity.field_config.{$this->entityTypeId}_storage_edit_form",
          'route_parameters' => $route_parameters,
        ];
        $destinations[] = [
          'route_name' => "entity.field_config.{$this->entityTypeId}_field_edit_form",
          'route_parameters' => $route_parameters,
        ];
        $destinations[] = [
          'route_name' => "entity.{$this->entityTypeId}.field_ui_fields",
          'route_parameters' => $route_parameters,
        ];

        // Store new field information for any additional submit handlers.
        $form_state
          ->set([
          'fields_added',
          '_add_new_field',
        ], $values['field_name']);
      } catch (\Exception $e) {
        $error = TRUE;
        $this
          ->messenger()
          ->addError($this
          ->t('There was a problem creating field %label: @message', [
          '%label' => $values['label'],
          '@message' => $e
            ->getMessage(),
        ]));
      }
    }
    if ($destinations) {
      $destination = $this
        ->getDestinationArray();
      $destinations[] = $destination['destination'];
      $form_state
        ->setRedirectUrl(FieldUI::getNextDestination($destinations, $form_state));
    }
    elseif (!$error) {
      $this
        ->messenger()
        ->addStatus($this
        ->t('Your settings have been saved.'));
    }
  }

}

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
DeprecatedServicePropertyTrait::__get public function Allows to access deprecated/removed properties.
FieldStorageAddForm::$bundle protected property The entity bundle.
FieldStorageAddForm::$configFactory protected property The configuration factory. Overrides FormBase::$configFactory
FieldStorageAddForm::$deprecatedProperties protected property
FieldStorageAddForm::$entityDisplayRepository protected property The entity display repository.
FieldStorageAddForm::$entityFieldManager protected property The entity field manager.
FieldStorageAddForm::$entityTypeId protected property The name of the entity type.
FieldStorageAddForm::$entityTypeManager protected property The entity type manager.
FieldStorageAddForm::$fieldTypePluginManager protected property The field type plugin manager.
FieldStorageAddForm::configureEntityFormDisplay protected function Configures the field for the default form mode.
FieldStorageAddForm::configureEntityViewDisplay protected function Configures the field for the default view mode.
FieldStorageAddForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
FieldStorageAddForm::fieldNameExists public function Checks if a field machine name is taken.
FieldStorageAddForm::getExistingFieldLabels protected function Gets the human-readable labels for the given field storage names.
FieldStorageAddForm::getExistingFieldStorageOptions protected function Returns an array of existing field storages that can be added to a bundle.
FieldStorageAddForm::validateAddExisting protected function Validates the 're-use existing field' case.
FieldStorageAddForm::validateAddNew protected function Validates the 'add new field' case.
FieldStorageAddForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
FieldStorageAddForm::__construct public function Constructs a new FieldStorageAddForm object.
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.
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.
WSFieldAddFieldForm::buildForm public function Form constructor. Overrides FieldStorageAddForm::buildForm
WSFieldAddFieldForm::getFormId public function Returns a unique string identifying the form. Overrides FieldStorageAddForm::getFormId
WSFieldAddFieldForm::submitForm public function Form submission handler. Overrides FieldStorageAddForm::submitForm