class ServerForm in Search API 8
Provides a form for creating and editing search servers.
Hierarchy
- class \Drupal\Core\Form\FormBase implements ContainerInjectionInterface, FormInterface uses DependencySerializationTrait, LoggerChannelTrait, MessengerTrait, LinkGeneratorTrait, RedirectDestinationTrait, UrlGeneratorTrait, StringTranslationTrait
- class \Drupal\Core\Entity\EntityForm implements EntityFormInterface
- class \Drupal\search_api\Form\ServerForm
- class \Drupal\Core\Entity\EntityForm implements EntityFormInterface
Expanded class hierarchy of ServerForm
File
- src/
Form/ ServerForm.php, line 22
Namespace
Drupal\search_api\FormView 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
Name | Modifiers | Type | Description | Overrides |
---|---|---|---|---|
DependencySerializationTrait:: |
protected | property | An array of entity type IDs keyed by the property name of their storages. | |
DependencySerializationTrait:: |
protected | property | An array of service IDs keyed by property name used for serialization. | |
DependencySerializationTrait:: |
public | function | 1 | |
DependencySerializationTrait:: |
public | function | 2 | |
EntityForm:: |
protected | property | The entity being used by this form. | 7 |
EntityForm:: |
protected | property | The entity type manager. | 3 |
EntityForm:: |
protected | property | The module handler service. | |
EntityForm:: |
protected | property | The name of the current operation. | |
EntityForm:: |
private | property | The entity manager. | |
EntityForm:: |
protected | function | Returns the action form element for the current entity form. | |
EntityForm:: |
public | function | Form element #after_build callback: Updates the entity with submitted data. | |
EntityForm:: |
public | function |
Builds an updated entity object based upon the submitted form values. Overrides EntityFormInterface:: |
2 |
EntityForm:: |
public | function |
Form constructor. Overrides FormInterface:: |
10 |
EntityForm:: |
protected | function | Copies top-level form values to entity properties | 7 |
EntityForm:: |
public | function |
Returns a string identifying the base form. Overrides BaseFormIdInterface:: |
5 |
EntityForm:: |
public | function |
Gets the form entity. Overrides EntityFormInterface:: |
|
EntityForm:: |
public | function |
Determines which entity will be used by this form from a RouteMatch object. Overrides EntityFormInterface:: |
1 |
EntityForm:: |
public | function |
Returns a unique string identifying the form. Overrides FormInterface:: |
10 |
EntityForm:: |
public | function |
Gets the operation identifying the form. Overrides EntityFormInterface:: |
|
EntityForm:: |
protected | function | Initialize the form state and the entity before the first form build. | 3 |
EntityForm:: |
protected | function | Prepares the entity object before the form is built first. | 3 |
EntityForm:: |
protected | function | Invokes the specified prepare hook variant. | |
EntityForm:: |
public | function | Process callback: assigns weights and hides extra fields. | |
EntityForm:: |
public | function |
Sets the form entity. Overrides EntityFormInterface:: |
|
EntityForm:: |
public | function |
Sets the entity manager for this form. Overrides EntityFormInterface:: |
|
EntityForm:: |
public | function |
Sets the entity type manager for this form. Overrides EntityFormInterface:: |
|
EntityForm:: |
public | function |
Sets the module handler for this form. Overrides EntityFormInterface:: |
|
EntityForm:: |
public | function |
Sets the operation for this form. Overrides EntityFormInterface:: |
|
EntityForm:: |
public | function | ||
EntityForm:: |
public | function | ||
FormBase:: |
protected | property | The config factory. | 1 |
FormBase:: |
protected | property | The request stack. | 1 |
FormBase:: |
protected | property | The route match. | |
FormBase:: |
protected | function | Retrieves a configuration object. | |
FormBase:: |
protected | function | Gets the config factory for this form. | 1 |
FormBase:: |
private | function | Returns the service container. | |
FormBase:: |
protected | function | Gets the current user. | |
FormBase:: |
protected | function | Gets the request object. | |
FormBase:: |
protected | function | Gets the route match. | |
FormBase:: |
protected | function | Gets the logger for a specific channel. | |
FormBase:: |
protected | function |
Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait:: |
|
FormBase:: |
public | function | Resets the configuration factory. | |
FormBase:: |
public | function | Sets the config factory for this form. | |
FormBase:: |
public | function | Sets the request stack object to use. | |
LinkGeneratorTrait:: |
protected | property | The link generator. | 1 |
LinkGeneratorTrait:: |
protected | function | Returns the link generator. | |
LinkGeneratorTrait:: |
protected | function | Renders a link to a route given a route name and its parameters. | |
LinkGeneratorTrait:: |
public | function | Sets the link generator service. | |
LoggerChannelTrait:: |
protected | property | The logger channel factory service. | |
LoggerChannelTrait:: |
protected | function | Gets the logger for a specific channel. | |
LoggerChannelTrait:: |
public | function | Injects the logger channel factory. | |
MessengerTrait:: |
public | function | Gets the messenger. | 29 |
MessengerTrait:: |
public | function | Sets the messenger. | |
RedirectDestinationTrait:: |
protected | property | The redirect destination service. | 1 |
RedirectDestinationTrait:: |
protected | function | Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url. | |
RedirectDestinationTrait:: |
protected | function | Returns the redirect destination service. | |
RedirectDestinationTrait:: |
public | function | Sets the redirect destination service. | |
ServerForm:: |
protected | property | The backend plugin manager. | |
ServerForm:: |
protected | property |
The messenger. Overrides MessengerTrait:: |
|
ServerForm:: |
protected | function |
Returns an array of supported actions for the current entity form. Overrides EntityForm:: |
|
ServerForm:: |
public static | function | Handles switching the selected backend plugin. | |
ServerForm:: |
public | function | Builds the backend-specific configuration form. | |
ServerForm:: |
public | function | Builds the form for the basic server properties. | |
ServerForm:: |
public static | function |
Instantiates a new instance of this class. Overrides FormBase:: |
|
ServerForm:: |
public | function |
Gets the actual form array to be built. Overrides EntityForm:: |
|
ServerForm:: |
public | function |
Form submission handler for the 'save' action. Overrides EntityForm:: |
|
ServerForm:: |
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:: |
|
ServerForm:: |
public | function |
Form validation handler. Overrides FormBase:: |
|
ServerForm:: |
public | function | Constructs a ServerForm object. | |
StringTranslationTrait:: |
protected | property | The string translation service. | 1 |
StringTranslationTrait:: |
protected | function | Formats a string containing a count of items. | |
StringTranslationTrait:: |
protected | function | Returns the number of plurals supported by a given language. | |
StringTranslationTrait:: |
protected | function | Gets the string translation service. | |
StringTranslationTrait:: |
public | function | Sets the string translation service to use. | 2 |
StringTranslationTrait:: |
protected | function | Translates a string to the current language or to a given language. | |
UrlGeneratorTrait:: |
protected | property | The url generator. | |
UrlGeneratorTrait:: |
protected | function | Returns the URL generator service. | |
UrlGeneratorTrait:: |
public | function | Sets the URL generator service. | |
UrlGeneratorTrait:: |
protected | function | Generates a URL or path for a specific route based on the given parameters. |