Process and render search results.

@param array $data The raw request data submitted by user
@param SearchForm $form The form instance that was submitted
@param HTTPRequest $request Request generated for this action
@return DBHTMLText
335709
public function results($data, $form, $request)
    {
        // Check parameters for terms, pagination, and if we should follow suggestions
        $keywords = empty($data['Search']) ? '' : $data['Search'];
        $start = isset($data['start']) ? $data['start'] : 0;
        $suggestions = isset($data['suggestions'])
            ? $data['suggestions']
            : $this->config()->get('search_follow_suggestions');

        $results = CwpSearchEngine::create()
            ->search(
                $keywords,
                $this->config()->get('classes_to_search'),
                Injector::inst()->get(CwpSearchEngine::class . '.search_index'),
                $this->config()->get('results_per_page'),
                $start,
                $suggestions
            );

        // Customise content with these results
        $properties = [
            'MetaTitle' => _t(__CLASS__ . '.MetaTitle', 'Search {keywords}', ['keywords' => $keywords]),
            'NoSearchResults' => _t(__CLASS__ . '.NoResult', 'Sorry, your search query did not return any results.'),
            'EmptySearch' => _t(__CLASS__ . '.EmptySearch', 'Search field empty, please enter your search query.'),
            'PdfLink' => '',
            'Title' => _t('SilverStripe\\CMS\\Search\\SearchForm.SearchResults', 'Search Results'),
        ];
        $this->owner->extend('updateSearchResults', $results, $properties);

        // Customise page
        /** @var ViewableData_Customised $response */
        $response = $this->owner->customise($properties);
        if ($results) {
            $response = $response
                ->customise($results)
                ->customise(['Results' => $results->getResults()]);
        }

        // Render
        $templates = $this->getResultsTemplate($request);
        return $response->renderWith($templates);
    }
1107195
public function doRegistryFilter($data, $form, $request)
    {
        $singleton = $this->dataRecord->getDataSingleton();

        // Restrict fields
        $fields = array_merge(['start', 'Sort', 'Dir'], $singleton->config()->get('searchable_fields'));
        $params = [];
        foreach ($fields as $field) {
            $value = $this->getRequest()->getVar(str_replace('.', '_', $field));
            if ($value) {
                $params[$field] = $value;
            }
        }

        // Link back to this page with the relevant parameters
        $this->redirect($this->Link('?' . http_build_query($params)));
    }
584176
public function getForm($request = null, $sorting = true) {

		// Determine whether a search engine has been selected.

		$engine = $this->data()->SearchEngine;
		$configuration = Config::inst();
		$classes = $configuration->get(FulltextSearchable::class, 'searchable_classes');
		if(!$engine || (($engine !== 'Full-Text') && !ClassInfo::exists($engine)) || (($engine === 'Full-Text') && (!is_array($classes) || (count($classes) === 0)))) {

			// The search engine has not been selected.

			return null;
		}

		// Determine whether the request has been passed through.

		if(is_null($request)) {
			$request = $this->getRequest();
		}

		// Display the search.

		$fields = FieldList::create(
			TextField::create(
				'Search',
				_t('EXTENSIBLE_SEARCH.SEARCH', 'Search'),
				$request->getVar('Search')
			)->addExtraClass('extensible-search')->setAttribute('data-suggestions-enabled', $configuration->get(ExtensibleSearchSuggestion::class, 'enable_suggestions') ? 'true' : 'false')->setAttribute('data-extensible-search-page', $this->data()->ID)
		);

		// Determine whether sorting has been passed through from the template.

		if(is_string($sorting)) {
			$sorting = ($sorting === 'true');
		}

		// Determine whether to display the sorting selection.

		if($sorting) {

			// Display the sorting selection.

			$fields->push(DropdownField::create(
				'SortBy',
				_t('EXTENSIBLE_SEARCH.SORT_BY', 'Sort By'),
				$this->data()->getSelectableFields(),
				$request->getVar('SortBy') ? $request->getVar('SortBy') : $this->data()->SortBy
			)->setHasEmptyDefault(true));
			$fields->push(DropdownField::create(
				'SortDirection',
				_t('EXTENSIBLE_SEARCH.SORT_DIRECTION', 'Sort Direction'),
				array(
					'DESC' => _t('EXTENSIBLE_SEARCH.DESCENDING', 'Descending'),
					'ASC' => _t('EXTENSIBLE_SEARCH.ASCENDING', 'Ascending')
				),
				$request->getVar('SortDirection') ? $request->getVar('SortDirection') : $this->data()->SortDirection
			)->setHasEmptyDefault(true));
		}

		// Instantiate the search form.

		$form = SearchForm::create(
			$this,
			'getForm',
			$fields,
			FieldList::create(
				FormAction::create(
					'getSearchResults',
					_t('EXTENSIBLE_SEARCH.GO', 'Go')
				)
			)
		);

		// When using the full-text search engine, the classes to search needs to be initialised.

		if($engine === 'Full-Text') {
			$form->classesToSearch($classes);
		}

		// Allow extension customisation.

		$this->extend('updateExtensibleSearchForm', $form);
		return $form;
	}
1162189
public function search(HTTPRequest $request)
    {
        // Detect Ajax:
        
        if (!$request->isAjax()) {
            return;
        }
        
        // Initialise:
        
        $data = ['results' => []];
        
        // Create Data List:
        
        $list = $this->getList();
        
        // Filter Data List:
        
        if ($term = $request->getVar('term')) {
            $list = $list->filterAny($this->getSearchFilters($term))->exclude($this->getExclude());
        }
        
        // Sort Data List:
        
        if ($sort = $this->getSortBy()) {
            $list = $list->sort($sort);
        }
        
        // Limit Data List:
        
        if ($limit = $this->getLimit()) {
            $list = $list->limit($limit);
        }
        
        // Define Results:
        
        foreach ($list as $record) {
            $data['results'][] = $this->getResultData($record);
        }
        
        // Answer JSON Response:
        
        return $this->respond($data);
    }
1047367
public function doNext($data, $form)
    {
        $this->getToplevelController()->getResponse()->addHeader('X-Pjax', 'Content');
        $link = $this->getEditLink($this->getNextRecordID());
        return $this->redirect($link);
    }
85769
public function searchFillerAction(Request $request)
    {
        /* @var $chain ChainFiller */
        $chain = $this->get('anime_db.plugin.filler');
        $response = $this->getResponseFromChain($chain);

        // response was not modified for this request
        if ($response->isNotModified($request)) {
            return $response;
        }

        $entity = new SearchFiller($chain);
        /* @var $form Form */
        $form = $this->createForm(new SearchFillerForm(), $entity)->handleRequest($request);
        if ($form->isValid()) {
            return $this->redirect($entity->getFiller()->getLinkForFill($entity->getUrl()));
        }

        return $this->render('AnimeDbCatalogBundle:Fill:search_filler.html.twig', [
            'form' => $form->createView(),
        ], $response);
    }
221179
public function executeFormUpdateRequest(WebRequest $request, Response $response, Form $form)
    {
        $responseData = array('csrf' => $form->generateCsrfToken($request));
        
        // If the search param not set return with an empty response
        if (!$request->hasParam('form-extended-entity-select-query')) {
            $responseData['data'] = array();
            $response->setOutput(json_encode($responseData), true);
            return;
        }
        
        $query = $request->getParam('form-extended-entity-select-query');
        $entities = $this->getAvailableValues($query);
        
        if ($entities === false) {
            $response->setOutput(json_encode(array('error' => true)), true);
            return;
        }
        
        $data = array();
        foreach ($entities as $entity) {
            $data[] = array('id' => $entity->getId(), 'name' => (string) $entity);
        }
        
        $responseData['data'] = $data;
        
        $response->setOutput(json_encode($responseData), true);
    }
111521
public function searchSimpleFormAction()
    {
        $form = new SearchSimple($this->generateUrl('home_autocomplete_name'));

        return $this->render('AnimeDbCatalogBundle:Home:searchSimpleForm.html.twig', [
            'form' => $this->createForm($form)->createView(),
        ]);
    }
887083
public function doSaveLink($data, Form $form)
    {
        $link = $this->getLinkObject() ? $this->getLinkObject() : Link::create();
        $form->saveInto($link);

        try {
            $link->write();
        } catch (ValidationException $e) {
            $form->sessionMessage($e->getMessage(), 'bad');

            return $form->forTemplate();
        }

        $this->setValue($link->ID);
        $this->setForm($form);

        return $this->FieldHolder();
    }
1120769
public function formAction(HTTPRequest $request)
    {
        $formName = $request->param('FormName');

        // Get the element ID from the form name
        $id = substr($formName, strlen(sprintf(self::FORM_NAME_TEMPLATE, '')));
        $form = $this->getElementForm($id);

        $field = $form->getRequestHandler()->handleField($request);

        return $field->handleRequest($request);
    }
143647
private function handleAction(Request $request, &$data) {
        // Keyword Search
        if ($this->isAction($request, "searchByKeyword")) {
            $preparedKeywords = htmlspecialchars($data["keywords"]);
            $data["listings"] = $this->listingController($data)
                    ->setSortBy($data["sortBy"])->setReverseSort($data["reverseSort"])
                    ->searchByKeyword($preparedKeywords);
        }
        // Advanced Search
        else if ($this->isAction($request, "search")) {
            $data["listings"] = $this->listingController($data)
                    ->setSortBy($data["sortBy"])->setReverseSort($data["reverseSort"])
                    ->search($data["keywords"], $data["extra"], $data["maxPrice"], $data["minPrice"], $data["beds"], $data["baths"], $data["includeResidential"], $data["includeLand"], $data["includeCommercial"]);
        }
        // Return Listings by DMQL
        else if ($this->isAction($request, "getListingsByDMQL")) {
            $results = GetRETS::getRETSListing()
                    ->setSortBy($data["sortBy"])->setReverseSort($data["reverseSort"])
                    ->getListingsByDMQL($data["dmql"], ExampleController::EXAMPLE_SOURCE, "Residential");
            if (!empty($results)) {
                if ($results->success && !empty($results->data)) {
                    $data["listings"] = $results->data;
                }
            }
        }
        // Return raw DMQL results
        else if ($this->isAction($request, "executeDMQL")) {
            $data["rawData"] = GetRETS::getRETSListing()->executeDMQL($data["dmql"], ExampleController::EXAMPLE_SOURCE, "Residential");
        }
    }
1284233
public function search(SearchRequest $searchRequest)
    {
        $resultSet = $this->getInitializedSearchResultSet($searchRequest);
        $this->lastResultSet = $resultSet;

        $resultSet = $this->handleSearchHook('beforeSearch', $resultSet);
        if ($this->shouldReturnEmptyResultSetWithoutExecutedSearch($searchRequest)) {
            $resultSet->setHasSearched(false);
            return $resultSet;
        }

        $query = $this->queryBuilder->buildSearchQuery($searchRequest->getRawUserQuery(), (int)$searchRequest->getResultsPerPage(), $searchRequest->getAdditionalFilters());
        $this->initializeRegisteredSearchComponents($query, $searchRequest);
        $resultSet->setUsedQuery($query);

        // performing the actual search, sending the query to the Solr server
        $query = $this->modifyQuery($query, $searchRequest, $this->search);
        $response = $this->doASearch($query, $searchRequest);

        if ((int)$searchRequest->getResultsPerPage() === 0) {
            // when resultPerPage was forced to 0 we also set the numFound to 0 to hide results, e.g.
            // when results for the initial search should not be shown.
            $response->response->numFound = 0;
        }

        $resultSet->setHasSearched(true);
        $resultSet->setResponse($response);

        $this->getParsedSearchResults($resultSet);

        $resultSet->setUsedAdditionalFilters($this->queryBuilder->getAdditionalFilters());

        /** @var $variantsProcessor VariantsProcessor */
        $variantsProcessor = GeneralUtility::makeInstance(
            VariantsProcessor::class,
            /** @scrutinizer ignore-type */ $this->typoScriptConfiguration,
            /** @scrutinizer ignore-type */ $this->searchResultBuilder
        );
        $variantsProcessor->process($resultSet);

        /** @var $searchResultReconstitutionProcessor ResultSetReconstitutionProcessor */
        $searchResultReconstitutionProcessor = GeneralUtility::makeInstance(ResultSetReconstitutionProcessor::class);
        $searchResultReconstitutionProcessor->process($resultSet);

        $resultSet = $this->getAutoCorrection($resultSet);

        return $this->handleSearchHook('afterSearch', $resultSet);
    }
148305
public function restore($data, $form)
    {
        if (!isset($data['ID']) || !is_numeric($data['ID'])) {
            return new HTTPResponse("Please pass an ID in the form content", 400);
        }

        $id = (int)$data['ID'];
        /** @var SiteTree $restoredPage */
        $restoredPage = Versioned::get_latest_version(SiteTree::class, $id);
        if (!$restoredPage) {
            return new HTTPResponse("SiteTree #$id not found", 400);
        }

        $restoredPage = $restoredPage->doRestoreToStage();

        $this->getResponse()->addHeader(
            'X-Status',
            rawurlencode(_t(
                __CLASS__ . '.RESTORED',
                "Restored '{title}' successfully",
                array('title' => $restoredPage->Title)
            ))
        );

        return $this->getResponseNegotiator()->respond($this->getRequest());
    }
978101
public function searchAction(Request $request)
    {
        $queryString = $request->query->get('q');
        $index = $request->query->get('index', null);
        $locale = $request->query->get('locale', null);

        $page = $this->listRestHelper->getPage();
        $limit = $this->listRestHelper->getLimit();
        $startTime = microtime(true);

        $indexes = $index ? [$index] : $this->getAllowedIndexes();

        $query = $this->searchManager->createSearch($queryString);

        if ($locale) {
            $query->locale($locale);
        }

        $query->indexes($indexes);
        $query->setLimit($limit);

        $time = microtime(true) - $startTime;

        $adapter = new ArrayAdapter(iterator_to_array($query->execute()));
        $pager = new Pagerfanta($adapter);
        $pager->setMaxPerPage($limit);
        $pager->setCurrentPage($page);

        $representation = new SearchResultRepresentation(
            new CollectionRepresentation($pager->getCurrentPageResults(), 'result'),
            'sulu_search_search',
            [
                'locale' => $locale,
                'query' => $query,
                'index' => $index,
            ],
            (int) $page,
            (int) $limit,
            $pager->getNbPages(),
            'page',
            'limit',
            false,
            $adapter->getNbResults(),
            $this->getIndexTotals($adapter->getArray()),
            number_format($time, 8)
        );

        $view = View::create($representation);
        $context = new Context();
        $context->enableMaxDepth();
        $view->setContext($context);

        return $this->viewHandler->handle($view);
    }
569097
public function search( Form $form, SearchCriteriaBuilder $searchCriteriaBuilder, SearchResultConverter $resultConverter, $offset, $length, $params = array() ) {

        $criteria = $searchCriteriaBuilder->build($form, $offset, $length, $params);

        $legacyKernelClosure = $this->kernel;

        $searchResults = $legacyKernelClosure()->runCallback(
            function () use ( $criteria )
            {
                return eZFunctionHandler::execute(
                    'ezfind',
                    'search',
                    $criteria
                );
            }
        );
        return $resultConverter->convert( $searchResults );
    }
630510
protected function getViewParameters(Request $request, Form $form = null, $data = null): array
    {
        $parameters = [
            'isAjax' => $request->isXmlHttpRequest(),
            'target' => $request->get('target'),
            'success' => $request->get('success'),
            'isModal' => $request->isXmlHttpRequest() && $request->get('modal'),
            'listPath' => $this->getAdminListPath($data),
            'admin' => $this->admin,
        ];

        if ($form) {
            $parameters['form'] = $form->createView();
        }
        if ($data) {
            $parameters['data'] = $data;
        }

        return $parameters;
    }
809142
public function searchAction(Request $request)
    {
        $expression = $request->request->get('expression');

        $results = $this->get('ekyna_cms.wide_search')->search($expression);

        return $this->render('@EkynaCms/Cms/search.html.twig', array(
            'expression' => $expression,
            'results'    => $results,
        ))->setPrivate();
    }