A backend widget for Contao that lets editors search and select records from a chosen provider.
Install via Composer:
composer require terminal42/contao-search-widget'myField' => [
'inputType' => 'searchWidget',
'eval' => [
'searchProviderKey' => 'my_provider',
'searchProviderOptions' => ['country' => 'CH'],
'tl_class' => 'clr',
],
'sql' => ['type' => \Doctrine\DBAL\Types\Types::INTEGER, 'unsigned' => true, 'default' => 0],
],<?php
namespace App\SearchWidget;
use Symfony\Component\DependencyInjection\Attribute\AutoconfigureTag;
use Terminal42\SearchWidgetBundle\DataProvider\DataProviderInterface;
use Terminal42\SearchWidgetBundle\Exception\InvalidSearchConfigException;
use Terminal42\SearchWidgetBundle\Search\Config\SearchConfig;
use Terminal42\SearchWidgetBundle\Search\Criteria\SearchCriteria;
use Terminal42\SearchWidgetBundle\Search\Results\SearchHeader;
use Terminal42\SearchWidgetBundle\Search\Results\SearchResult;
use Terminal42\SearchWidgetBundle\Search\Results\SearchResultField;
use Terminal42\SearchWidgetBundle\Search\Results\SearchResults;
#[AutoconfigureTag(DataProviderInterface::class, attributes: ['key' => 'my_provider'])]
class MyProvider implements DataProviderInterface
{
public function search(SearchConfig $config, SearchCriteria $criteria): SearchResults
{
$items = $this->fetchItems($config, $criteria); // Your custom method to fetch items
if ([] === $items) {
return SearchResults::empty();
}
$headers = [
new SearchHeader('name', 'Name'),
new SearchHeader('address', 'Address'),
];
$results = [];
foreach ($items as $item) {
$results[] = new SearchResult($item['id'], [
new SearchResultField('name', $item['name']),
new SearchResultField('address', $item['address']),
]);
}
// Paginate only for keyword searches – pre-selected records must stay complete.
if ($criteria->getKeywords()) {
$results = array_slice($results, 0, $config->getLimit());
}
return new SearchResults($headers, $results, count($items));
}
public function validate(SearchConfig $config): void
{
$options = $config->getProviderOptions();
if (empty($options['country'])) {
throw new InvalidSearchConfigException('The country is missing.');
}
}
}| Option | Type | Default | Description |
|---|---|---|---|
searchProviderKey |
string |
– | The search provider used for the search. |
| Option | Type | Default | Description |
|---|---|---|---|
searchProviderOptions |
array |
[] |
Provider-specific options passed to the SearchConfig object. |
limit |
int |
10 |
The maximum number of items the widget returns. |
multiple |
bool |
false |
Allows selecting multiple records. |
isSortable |
bool |
false |
Enables drag-and-drop sorting. Only effective when multiple = true. |
resultsTemplate |
string |
backend/search_widget/results |
The results template. Resolves to @Contao/backend/search_widget/results.html.twig. |
