You are here

class ServerForm in Search API 8

Provides a form for creating and editing search servers.

Hierarchy

Expanded class hierarchy of ServerForm

File

src/Form/ServerForm.php, line 22

Namespace

Drupal\search_api\Form
View source
class ServerForm extends EntityForm {

  /**
   * The backend plugin manager.
   *
   * @var \Drupal\search_api\Backend\BackendPluginManager
   */
  protected $backendPluginManager;

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

  /**
   * Constructs a ServerForm object.
   *
   * @param \Drupal\search_api\Backend\BackendPluginManager $backend_plugin_manager
   *   The backend plugin manager.
   * @param \Drupal\Core\Messenger\MessengerInterface $messenger
   *   The messenger.
   */
  public function __construct(BackendPluginManager $backend_plugin_manager, MessengerInterface $messenger) {
    $this->backendPluginManager = $backend_plugin_manager;
    $this->messenger = $messenger;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    $backend_plugin_manager = $container
      ->get('plugin.manager.search_api.backend');
    $messenger = $container
      ->get('messenger');
    return new static($backend_plugin_manager, $messenger);
  }

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

    // If the form is being rebuilt, rebuild the entity with the current form
    // values.
    if ($form_state
      ->isRebuilding()) {
      $this->entity = $this
        ->buildEntity($form, $form_state);
    }
    $form = parent::form($form, $form_state);

    /** @var \Drupal\search_api\ServerInterface $server */
    $server = $this
      ->getEntity();

    // Set the page title according to whether we are creating or editing the
    // server.
    if ($server
      ->isNew()) {
      $form['#title'] = $this
        ->t('Add search server');
    }
    else {
      $form['#title'] = $this
        ->t('Edit search server %label', [
        '%label' => $server
          ->label(),
      ]);
    }
    $this
      ->buildEntityForm($form, $form_state, $server);

    // Skip adding the backend config form if we cleared the server form due to
    // an error.
    if ($form) {
      $this
        ->buildBackendConfigForm($form, $form_state, $server);
    }
    return $form;
  }

  /**
   * Builds the form for the basic server properties.
   *
   * @param array $form
   *   The current form array.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current form state.
   * @param \Drupal\search_api\ServerInterface $server
   *   The server that is being created or edited.
   */
  public function buildEntityForm(array &$form, FormStateInterface $form_state, ServerInterface $server) {
    $form['#attached']['library'][] = 'search_api/drupal.search_api.admin_css';
    $form['name'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Server name'),
      '#description' => $this
        ->t('Enter the displayed name for the server.'),
      '#default_value' => $server
        ->label(),
      '#required' => TRUE,
    ];
    $form['id'] = [
      '#type' => 'machine_name',
      '#default_value' => $server
        ->isNew() ? NULL : $server
        ->id(),
      '#maxlength' => 50,
      '#required' => TRUE,
      '#machine_name' => [
        'exists' => '\\Drupal\\search_api\\Entity\\Server::load',
        'source' => [
          'name',
        ],
      ],
      '#disabled' => !$server
        ->isNew(),
    ];
    $form['status'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Enabled'),
      '#description' => $this
        ->t('Only enabled servers can index items or execute searches.'),
      '#default_value' => $server
        ->status(),
    ];
    $form['description'] = [
      '#type' => 'textarea',
      '#title' => $this
        ->t('Description'),
      '#description' => $this
        ->t('Enter a description for the server.'),
      '#default_value' => $server
        ->getDescription(),
    ];
    $backends = $this->backendPluginManager
      ->getDefinitions();
    $backend_options = [];
    $descriptions = [];
    foreach ($backends as $backend_id => $definition) {
      $config = $backend_id === $server
        ->getBackendId() ? $server
        ->getBackendConfig() : [];
      $config['#server'] = $server;
      try {

        /** @var \Drupal\search_api\Backend\BackendInterface $backend */
        $backend = $this->backendPluginManager
          ->createInstance($backend_id, $config);
      } catch (PluginException $e) {
        continue;
      }
      if ($backend
        ->isHidden()) {
        continue;
      }
      $backend_options[$backend_id] = Utility::escapeHtml($backend
        ->label());
      $descriptions[$backend_id]['#description'] = Utility::escapeHtml($backend
        ->getDescription());
    }
    asort($backend_options, SORT_NATURAL | SORT_FLAG_CASE);
    if ($backend_options) {
      if (count($backend_options) == 1) {
        $server
          ->set('backend', key($backend_options));
      }
      $form['backend'] = [
        '#type' => 'radios',
        '#title' => $this
          ->t('Backend'),
        '#description' => $this
          ->t('Choose a backend to use for this server.'),
        '#options' => $backend_options,
        '#default_value' => $server
          ->getBackendId(),
        '#required' => TRUE,
        '#disabled' => !$server
          ->isNew(),
        '#ajax' => [
          'callback' => [
            get_class($this),
            'buildAjaxBackendConfigForm',
          ],
          'wrapper' => 'search-api-backend-config-form',
          'method' => 'replace',
          'effect' => 'fade',
        ],
      ];
      $form['backend'] += $descriptions;
    }
    else {
      $url = 'https://www.drupal.org/docs/8/modules/search-api/getting-started/server-backends-and-features';
      $args[':url'] = Url::fromUri($url)
        ->toString();
      $error = $this
        ->t('There are no backend plugins available for the Search API. Please install a <a href=":url">module that provides a backend plugin</a> to proceed.', $args);
      $this->messenger
        ->addError($error);
      $form = [];
    }
  }

  /**
   * {@inheritdoc}
   */
  protected function actions(array $form, FormStateInterface $form_state) {
    if ($form === []) {
      return [];
    }
    return parent::actions($form, $form_state);
  }

  /**
   * Builds the backend-specific configuration form.
   *
   * @param array $form
   *   The current form array.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current form state.
   * @param \Drupal\search_api\ServerInterface $server
   *   The server that is being created or edited.
   */
  public function buildBackendConfigForm(array &$form, FormStateInterface $form_state, ServerInterface $server) {
    $form['backend_config'] = [];
    if ($server
      ->hasValidBackend()) {
      $backend = $server
        ->getBackend();
      $form_state
        ->set('backend', $backend
        ->getPluginId());
      if ($backend instanceof PluginFormInterface) {
        if ($form_state
          ->isRebuilding()) {
          $this->messenger
            ->addWarning($this
            ->t('Please configure the selected backend.'));
        }

        // Attach the backend plugin configuration form.
        $backend_form_state = SubformState::createForSubform($form['backend_config'], $form, $form_state);
        $form['backend_config'] = $backend
          ->buildConfigurationForm($form['backend_config'], $backend_form_state);

        // Modify the backend plugin configuration container element.
        $form['backend_config']['#type'] = 'details';
        $form['backend_config']['#title'] = $this
          ->t('Configure %plugin backend', [
          '%plugin' => $backend
            ->label(),
        ]);
        $form['backend_config']['#open'] = TRUE;
      }
    }
    elseif (!$server
      ->isNew()) {
      $this->messenger
        ->addError($this
        ->t('The backend plugin is missing or invalid.'));
      return;
    }
    $form['backend_config'] += [
      '#type' => 'container',
    ];
    $form['backend_config']['#attributes']['id'] = 'search-api-backend-config-form';
    $form['backend_config']['#tree'] = TRUE;
  }

  /**
   * Handles switching the selected backend plugin.
   *
   * @param array $form
   *   The current form array.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current form state.
   *
   * @return array
   *   The part of the form to return as AJAX.
   */
  public static function buildAjaxBackendConfigForm(array $form, FormStateInterface $form_state) {

    // The work is already done in form(), where we rebuild the entity according
    // to the current form values and then create the backend configuration form
    // based on that. So we just need to return the relevant part of the form
    // here.
    return $form['backend_config'];
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    parent::validateForm($form, $form_state);

    /** @var \Drupal\search_api\ServerInterface $server */
    $server = $this
      ->getEntity();

    // Check if the backend plugin changed.
    $backend_id = $server
      ->getBackendId();
    if ($backend_id != $form_state
      ->get('backend')) {

      // This can only happen during initial server creation, since we don't
      // allow switching the backend afterwards. The user has selected a
      // different backend, so any values entered for the other backend should
      // be discarded.
      $input =& $form_state
        ->getUserInput();
      $input['backend_config'] = [];
      $new_backend = $this->backendPluginManager
        ->createInstance($form_state
        ->getValue('backend'));
      if ($new_backend instanceof PluginFormInterface) {
        $form_state
          ->setRebuild();
      }
    }
    elseif ($server
      ->hasValidBackend()) {
      $backend = $server
        ->getBackend();
      if ($backend instanceof PluginFormInterface) {
        $backend_form_state = SubformState::createForSubform($form['backend_config'], $form, $form_state);
        $backend
          ->validateConfigurationForm($form['backend_config'], $backend_form_state);
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    parent::submitForm($form, $form_state);

    /** @var \Drupal\search_api\ServerInterface $server */
    $server = $this
      ->getEntity();

    // Check before loading the backend plugin so we don't throw an exception.
    if ($server
      ->hasValidBackend()) {
      $backend = $server
        ->getBackend();
      if ($backend instanceof PluginFormInterface) {
        $backend_form_state = SubformState::createForSubform($form['backend_config'], $form, $form_state);
        $backend
          ->submitConfigurationForm($form['backend_config'], $backend_form_state);
      }
    }
    return $server;
  }

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

    // Only save the server if the form doesn't need to be rebuilt.
    if (!$form_state
      ->isRebuilding()) {
      try {
        $server = $this
          ->getEntity();
        $server
          ->save();
        $this->messenger
          ->addStatus($this
          ->t('The server was successfully saved.'));
        $form_state
          ->setRedirect('entity.search_api_server.canonical', [
          'search_api_server' => $server
            ->id(),
        ]);
      } catch (EntityStorageException $e) {
        $form_state
          ->setRebuild();
        $message = '%type: @message in %function (line %line of %file).';
        $variables = Error::decodeException($e);
        $this
          ->getLogger('search_api')
          ->error($message, $variables);
        $this->messenger
          ->addError($this
          ->t('The server could not be 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
EntityForm::$entity protected property The entity being used by this form. 7
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::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::__get public function
EntityForm::__set public function
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.
ServerForm::$backendPluginManager protected property The backend plugin manager.
ServerForm::$messenger protected property The messenger. Overrides MessengerTrait::$messenger
ServerForm::actions protected function Returns an array of supported actions for the current entity form. Overrides EntityForm::actions
ServerForm::buildAjaxBackendConfigForm public static function Handles switching the selected backend plugin.
ServerForm::buildBackendConfigForm public function Builds the backend-specific configuration form.
ServerForm::buildEntityForm public function Builds the form for the basic server properties.
ServerForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
ServerForm::form public function Gets the actual form array to be built. Overrides EntityForm::form
ServerForm::save public function Form submission handler for the 'save' action. Overrides EntityForm::save
ServerForm::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
ServerForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
ServerForm::__construct public function Constructs a ServerForm object.
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.