Search by

martcode / advanced-search

selcukmart

Declarative advanced search for Symfony admin screens: schema-driven filters, filter-axis join pruning, saved searches, multi-tenancy that fails closed, and Bootstrap, light and Tailwind themes.

Package info

github.com/selcukmart/advanced-search

Type:symfony-bundle

pkg:composer/martcode/advanced-search

Statistics

Installs: 3

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

v0.21.0 2026-11-30 17:00 UTC

This package is auto-updated.

Last update: 2026-11-30 20:22:58 UTC


README

CI Packagist PHP License: MIT

Declarative advanced search for Symfony admin screens. A screen declares its searchable fields once; the bundle renders the filter panel, compiles the submitted criteria into SQL with Doctrine DBAL, and pulls in only the joins the submitted filters actually need.

The Tailwind theme

It is the successor to a search engine that ran behind a few hundred admin listings for twelve years. The rewrite keeps what that engine got right (sticky forms, Turkish-aware text matching, saved searches, statistics over the filtered rows) and designs out what it got wrong: column names arriving from input, values escaped by hand, fields that silently failed to render.

The story behind it: Filter-Axis Join Pruning: Rebuilding a 12-Year-Old Search Engine as a Symfony Bundle.

Why

Filter-axis join pruning. Semantic layers such as Looker, Cube and Omni prune joins by the select axis: which columns the user asked to see. Admin CRUD listings have a fixed column set and sixty-odd filters, so the useful axis is the filter one: which field did the user actually search in. That field brings its own SELECT, JOIN and GROUP BY contribution with it, and nothing else is joined.

The reasoning, and what was deliberately kept from the old engine, is in ADR 0001.

Features

  • Schema-driven filters: text, choice (single or multiple), date range and number range types, a phone-number text strategy that matches the significant digits however they were typed, plus your own types and custom predicates.
  • Join graph with cardinality: joins are declared once; a one-to-many join that would inflate counts is caught instead of silently distorting them.
  • List, count and aggregate modes over the same joins and conditions, so a listing and its row count can never drift apart.
  • POST-redirect-GET with shareable URLs, sticky values and sorting links that keep the search.
  • Saved searches and statistics profiles stored as criteria, never as SQL.
  • Dependent lists (pick a region, the branch list narrows) done in the browser from data already on the page.
  • Multi-tenancy that fails closed: the tenant predicate is added to the base table and every join, or the query does not run.
  • Three themes: default (Bootstrap 3 / Metronic-style panel), light (a one-row search bar for list pages) and tailwind (the full panel in Tailwind CSS, with dark mode). Every piece of markup is a Twig block you can override.
  • No jQuery, no globals: one small self-contained script, scoped to each panel.

Requirements

PHP 8.1+, Symfony 6.4 / 7.x / 8.x, Doctrine DBAL 3.6+ or 4, Twig 3.

Installation

composer require martcode/advanced-search

With Symfony Flex, that is all: the bundle is registered in config/bundles.php and its assets are published by assets:install, which Flex projects run after every install. Without Flex, register it yourself:

// config/bundles.php
return [
    // ...
    MartCode\AdvancedSearch\MartCodeAdvancedSearchBundle::class => ['all' => true],
];
php bin/console assets:install

Then include the stylesheet and script on pages that render a search panel:

<link rel="stylesheet" href="{{ asset('bundles/martcodeadvancedsearch/css/search.css') }}">
<script src="{{ asset('bundles/martcodeadvancedsearch/js/search.js') }}" defer></script>

Quick start

1. Declare a schema

A schema is a service implementing SearchSchemaInterface. With autoconfiguration on, nothing else is needed.

use MartCode\AdvancedSearch\Schema\Cardinality;
use MartCode\AdvancedSearch\Schema\SearchSchemaBuilder;
use MartCode\AdvancedSearch\Schema\SearchSchemaInterface;
use MartCode\AdvancedSearch\Type\ChoiceType;
use MartCode\AdvancedSearch\Type\DateRangeType;
use MartCode\AdvancedSearch\Type\NumberRangeType;
use MartCode\AdvancedSearch\Type\TextType;

final class OrderSearchSchema implements SearchSchemaInterface
{
    public function build(SearchSchemaBuilder $b): void
    {
        $b->from('orders', 'o')

          ->add('number', TextType::class, [
              'label'     => 'Order number',
              'column'    => 'o.number',
              'orderable' => true,
          ])

          // Searching by customer name joins `customers`; nothing else does.
          ->add('customer', TextType::class, [
              'label'     => 'Customer',
              'column'    => 'c.name',
              'needsJoin' => 'customers',
          ])

          ->add('status', ChoiceType::class, [
              'label'     => 'Status',
              'column'    => 'o.status',
              'choices'   => ['open' => 'Open', 'paid' => 'Paid', 'shipped' => 'Shipped'],
              'groupable' => true,
          ])

          ->add('placed', DateRangeType::class, ['label' => 'Placed', 'column' => 'o.placed_at'])
          ->add('total', NumberRangeType::class, ['label' => 'Total', 'column' => 'o.total', 'scale' => 2])

          ->join('customers', alias: 'c', on: 'c.id = o.customer_id',
                 cardinality: Cardinality::MANY_TO_ONE);
    }
}

An unknown option or an unknown field type stops the container from compiling. A field that silently fails to appear is the bug this bundle was built to remove.

2. Use it in a controller

use Doctrine\DBAL\Connection;
use MartCode\AdvancedSearch\Http\Attribute\FromSearch;
use MartCode\AdvancedSearch\Http\Search;
use MartCode\AdvancedSearch\Query\QueryMode;

#[Route('/orders', name: 'order_list', methods: ['GET', 'POST'])]
public function index(#[FromSearch(OrderSearchSchema::class)] Search $search, Connection $db): Response
{
    // A submitted search redirects to a GET URL that can be shared and refreshed.
    if ($redirect = $search->getRedirectResponse()) {
        return $redirect;
    }

    $rows = $db->createQueryBuilder()->select('o.id', 'o.number', 'o.status', 'o.total');
    $search->apply($rows);

    $count = $db->createQueryBuilder();
    $search->apply($count, QueryMode::COUNT);

    return $this->render('order/index.html.twig', [
        'search' => $search->createView(),
        'orders' => $rows->setMaxResults(50)->executeQuery()->fetchAllAssociative(),
        'total'  => $count->executeQuery()->fetchOne(),
    ]);
}

#[FromSearch] is a convenience: injecting SearchFactory and calling create(OrderSearchSchema::class, $request) does the same thing.

3. Render the panel

{{ search_start(search) }}
  {{ search_widget(search) }}
{{ search_end(search) }}

Pick a theme per page where the search starts:

{{ search_start(search, {theme: 'tailwind'}) }}   {# or 'light', 'default', or a template name #}

Themes

Theme What it is
default The full panel: field chooser, saved searches, statistics. Bootstrap 3 markup with Metronic-style portlet classes.
light A one-row search bar for list pages: the first fields inline, the rest behind "More filters", applied filters as removable chips.
tailwind The full panel in Tailwind CSS utilities, with dark mode. No Bootstrap, no jQuery; menus are native <details>.

Set the application-wide theme in configuration, and choose another per page with search_start(search, {theme: ...}). A block a theme does not define falls back to the configured theme, then to the bundle default, so overriding one block and inheriting the rest is the normal case. The decisions behind the themes are in ADR 0002 and ADR 0004.

Tailwind setup

Tailwind only generates classes it finds in the files it scans, so add the theme to your sources.

Tailwind 4:

@import "tailwindcss";
@source "../../vendor/martcode/advanced-search/Resources/views";

Tailwind 3:

// tailwind.config.js
content: [
  './templates/**/*.twig',
  './vendor/martcode/advanced-search/Resources/views/**/*.twig',
],

The Tailwind theme in dark mode

Configuration

Every key has a working default. The full tree, with its documentation, is in Configuration.php.

# config/packages/martcode_advanced_search.yaml
martcode_advanced_search:
    prefix: mas                  # every CSS class, element id and table name starts here
    theme: '@MartCodeAdvancedSearch/themes/tailwind.html.twig'
    layout:
        columns: 4
        initially_visible: 4     # fields shown before the panel is expanded
    text:
        strategy: like           # like: one LIKE per folding variant; collation: one LIKE, the column collation matches
        folding: tr              # tr: Turkish-aware accent and case variants (seyma finds Şeyma); none: off
    tenant:
        enabled: false
        provider: ~              # service id of a TenantProviderInterface
        column: company_id
        propagate_to_joins: true
    saved_searches:
        enabled: false
        write_guard: ~           # service id of a WriteGuardInterface; without one, writes are refused

Labels and translation

The bundle has no translator dependency. The strings it prints are configuration, English by default:

martcode_advanced_search:
    labels:
        title: 'Gelişmiş Arama'
        fields: 'Arama Alanı Seçimi'
        submit: 'Ara'
        reset: 'Filtreyi Resetle'
        more: 'Daha fazla filtre'
        clear_all: 'Tümünü temizle'
        # copy, copied, save, prompt, searches, groupings, grouping,
        # nothing_yet, close, chip_clear, range_from, range_to

For full translation, override the theme blocks and call your translator there.

Multi-tenancy

With tenant.enabled, the bundle asks your TenantProviderInterface for the current tenant and adds base.<column> = :tenant to the base table and, with propagate_to_joins, to every join. If the provider returns null, the query throws TenantNotResolvedException instead of running unscoped.

A schema whose rows do not carry the configured column, such as a list of the tenant table itself, declares its own scope:

$b->from('companies', 'c')->scope(TenantScope::column('dealer_id'));
$b->from('companies', 'c')->scope(TenantScope::exclusiveTo(1));

See ADR 0003.

Saved searches

Saved searches store criteria as JSON, never SQL, so they stay portable and reviewable. To enable them:

martcode_advanced_search:
    saved_searches:
        enabled: true
        write_guard: App\Search\SavedSearchWriteGuard   # decides who may save and delete
php bin/console martcode:advanced-search:install    # creates {prefix}_saved_search, safe to rerun
# config/routes/martcode_advanced_search.yaml
martcode_advanced_search:
    resource: '@MartCodeAdvancedSearchBundle/Resources/config/routes.php'
    prefix: /admin

The endpoints refuse every write until a write guard is configured. An endpoint whose unconfigured state is "open" ships a hole into every project that installs it.

Principles

  • The bundle knows no application. Tenancy arrives through TenantProviderInterface; no superglobals, no host classes.
  • Tenant isolation fails closed. No tenant, no query.
  • Loud failure. An unknown config key or field type stops the container from compiling.
  • Criteria are stored, never SQL.
  • Every value is a bound parameter. Column references come from the schema only, never from input.
  • No inline styles, no borrowed globals. Classes and ids carry the configurable prefix; script hooks are fixed data-mcas-* attributes scoped to each panel, so two panels with two prefixes can share a page.

Development

composer install
vendor/bin/phpunit

Architecture decisions are recorded in docs/decisions. Changes are listed in the changelog. Security issues: see SECURITY.md.

License

MIT. See LICENSE.