Problem/Motivation

In Drupal 11.1, we have shipped #3471494: Add an icon management API without a Form Element in order to test what can be done in contrib first.

We have now 2 form elements built on the Icon API in contrib, from the same module. Other modules implements the Core Icon API but they don't provide (yet) a dedicated Form Element.

icon_autocomplete

Properties:

  • #default_value: (string) Icon value as pack_id:icon_id.
  • #show_settings: (bool) Enable extractor settings, default FALSE.
  • #default_settings: (array) Settings for the extractor settings.
  • #settings_title: (string) Extractor settings details title.
  • #allowed_icon_pack: (array) Icon pack to limit the selection.
  • #return_id: (bool) Form return icon id instead of icon object as default.

Some base properties from FormElementBase:

  • #description: (string) Help or description text for the input element.
  • #placeholder: (string) Placeholder text for the input, default to 'Start typing icon name'.
  • #required: (bool) Whether or not input is required on the element.
  • #size: (int): Textfield size, default 55.

Example:

[
  '#type' => 'icon_autocomplete',
  '#title' => $this->t('Select icon'),
  '#default_value' => 'my_icon_pack:my_default_icon',
  '#allowed_icon_pack' => [
    'my_icon_pack',
    'other_icon_pack',
  ],
  '#show_settings' => TRUE,
];

icon_picker

Properties:

  • #default_value: (string) Icon value as pack_id:icon_id.
  • #show_settings: (bool) Enable extractor settings, default FALSE.
  • #default_settings: (array) Settings for the extractor settings.
  • #settings_title: (string) Extractor settings details title.
  • #allowed_icon_pack: (array) Icon pack to limit the selection.
  • #return_id: (bool) Form return icon id instead of icon object as default.

Some base properties from FormElementBase.

  • #description: (string) Help or description text for the input element.
  • #placeholder: (string) Placeholder text for the input, default to 'Click to select an Icon'.
  • #required: (bool) Whether or not input is required on the element.
  • #size: (int): Textfield size, default 55.

Global properties applied to the parent element:

  • #attributes': (array) Attributes to the global element.

Example:

[
  '#type' => 'icon_picker',
  '#title' => $this->t('Select icon'),
  '#default_value' => 'my_icon_pack:my_default_icon',
  '#allowed_icon_pack' => [
    'my_icon_pack',
    'other_icon_pack',
  ],
  '#show_settings' => TRUE,
];

Other form elements to study

They are not implementing (yet) the Icon API:

They are already implementing the Icon API but not at the Form Element level:

Proposed resolution

Add a Form Element for the icon API in Core, maybe inspired by one of those examples.

If possible, let's keep it simple, dependency free, and theme agnostic.

Also, let's notice the Form Elements may be impacted by #3508641: Define form elements from SDC the next months/years, so let's manage the callbacks in a way we can move to SDC later.

User interface changes

No, the form element is not used by default in Druapl Core. It will be available for Contrib modules (which will still be able to add their owns).

API changes

Only additions.

Issue fork drupal-3528969

Command icon Show commands

Start within a Git clone of the project using the version control instructions.

Or, if you do not have SSH keys set up on git.drupalcode.org:

Comments

pdureau created an issue. See original summary.

larowlan’s picture

pdureau’s picture

Issue summary: View changes
pdureau’s picture

Currently trying to get feedbacks from contrib module maintainers:

quietone’s picture

Version: 11.2.x-dev » 11.x-dev
mogtofu33’s picture

Added a grid view on the icon_autocomplete, it add 2 new attributes:

 * - #result_format: (string) autocomplete search format, can be 'grid' or
 *   anything else for list (Default Drupal autocomplete).
 * - #max_result: (int) search results.

Could make icon_picker obsolete for now, need discussion.

gxleano made their first commit to this issue’s fork.

gxleano’s picture

StatusFileSize
new763.33 KB
new10.92 KB

In order to test this implementation, we would need to create a new element like:

$form['icon_element'] = [
    '#type' => 'icon_autocomplete',
    '#title' => $this->t('Icon element (NEW 🎉)'),
    '#description' => $this->t('Search and select any icon from all available icon packs.'),
    '#default_value' => '',
    '#required' => FALSE,
];

Evidences:
Icon Autocomplete Form Element

Icon Autocomplete Form Element Working

gxleano’s picture

In order to have a bunch of icons to test this new implementation, I have provide the iconsets using https://www.drupal.org/project/iconify_icons 2.0.x, in this case we would just need to:

1. Enable the module
2. Go to /admin/config/iconify_icons/settings and select the iconsets which we would like to use.

It can be even tested with core iconsets, like navigation. In this case, we would just need to enable the Navigation module and it will be available to be used in the icon_autocomplete form element

pdureau’s picture

Assigned: Unassigned » mogtofu33
Status: Active » Needs review

Jean, can you have a look?

needs-review-queue-bot’s picture

Status: Needs review » Needs work
StatusFileSize
new19.86 KB

The Needs Review Queue Bot tested this issue. It fails the Drupal core commit checks. Therefore, this issue status is now "Needs work".

This does not mean that the patch necessarily needs to be re-rolled or the MR rebased. Read the Issue Summary, the issue tags and the latest discussion here to determine what needs to be done.

Consult the Drupal Contributor Guide to find step-by-step guides for working with issues.

Version: 11.x-dev » main

Drupal core is now using the main branch as the primary development branch. New developments and disruptive changes should now be targeted to the main branch.

Read more in the announcement.

pdureau’s picture

pdureau’s picture

Assigned: mogtofu33 » Unassigned

Rebased & squashed (the previous HEAD has been tagged previous/3528969-add-form-elements/2026-04-2)

Pipeline is red. David (@gxleano), you can assign to you if you want to check.

gxleano’s picture

Assigned: Unassigned » gxleano

Sure, I will try to check this during Drupal Dev Days Athens

gxleano’s picture

Assigned: gxleano » Unassigned
Status: Needs work » Needs review
larowlan’s picture

Status: Needs review » Needs work

Left some comments on the MR

gxleano’s picture

Status: Needs work » Needs review
jatingupta40’s picture

Assigned: Unassigned » jatingupta40
gxleano’s picture

Thanks to think on work on this @jatingupta40!

But seems like we are almost done on review from @larowlan

gxleano’s picture

Assigned: jatingupta40 » Unassigned
larowlan’s picture

Status: Needs review » Reviewed & tested by the community

I think this is ready now

pdureau’s picture

Assigned: Unassigned » pdureau

I think this is ready now

That's so great. I will have a last look (by testing with 2 modules already using Icon API: UI Icons & Iconify and commit to main and 11.x.)

pdureau’s picture

Assigned: pdureau » mogtofu33
Status: Reviewed & tested by the community » Needs review

Tested with the #3589768: Drupal 12 compatibility branch of UI Icons.

I did this temporary change in \Drupal\ui_icons\Element\IconAutocomplete:

 #[FormElement('icon_autocomplete')]
-class IconAutocomplete extends FormElementBase {
+class IconAutocomplete extends \Drupal\Core\Render\Element\IconAutocomplete {

But the Core icon_autocomplete form element (\Drupal\Core\Render\Element\IconAutocomplete) is always loaded instead of the contrib one anyway. At least it doesn't break.

Issue about submitted value

  • ui_icons_media: Creating or editing a media entity using the Icon media source plugin: Error message: "This value should not be null."
  • ui_icons_menu: Creating or editing a menu item: I can pick an icon, but fatal on submitting or when I display the rendered menu item: Cannot access offset of type string on string in ui_icons_menu_link_alter() (line 159 of ui_icons_menu.module).
  • ui_icons_field Creating or editing a content entity with Autocomplete widget: I can pick an icon but the value is not saved at submit
  • ui_icons_field Creating or editing a content entity with picker widget: Everything works fine (which is expected, because Core MR is not impacting this)
  • ui_icons_ckeditor5: it silently fails, the icon is not injected in the WYSIWYG area

I guess it is because the value is always submitted as 'pack_id:icon_id', but in UI Icons, it is the case only when #return_id is TRUE, but it is FALSE by default. For information, #return_id is:

  • TRUE in ui_icons_field (with icon_link_widget), ui_icons_media (in media library), ui_icons_menu (using icon_link_widget), and ui_icons_patterns
  • FALSE in ui_icons_ckeditor5, ui_icons_field (with icon_widget) and ui_icons_media (in entity form display)

Missing settings form

The icon settings form is missing from Core form element. In UI Icons, it is displayed in ui_icons_ckeditor5, ui_icons_field (with icon_link_widget if the setting is TRUE), ui_icons_patterns and ui_icons_menu.

I understand this decision, it is to keep Core form element simple and avoid the burden of generating a form from JSON schema (something we are still figuring out for SDC). So, it is the role of contrib module like UI Icons to extend the element, adding settings management.

To review

Overriding the element is fixing both the value type issue and the missing setting form:

function ui_icons_element_plugin_alter(array &$definitions) {
 $definitions['icon_autocomplete']['class'] = '\Drupal\ui_icons\Element\IconAutocomplete';
}

So UI Icons will still work after this MR is merged. That' a relief, but are we at risk of diverging from the broader Icon API ecosystem by having such divergences in our own implementation?

Jean (@mogtofu33), as both the Icon API expert and the UI Icons lead, are you OK about this MR?

Without any news late Thursday May 14th, I will put the ticket back to RTBC.

pdureau’s picture

Assigned: mogtofu33 » Unassigned
Status: Needs review » Reviewed & tested by the community
needs-review-queue-bot’s picture

Status: Reviewed & tested by the community » Needs work
StatusFileSize
new91 bytes

The Needs Review Queue Bot tested this issue. It no longer applies to Drupal core. Therefore, this issue status is now "Needs work".

This does not mean that the patch necessarily needs to be re-rolled or the MR rebased. Read the Issue Summary, the issue tags and the latest discussion here to determine what needs to be done.

Consult the Drupal Contributor Guide to find step-by-step guides for working with issues.

gxleano’s picture

Status: Needs work » Needs review
gxleano’s picture

Status: Needs review » Reviewed & tested by the community
mogtofu33’s picture

Status: Reviewed & tested by the community » Needs work

Sorry for the late reply. Some remarks on the search service, from testing the MR with UI Icons.
Ranking. doSearch() appends matches in pack order. A substring match declared before a prefix match comes first. The exact branch compares the query with the full id, so add never matches core:add as exact.
Example: 60 icons xhomex1..60 declared before home, max_result 50, home is not returned.

Drupal\ui_icons\IconSearch::doSearch() fills priority buckets instead: full id, whole words in order, whole words any order, substring in order, substring any order.

Result: best match first, independent of pack declaration order. The UI Icons data provider has 31 cases and can be ported to IconSearchTest. I can push that if ok.

Hard cap. search() applies min($max_result, 200). UI Icons picker and library pass the total icon count to paginate all matches.
The cap could live in the controller, and the service honors the argument.

Small fixes, let me know if i can commit or if they need discussion:

  • strlen($query) < 2 counts bytes. A single é or one CJK character is 2 to 4 bytes and passes the check. The JS side counts characters with minLength: 2. mb_strlen() keeps both in sync.
  • search() writes the result to cache even when it is empty, permanently, one item per distinct query. The route is anonymous, so every typo becomes a row in the icon bin. Returning early on an empty result keeps the bin to queries that match something.
  • The cache id contains the raw query: icon_search::
    :. Spaces and any user input become the key. The database backend hashes ids over 255 characters, other backends have their own limits. hash('xxh3', ...) gives a fixed length id and keeps user input out of keys.

Optional. An IconSearchInterface would let contrib swap the ranking through a service provider. Not blocking.

interface IconSearchInterface {

  public const int SEARCH_MIN_LENGTH = 2;
  public const int SEARCH_RESULT = 50;
  public const int SEARCH_RESULT_MAX = 200;

  /**
   * @return string[]
   *   Full icon ids, best match first.
   */
  public function search(string $query, array $allowed_icon_pack = [], int $max_result = self::SEARCH_RESULT): array;

}

Note: grammar and language fixes with help of LLM.

pdureau’s picture

gxleano’s picture

@mogtofu33

Thanks for the thorough review. Everything is addressed in the MR, with a few deviations noted below.

Ranking

doSearch() now scans every icon once, drops each into the first matching bucket, merges the buckets, and slices to $max_result at the end.

Two additions on top of the five buckets you listed, both from testing against icon_test:

  • Whole-word buckets look at the icon name only. Splitting the full ID made the pack ID a match word, so "home" returned home:widget ahead of every icon actually named home.
  • A "name starts with the query" bucket sits between exact and whole-word-in-order. Otherwise core:home-outline and other:my-home tied, and declaration order decided again.

So the order is:

  1. Exact ID or name
  2. Name prefix
  3. Whole words in order
  4. Whole words in any order
  5. Substring in order
  6. Substring in any order

Your 31 cases are very welcome in IconSearchTest::providerRanking(); a few expectations may shift because of the extra bucket.

Hard cap

Removed from the service, which now honors any positive $max_result. A non-positive value returns an empty array.

The controller clamps the query parameter to SEARCH_RESULT_MAX, and the constant's docblock on the interface now says exactly that: it is the bound anything exposing search to untrusted requests should apply.

Small fixes

  • mb_strlen() applied. One correction: core's autocomplete.js defaults to minLength 1 and the element does not override it, so the server check is the real guard. Setting minLength 2 on the element is a possible follow-up.
  • Empty results are no longer cached. Also, $max_result is no longer part of the cache ID. The full ranked list is cached once per query and pack set, and sliced on read, so varying max_result on the anonymous route cannot create rows either. The pack list is sorted before hashing. The trade-off is that a cache entry holds every match for that query rather than the first page.
  • Cache ID uses Crypt::hashBase64() rather than hash('xxh3'), to match AssetResolver and the cache backends.

Interface

IconSearchInterface added as sketched, with the three constants. IconSearch implements it, the controller type-hints it, and core.services.yml aliases it to icon.search.

One open question

Repeated query words ("add add") are treated as a set by the whole-word and substring "any order" buckets, but by multiplicity in the "in order" ones.

Deduplicating the query words once would make them agree. Happy to add it if you think it matters.

Note: code has been fixed with help of LLM (AI + Human in the loop).

gxleano’s picture

Status: Needs work » Needs review

mogtofu33’s picture

I pushed the UI Icons search cases to IconSearchTest.

The search cache writes one permanent row per distinct query and pack list. Measured on the anonymous route:

  • arr, Arr, ARR and aRr create four rows with the same result.
  • navigation+r1 and navigation+r2 create two rows with the same result. getIcons() ignores unknown pack ids.
  • A row holds the full match list. A two letter query on 50,000 test icons stores 33,333 ids, 1.47 MB.

I tested a normalized cache id: lowercase query, pack limit applied on read. Those variants then share one row. Word combinations still add rows: ar ro, ro ar, a r and ar ar create four.

Branch 3528969-drop-search-cache removes the result cache from IconSearch and the cache.icon bin:

  • search() scans the icons on every call. An uncached search took about 40 ms on 50,000 test icons.
  • The page cache still serves repeated anonymous requests.
  • Five cache tests are deleted.

Repeated words: add add returns add-add first.

Generated with the help of an LLM.