View source
<?php
namespace Drupal\social_search\Form;
use Drupal\Component\Utility\Xss;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Url;
use Drupal\Component\Utility\UrlHelper;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\RequestStack;
class SearchHeroForm extends FormBase implements ContainerInjectionInterface {
protected $routeMatch;
protected $requestStack;
public function __construct(RouteMatchInterface $routeMatch, RequestStack $requestStack) {
$this->routeMatch = $routeMatch;
$this->requestStack = $requestStack;
}
public static function create(ContainerInterface $container) {
return new static($container
->get('current_route_match'), $container
->get('request_stack'));
}
public function getFormId() {
return 'search_hero_form';
}
public function buildForm(array $form, FormStateInterface $form_state) {
$form['search_input'] = [
'#type' => 'textfield',
'#title' => $this
->t('Search'),
'#title_display' => 'invisible',
];
$form['search_input']['#default_value'] = $this->routeMatch
->getParameter('keys');
$form['actions'] = [
'#type' => 'actions',
];
$form['actions']['submit'] = [
'#type' => 'submit',
'#value' => $this
->t('Search'),
];
$form['#cache']['contexts'][] = 'url';
return $form;
}
public function submitForm(array &$form, FormStateInterface $form_state) {
$current_route = $this->routeMatch
->getRouteName();
$route_parts = explode('.', $current_route);
if (empty($form_state
->getValue('search_input'))) {
$new_route = "view.{$route_parts[1]}.page_no_value";
$search_group_page = Url::fromRoute($new_route);
}
else {
$search_input = Xss::filter($form_state
->getValue('search_input'));
$search_input = preg_replace('/[\\/]+/', ' ', $search_input);
$search_input = str_replace('&', '&', $search_input);
$new_route = "view.{$route_parts[1]}.page";
$search_group_page = Url::fromRoute($new_route, [
'keys' => $search_input,
]);
}
$redirect_path = $search_group_page
->toString();
$query = UrlHelper::filterQueryParameters($this->requestStack
->getCurrentRequest()->query
->all(), [
'page',
]);
$redirect = Url::fromUserInput($redirect_path, [
'query' => $query,
]);
$form_state
->setRedirectUrl($redirect);
}
}