You are here

class FormatterForm in Custom Formatters 8.3

Form controller for the shortcut set entity edit forms.

Hierarchy

Expanded class hierarchy of FormatterForm

File

src/Form/FormatterForm.php, line 16

Namespace

Drupal\custom_formatters\Form
View source
class FormatterForm extends EntityForm {

  /**
   * The entity being used by this form.
   *
   * @var \Drupal\custom_formatters\FormatterInterface
   */
  protected $entity;

  /**
   * Formatter extras plugin manager.
   *
   * @var FormatterExtrasManager
   */
  protected $formatterExtrasManager;

  /**
   * Field formatter plugin manager.
   *
   * @var FormatterPluginManager
   */
  protected $fieldFormatterManager;

  /**
   * Field type plugin manager.
   *
   * @var FieldTypePluginManagerInterface
   */
  protected $fieldTypeManager;

  /**
   * Constructs a FormatterForm object.
   */
  public function __construct(FormatterExtrasManager $formatter_extras_manager, FormatterPluginManager $field_formatter_manager, FieldTypePluginManagerInterface $field_type_manager) {
    $this->formatterExtrasManager = $formatter_extras_manager;
    $this->fieldTypeManager = $field_type_manager;
    $this->fieldFormatterManager = $field_formatter_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('plugin.manager.custom_formatters.formatter_extras'), $container
      ->get('plugin.manager.field.formatter'), $container
      ->get('plugin.manager.field.field_type'));
  }

  /**
   * {@inheritdoc}
   */
  public function form(array $form, FormStateInterface $form_state) {
    $formatter_type = $this->entity
      ->getFormatterType();
    $form = parent::form($form, $form_state);

    // Show warning if formatter is currently in use.
    $dependent_entities = $this->entity
      ->getDependentEntities();
    if ($dependent_entities) {
      $form['warning'] = [
        '#theme' => 'status_messages',
        '#message_list' => [
          'warning' => [
            $this
              ->t("Changing the field type(s) are currently disabled as this formatter is required by the following configuration(s): @config", [
              '@config' => $this
                ->getDependentEntitiesList($dependent_entities),
            ]),
          ],
        ],
        '#status_headings' => [
          'warning' => t('Warning message'),
        ],
      ];
    }
    $form['label'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Formatter name'),
      '#description' => $this
        ->t('This will appear in the administrative interface to easily identify it.'),
      '#required' => TRUE,
      '#default_value' => $this->entity
        ->label(),
    ];
    $form['id'] = [
      '#type' => 'machine_name',
      '#machine_name' => [
        'exists' => '\\Drupal\\custom_formatters\\Entity\\Formatter::load',
        'source' => [
          'label',
        ],
        'replace_pattern' => '[^a-z0-9_]+',
        'replace' => '_',
      ],
      '#default_value' => $this->entity
        ->isNew() ? NULL : $this->entity
        ->id(),
      '#disabled' => !$this->entity
        ->isNew(),
      '#maxlength' => 255,
    ];
    $form['type'] = [
      '#type' => 'value',
      '#value' => $this->entity
        ->get('type'),
    ];
    $form['status'] = [
      '#type' => 'value',
      '#value' => TRUE,
    ];
    $form['description'] = [
      '#type' => 'textarea',
      '#title' => $this
        ->t('Description'),
      '#default_value' => $this->entity
        ->get('description'),
    ];
    $form['field_types'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Field type(s)'),
      '#options' => $this
        ->getFieldTypes(),
      '#default_value' => $this->entity
        ->get('field_types'),
      '#required' => TRUE,
      '#multiple' => $formatter_type
        ->getPluginDefinition()['multipleFields'],
      '#ajax' => [
        'callback' => '::formAjax',
        'wrapper' => 'plugin-wrapper',
      ],
      '#disabled' => $dependent_entities,
    ];

    // Get Formatter type settings form.
    $plugin_form = [];
    $form['plugin'] = $formatter_type
      ->settingsForm($plugin_form, $form_state);
    $form['plugin']['#type'] = 'container';
    $form['plugin']['#prefix'] = "<div id='plugin-wrapper'>";
    $form['plugin']['#suffix'] = "</div>";

    // Third party integration settings form.
    $extras = $this
      ->getFormatterExtrasForm();
    if ($extras && is_array($extras)) {
      $form['vertical_tabs'] = [
        '#type' => 'vertical_tabs',
        '#title' => $this
          ->t('Extras'),
        '#parents' => [
          'extras',
        ],
      ];
      $form['extras'] = $extras;
      $form['extras']['#tree'] = TRUE;
    }
    return $form;
  }

  /**
   * Returns the settings form for any available third party integrations.
   */
  public function getFormatterExtrasForm() {
    $form = [];
    $definitions = $this->formatterExtrasManager
      ->getDefinitions();
    if (is_array($definitions) && !empty($definitions)) {
      foreach ($definitions as $definition) {
        $extras_form = $this->formatterExtrasManager
          ->invoke($definition['id'], 'settingsForm', $this->entity);
        if (is_array($extras_form) && !empty($extras_form)) {

          // Extras form.
          $form[$definition['id']] = $extras_form;

          // Extras form details element.
          $form[$definition['id']]['#type'] = 'details';
          $form[$definition['id']]['#title'] = $definition['label'];
          $form[$definition['id']]['#description'] = $definition['description'];
          $form[$definition['id']]['#group'] = 'extras';
        }
      }
    }
    return $form;
  }

  /**
   * Ajax callback for form.
   *
   * @param array $form
   *   The form array.
   * @param FormStateInterface $form_state
   *   The form state object.
   *
   * @return mixed
   *   The ajax form element.
   */
  public function formAjax(array $form, FormStateInterface $form_state) {
    return $form['plugin'];
  }

  /**
   * {@inheritdoc}
   */
  public function save(array $form, FormStateInterface $form_state) {
    $this->entity
      ->getFormatterType()
      ->submitForm($form, $form_state);
    $entity = $this->entity;
    $is_new = !$entity
      ->getOriginalId();

    // Invoke all third party integrations save method.
    $this->formatterExtrasManager
      ->invokeAll('settingsSave', $entity, $form, $form_state);
    $entity
      ->save();

    // Clear cached formatters.
    // @TODO - Tag custom formatters?
    $this->fieldFormatterManager
      ->clearCachedDefinitions();
    if ($is_new) {
      $this
        ->messenger()
        ->addStatus($this
        ->t('Added formatter %formatter.', [
        '%formatter' => $entity
          ->label(),
      ]));
    }
    else {
      $this
        ->messenger()
        ->addStatus($this
        ->t('Updated formatter %formatter.', [
        '%formatter' => $entity
          ->label(),
      ]));
    }
    $form_state
      ->setRedirectUrl(new Url('entity.formatter.collection'));
  }

  /**
   * Returns a list of dependent entities.
   *
   * @param array $entities
   *   The dependent entities.
   *
   * @return mixed|null
   *   The rendered list of dependent entities.
   */
  protected function getDependentEntitiesList(array $entities = []) {
    $list = [];
    foreach ($entities as $entity) {
      $entity_type_id = $entity
        ->getEntityTypeId();
      if (!isset($list[$entity_type_id])) {
        $entity_type = $this->entityTypeManager
          ->getDefinition($entity_type_id);

        // Store the ID and label to sort the entity types and entities later.
        $label = $entity_type
          ->getLabel();
        $list[$entity_type_id] = [
          '#theme' => 'item_list',
          '#title' => $label,
          '#items' => [],
        ];
      }
      $list[$entity_type_id]['#items'][$entity
        ->id()] = $entity
        ->label() ?: $entity
        ->id();
    }
    return render($list);
  }

  /**
   * Returns an array of available field types.
   *
   * @TODO - Allow formatter type plugin to modify this list.
   *
   * @return mixed
   *   Array of field types grouped by their providers.
   */
  protected function getFieldTypes() {
    $options = [];
    $field_types = $this->fieldTypeManager
      ->getDefinitions();
    $this->moduleHandler
      ->alter('custom_formatters_fields', $field_types);
    ksort($field_types);
    foreach ($field_types as $field_type) {
      $options[$field_type['provider']][$field_type['id']] = $field_type['label']
        ->render();
    }
    ksort($options);
    return $options;
  }

}

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
EntityForm::$entityTypeManager protected property The entity type manager. 3
EntityForm::$moduleHandler protected property The module handler service.
EntityForm::$operation protected property The name of the current operation.
EntityForm::$privateEntityManager private property The entity manager.
EntityForm::actions protected function Returns an array of supported actions for the current entity form. 29
EntityForm::actionsElement protected function Returns the action form element for the current entity form.
EntityForm::afterBuild public function Form element #after_build callback: Updates the entity with submitted data.
EntityForm::buildEntity public function Builds an updated entity object based upon the submitted form values. Overrides EntityFormInterface::buildEntity 2
EntityForm::buildForm public function Form constructor. Overrides FormInterface::buildForm 10
EntityForm::copyFormValuesToEntity protected function Copies top-level form values to entity properties 7
EntityForm::getBaseFormId public function Returns a string identifying the base form. Overrides BaseFormIdInterface::getBaseFormId 5
EntityForm::getEntity public function Gets the form entity. Overrides EntityFormInterface::getEntity
EntityForm::getEntityFromRouteMatch public function Determines which entity will be used by this form from a RouteMatch object. Overrides EntityFormInterface::getEntityFromRouteMatch 1
EntityForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId 10
EntityForm::getOperation public function Gets the operation identifying the form. Overrides EntityFormInterface::getOperation
EntityForm::init protected function Initialize the form state and the entity before the first form build. 3
EntityForm::prepareEntity protected function Prepares the entity object before the form is built first. 3
EntityForm::prepareInvokeAll protected function Invokes the specified prepare hook variant.
EntityForm::processForm public function Process callback: assigns weights and hides extra fields.
EntityForm::setEntity public function Sets the form entity. Overrides EntityFormInterface::setEntity
EntityForm::setEntityManager public function Sets the entity manager for this form. Overrides EntityFormInterface::setEntityManager
EntityForm::setEntityTypeManager public function Sets the entity type manager for this form. Overrides EntityFormInterface::setEntityTypeManager
EntityForm::setModuleHandler public function Sets the module handler for this form. Overrides EntityFormInterface::setModuleHandler
EntityForm::setOperation public function Sets the operation for this form. Overrides EntityFormInterface::setOperation
EntityForm::submitForm public function This is the default entity object builder function. It is called before any other submit handler to build the new entity object to be used by the following submit handlers. At this point of the form workflow the entity is validated and the form state… Overrides FormInterface::submitForm 17
EntityForm::__get public function
EntityForm::__set public function
FormatterForm::$entity protected property The entity being used by this form. Overrides EntityForm::$entity
FormatterForm::$fieldFormatterManager protected property Field formatter plugin manager.
FormatterForm::$fieldTypeManager protected property Field type plugin manager.
FormatterForm::$formatterExtrasManager protected property Formatter extras plugin manager.
FormatterForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
FormatterForm::form public function Gets the actual form array to be built. Overrides EntityForm::form
FormatterForm::formAjax public function Ajax callback for form.
FormatterForm::getDependentEntitiesList protected function Returns a list of dependent entities.
FormatterForm::getFieldTypes protected function Returns an array of available field types.
FormatterForm::getFormatterExtrasForm public function Returns the settings form for any available third party integrations.
FormatterForm::save public function Form submission handler for the 'save' action. Overrides EntityForm::save
FormatterForm::__construct public function Constructs a FormatterForm object.
FormBase::$configFactory protected property The config factory. 1
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.
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.