Taxonomy Term Exposed Filter with Image

Created on 30 January 2017, about 8 years ago
Updated 5 July 2023, over 1 year ago

I have a taxonomy terms with image field.

How can I expose terms of this taxonomy field as a filter with Term and image ?

✨ Feature request
Status

Closed: won't fix

Component

User interface

Created by

πŸ‡ΈπŸ‡ΎSyria Nightbird09x

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

  • πŸ‡¬πŸ‡§United Kingdom Dubs

    Hey - I know this is an old issue, but I had to do the same thing. Easiest way for me was to create a new better_exposed_filter plugin, and extend the existing one, e.g.

    /**
     * Default widget implementation.
     *
     * @BetterExposedFiltersFilterWidget(
     *   id = "srm_bikes_image_links",
     *   label = @Translation("SRM Image Links"),
     * )
     */
    class ImageLinks extends Links {}
    

    Then you can extend / change the exposedFormAlter function to suit, e.g.

    
          public function exposedFormAlter(array &$form, FormStateInterface $form_state) {
    
            /* Call the parent, or whatever you need to do in your use case. */
    
            foreach ($form[$field_id]['#options'] as $tid => $option) {
              if (is_numeric($tid)) {
                $term = \Drupal\taxonomy\Entity\Term::load($tid);
                if (!empty($term->get('field_image')->target_id)) {
                  try {
                    $image_uri = $term->get('field_image')->entity->field_media_image->entity->uri->value;
                    $form[$field_id]['#options'][$tid] = [
                      '#type' => 'container',
                    ];
                    $form[$field_id]['#options'][$tid]['image'] = [
                      '#theme' => 'image_style',
                      '#style_name' => 'thumbnail',
                      '#uri' => $image_uri,
                    ];
                    $form[$field_id]['#options'][$tid]['title'] = [
                      '#markup' => $option,
                    ];
                  }
                  catch (\Throwable $ex) {
                    // Do nothing - just ignore any image exceptions.
                  }
                }
              }
            }
    

    In my case I created a custom theme function too further down so we could target the rendering with a new twig file, but you don't need to do that unless required.

    You can just change the $form[$field_id]['#theme'] variable if you need to do that, and of course implement the custom theme hook in hook_theme in your module.

    I hope that helps :-)

Production build 0.71.5 2024