Smart Content and custom filters

Development
Applies to: every Sulu website As of Sulu 3.0

In short

The field smart_content needs a provider. Twig receives the entries in content and the list data in view. With max_per_page the overall limit no longer applies, so you cut the list in Twig. Custom filters are visitors with the tag sulu_content.smart_content_filters_visitor.

Smart Content is the field with which editors put together automatic lists: by tag, category, template and sort order. This chapter shows the field, the result in Twig and a custom filter that lets visitors filter by article group.

Helpful first: 5.3 Page templates: XML and Twig

The field

A smart_content field needs at least the parameter provider. The provider decides where the entries come from. Sulu ships pages, snippets, articles and articles_page_tree. The example website adds events and testimonials from its bundles. The parameter properties maps output names to the fields of the content, and max_per_page turns on pagination:

From config/templates/includes/atoms/collection/smart-articles.xml, shortened html
<property name="smart_articles" type="smart_content">
    <meta>
        <title lang="en">Filtered Articles</title>
        <title lang="de">Gefilterte Artikel</title>
    </meta>
    <params>
        <param name="provider" value="articles"/>
        <param name="max_per_page" value="12"/>
        <param name="page_parameter" value="p"/>
        <param name="properties" type="collection">
            <param name="title" value="title"/>
            <param name="url" value="url"/>
            <param name="teaser" value="teaser"/>
            <param name="tags" value="excerpt.tags"/>
            <param name="imageExcerpt" value="excerpt.image"/>
        </param>
    </params>
</property>

What Twig gets

The SmartContentPropertyResolver puts the entries into content under the field name, each entry with the names from properties. The data about the list is in view. It comes from SmartContentSmartResolver: among others page, maxPerPage, maxPage, hasNextPage, paginated, total, limit and the chosen filters (tags, categories, templateKeys, sortBys).

From templates/blocks/main/collection.html.twig html
{% set smartView = view['smart_' ~ type] ?? {} %}
{% set smartLimit = smartView.limit ?? null %}
{% if smartLimit and items|length > 0 %}
    {% set itemsBefore = ((smartView.page ?? 1) - 1) * (smartView.maxPerPage ?? 0) %}
    {% set items = items|slice(0, max(smartLimit - itemsBefore, 0)) %}
{% endif %}

Changed parameters

Three changes from UPGRADE-3.x.md affect existing templates:

  • Filtering templates (3.0.6): types and structureTypes are deprecated. For article providers the parameter is called groups, for pages and snippets templateKeys. A deprecated name makes the container build fail with a note about template and field.
  • Tags by ID (3.0.6): the tag filter stores and compares IDs instead of names. Filters stored with names no longer match.
  • Tags and categories raw (3.0.7): view.<field>.tags and .categories initially deliver only IDs. If you need names or category objects, set tagResourceLoader and categoryResourceLoader as parameters.

Writing a custom filter

A visitor changes the filters before Sulu queries the list. It implements SmartContentFiltersVisitorInterface with the method visit($data, $filters, $parameters) and returns the filters. The example website uses this so that visitors can filter an article list through the address: ?group=blog,faq shows all templates of these groups, ?template=guides-tutorial single templates.

From src/Content/Visitor/ArticleGroupFiltersVisitor.php, heavily shortened php
class ArticleGroupFiltersVisitor implements SmartContentFiltersVisitorInterface
{
    public function visit(array $data, array $filters, array $parameters): array
    {
        $request = $this->requestStack->getCurrentRequest();
        // other providers (pages, events) stay untouched
        if (null === $request || 'articles' !== ($parameters['provider'] ?? null)) {
            return $filters;
        }

        $groups = $this->parseList($request->query->getString('group', ''));
        // ... collect the templates of the groups

        $filters['templateKeys'] = [] !== $templateKeys ? $templateKeys : ['__no-match__'];

        return $filters;
    }
}

Two things stand out. For a filter without a valid template, the visitor returns a key that matches nothing instead of leaving the filters empty. Otherwise a typo in the address would show all articles. And Sulu does not detect it automatically: no compiler pass sets the tag. You register the service in config/services.yaml with the tag sulu_content.smart_content_filters_visitor. The GroupProviderInterface has no autowiring alias, so the example website passes the service @?sulu_admin.metadata_group_provider as an optional argument, because it does not have to exist in the website context.

Tags (?tags=) and categories (?categories=) can be filtered through the address without any code of your own. The SmartContentPropertyResolver reads them itself.

You rarely need a provider of your own

You write a provider of your own when the content is not in pages, articles or snippets, for example with an entity of your own. The example bundles for events and testimonials do this. The cookbook “SmartContentProvider for SmartContent” shows the structure.

More on this

Official documentation