View source
<?php
namespace Drupal\search\Form;
use Drupal\Core\Entity\EntityForm;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\PluginFormInterface;
use Drupal\search\SearchPageRepositoryInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
abstract class SearchPageFormBase extends EntityForm {
protected $entity;
protected $plugin;
protected $searchPageRepository;
public function __construct(SearchPageRepositoryInterface $search_page_repository) {
$this->searchPageRepository = $search_page_repository;
}
public static function create(ContainerInterface $container) {
return new static($container
->get('search.search_page_repository'));
}
public function getBaseFormId() {
return 'search_entity_form';
}
public function buildForm(array $form, FormStateInterface $form_state) {
$this->plugin = $this->entity
->getPlugin();
return parent::buildForm($form, $form_state);
}
public function form(array $form, FormStateInterface $form_state) {
$form['label'] = [
'#type' => 'textfield',
'#title' => $this
->t('Label'),
'#description' => $this
->t('The label for this search page.'),
'#default_value' => $this->entity
->label(),
'#maxlength' => '255',
];
$form['id'] = [
'#type' => 'machine_name',
'#default_value' => $this->entity
->id(),
'#disabled' => !$this->entity
->isNew(),
'#maxlength' => 64,
'#machine_name' => [
'exists' => [
$this,
'exists',
],
],
];
$form['path'] = [
'#type' => 'textfield',
'#title' => $this
->t('Path'),
'#field_prefix' => 'search/',
'#default_value' => $this->entity
->getPath(),
'#maxlength' => '255',
'#required' => TRUE,
];
$form['plugin'] = [
'#type' => 'value',
'#value' => $this->entity
->get('plugin'),
];
if ($this->plugin instanceof PluginFormInterface) {
$form += $this->plugin
->buildConfigurationForm($form, $form_state);
}
return parent::form($form, $form_state);
}
public function exists($id) {
$entity = $this->entityTypeManager
->getStorage('search_page')
->getQuery()
->condition('id', $id)
->execute();
return (bool) $entity;
}
public function validateForm(array &$form, FormStateInterface $form_state) {
parent::validateForm($form, $form_state);
$path = $this->entityTypeManager
->getStorage('search_page')
->getQuery()
->condition('path', $form_state
->getValue('path'))
->condition('id', $form_state
->getValue('id'), '<>')
->execute();
if ($path) {
$form_state
->setErrorByName('path', $this
->t('The search page path must be unique.'));
}
if ($this->plugin instanceof PluginFormInterface) {
$this->plugin
->validateConfigurationForm($form, $form_state);
}
}
public function submitForm(array &$form, FormStateInterface $form_state) {
parent::submitForm($form, $form_state);
if ($this->plugin instanceof PluginFormInterface) {
$this->plugin
->submitConfigurationForm($form, $form_state);
}
return $this->entity;
}
public function save(array $form, FormStateInterface $form_state) {
$this->entity
->save();
$form_state
->setRedirectUrl($this->entity
->toUrl('collection'));
}
}