You are here

class FieldConfigurationForm in Search API 8

Defines a form for changing a field's configuration.

Hierarchy

Expanded class hierarchy of FieldConfigurationForm

File

src/Form/FieldConfigurationForm.php, line 22

Namespace

Drupal\search_api\Form
View source
class FieldConfigurationForm extends EntityForm {
  use UnsavedConfigurationFormTrait;

  /**
   * The index for which the fields are configured.
   *
   * @var \Drupal\search_api\IndexInterface
   */
  protected $entity;

  /**
   * The field whose configuration is edited.
   *
   * @var \Drupal\search_api\Item\FieldInterface
   */
  protected $field;

  /**
   * The "id" attribute of the generated form.
   *
   * @var string
   */
  protected $formIdAttribute;

  /**
   * The messenger.
   *
   * @var \Drupal\Core\Messenger\MessengerInterface
   */
  protected $messenger;

  /**
   * Constructs a FieldConfigurationForm object.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   * @param \Drupal\Core\Render\RendererInterface $renderer
   *   The renderer to use.
   * @param \Drupal\Core\Datetime\DateFormatterInterface $date_formatter
   *   The date formatter.
   * @param \Symfony\Component\HttpFoundation\RequestStack $request_stack
   *   The request stack.
   * @param \Drupal\Core\Messenger\MessengerInterface $messenger
   *   The messenger.
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager, RendererInterface $renderer, DateFormatterInterface $date_formatter, RequestStack $request_stack, MessengerInterface $messenger) {
    $this->entityTypeManager = $entity_type_manager;
    $this->renderer = $renderer;
    $this->dateFormatter = $date_formatter;
    $this->requestStack = $request_stack;
    $this->messenger = $messenger;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    $entity_type_manager = $container
      ->get('entity_type.manager');
    $renderer = $container
      ->get('renderer');
    $date_formatter = $container
      ->get('date.formatter');
    $request_stack = $container
      ->get('request_stack');
    $messenger = $container
      ->get('messenger');
    return new static($entity_type_manager, $renderer, $date_formatter, $request_stack, $messenger);
  }

  /**
   * {@inheritdoc}
   */
  public function getBaseFormId() {
    return NULL;
  }

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $field = $this
      ->getField();
    if (!$field) {
      $args['@id'] = $this
        ->getRequest()->attributes
        ->get('field_id');
      $form['message'] = [
        '#markup' => $this
          ->t('Unknown field with ID "@id".', $args),
      ];
      return $form;
    }
    $args['%field'] = $field
      ->getLabel();
    $form['#title'] = $this
      ->t('Edit field %field', $args);
    if ($this
      ->getRequest()->query
      ->get('modal_redirect')) {
      $form['title']['#markup'] = new FormattableMarkup('<h2>@title</h2>', [
        '@title' => $form['#title'],
      ]);
      Html::setIsAjax(TRUE);
    }
    $this->formIdAttribute = Html::getUniqueId($this
      ->getFormId());
    $form['#id'] = $this->formIdAttribute;
    $form['messages'] = [
      '#type' => 'status_messages',
    ];
    $property = $field
      ->getDataDefinition();
    if (!$property instanceof ConfigurablePropertyInterface) {
      $args['%field'] = $field
        ->getLabel();
      $form['message'] = [
        '#markup' => $this
          ->t('Field %field is not configurable.', $args),
      ];
      return $form;
    }
    return parent::buildForm($form, $form_state);
  }

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

    /** @var \Drupal\search_api\Processor\ConfigurablePropertyInterface $property */
    $property = $field
      ->getDataDefinition();
    $form = $property
      ->buildConfigurationForm($field, $form, $form_state);
    $this
      ->checkEntityEditable($form, $this->entity);
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  protected function actions(array $form, FormStateInterface $form_state) {
    $actions = parent::actions($form, $form_state);
    unset($actions['delete']);
    if ($this
      ->getRequest()->query
      ->get('modal_redirect')) {
      $actions['submit']['#ajax']['wrapper'] = $this->formIdAttribute;
    }
    else {
      $actions['cancel'] = [
        '#type' => 'link',
        '#title' => $this
          ->t('Cancel'),
        '#url' => $this->entity
          ->toUrl('fields'),
      ];
    }
    return $actions;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    $field = $this
      ->getField();

    /** @var \Drupal\search_api\Processor\ConfigurablePropertyInterface $property */
    $property = $field
      ->getDataDefinition();
    $property
      ->validateConfigurationForm($field, $form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $field = $this
      ->getField();

    /** @var \Drupal\search_api\Processor\ConfigurablePropertyInterface $property */
    $property = $field
      ->getDataDefinition();
    $property
      ->submitConfigurationForm($field, $form, $form_state);
    $this->messenger
      ->addStatus($this
      ->t('The field configuration was successfully saved.'));
    if ($this
      ->getRequest()->query
      ->get('modal_redirect')) {
      $url = $this->entity
        ->toUrl('add-fields-ajax')
        ->setOption('query', [
        MainContentViewSubscriber::WRAPPER_FORMAT => 'drupal_ajax',
      ]);
      $form_state
        ->setRedirectUrl($url);
    }
    else {
      $form_state
        ->setRedirectUrl($this->entity
        ->toUrl('fields'));
    }
  }

  /**
   * {@inheritdoc}
   */
  protected function copyFormValuesToEntity(EntityInterface $entity, array $form, FormStateInterface $form_state) {

    // Our form structure doesn't emulate the entity structure, so copying those
    // values wouldn't make any sense.
  }

  /**
   * Retrieves the field that is being edited.
   *
   * @return \Drupal\search_api\Item\FieldInterface|null
   *   The field, if it exists.
   */
  protected function getField() {
    if (!isset($this->field)) {
      $field_id = $this
        ->getRequest()->attributes
        ->get('field_id');
      $this->field = $this->entity
        ->getField($field_id);
    }
    return $this->field;
  }

}

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::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::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::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::save public function Form submission handler for the 'save' action. Overrides EntityFormInterface::save 41
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::__get public function
EntityForm::__set public function
FieldConfigurationForm::$entity protected property The index for which the fields are configured. Overrides EntityForm::$entity
FieldConfigurationForm::$field protected property The field whose configuration is edited.
FieldConfigurationForm::$formIdAttribute protected property The "id" attribute of the generated form.
FieldConfigurationForm::$messenger protected property The messenger. Overrides MessengerTrait::$messenger
FieldConfigurationForm::actions protected function Returns an array of supported actions for the current entity form. Overrides EntityForm::actions
FieldConfigurationForm::buildForm public function Form constructor. Overrides EntityForm::buildForm
FieldConfigurationForm::copyFormValuesToEntity protected function Copies top-level form values to entity properties Overrides EntityForm::copyFormValuesToEntity
FieldConfigurationForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
FieldConfigurationForm::form public function Gets the actual form array to be built. Overrides EntityForm::form
FieldConfigurationForm::getBaseFormId public function Returns a string identifying the base form. Overrides EntityForm::getBaseFormId
FieldConfigurationForm::getField protected function Retrieves the field that is being edited.
FieldConfigurationForm::getFormId public function Returns a unique string identifying the form. Overrides EntityForm::getFormId
FieldConfigurationForm::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 EntityForm::submitForm
FieldConfigurationForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
FieldConfigurationForm::__construct public function Constructs a FieldConfigurationForm 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.
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 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.
UnsavedConfigurationFormTrait::$dateFormatter protected property The date formatter.
UnsavedConfigurationFormTrait::$renderer protected property The renderer.
UnsavedConfigurationFormTrait::checkEntityEditable protected function Checks whether the given entity contains unsaved changes.
UnsavedConfigurationFormTrait::getDateFormatter public function Retrieves the date formatter.
UnsavedConfigurationFormTrait::getRenderer public function Retrieves the renderer.
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.