Drupal 9 - Inserting Taxonomy Images into nodes

126 Views Asked by At

I have a content type 'asset' witch contains a select list with a taxonomy reference 'category'

In the taxonomy 'category' I have 2 fields: 'name' and 'photo'.

Now I want to have the photo of the taxonomy also visible in form display of the asset page.

Is this possible without coding?

1

There are 1 best solutions below

0
pwoltschk On

No additional coding is needed - this can be added in a custom module using hook_form_alter().

In order to dynamically display the taxonomy image in the node edit form when a category is selected, load the selected category term using its ID from the field value. Check if the term has an image set in the field_image field. If so, get the image file URI and add an image field to display it. Set the title to the category name.

Example:

function mymodule_form_asset_node_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {

 // Get the selected category term ID from the field value.
 $category_tid = $form['field_category']['widget']['#default_value'][0]['target_id'];

 // Load the category term entity.
 $term = \Drupal\taxonomy\Entity\Term::load($category_tid);

 // Check if the term has an image.
 if (!$term->get('field_image')->isEmpty()) {
   
   // Get the image URI.
   $image_uri = $term->get('field_image')->entity->getFileUri();

   // Add the image to the form.
   $form['category_image'] = [
     '#type' => 'image',
     '#title' => $term->getName(),
     '#uri' => $image_uri,
   ];

 }

}