taxonomy terms – How do I set up an article view that validates both article and category?

I’m working with Drupal 7, and trying to get a view set up that will display blog categories and articles based on their category.

The category is a Taxonomy – Blog Categories – let’s assume it’s:

  • rock-and-roll
  • pop
  • jazz
  • other

I’m hoping for the following path behavior:

  1. /blog/ should list all articles.
  2. /blog/rock-and-roll/ should list articles that have the rock-and-roll taxonomy set.
  3. /blog/non-existant-term/ should show page not found
  4. /blog/rock-and-roll/real-article-title should show the relevant article
  5. /blog/rock-and-roll/fake-article-title should show page not found

I’ve tried a ton of different combinations of relationships and contextual filters, but I just can’t get it to work. The closest I can get is where all of the ‘proper’ urls work… I get category lists, or I get article displays… but I also still get a page when I go to a path with either an invalid taxonomy term or an invalid article name.

It seems like it should be something with the Contextual Filter validation stuff… but anything I’ve tried with like validation based on a taxonomy or whatever just stops anything from working. I no longer get listings or articles properly.

I’m not sure what other information to include – I’m trying to avoid adding any modules (because I’ve basically been told not to) and I’m trying to avoid making it multiple views.

——– EDIT ——–

I’ve tried some of the stuff suggested by prkos but I’m not having any more success. I’ve attached some screenshots of my configs… with a little bit of censored stuff. It probably doesn’t matter, but I’m expected to be circumspect.
The original URL/Taxonomy I used isn’t actually the final stuff, it was just example… so there might be some mismatch there.

Main view config
Relationship config
Contectual Filter config

So, with these changes in place… now if I go to url/news2/ I get a Page not found. url/news2/all seems to work, but then url/news2/validterm doesn’t work. validterm doesn’t get any results in the view preview thing either… where it did before.

How to create a block for related products based on their taxonomy term?

I want to create a block for related products.. all the solutions I found are not working on drupal 8/9 with commerce 2 , for a content you can just specify a contextual filter for (has taxonomy term) but for products that’s not an available option .. is there anyway to accomplish this ?

views – Drupal 9 Taxonomy: Parent contextual filter

I’m using drupal 9 for a project with a large taxonomy structure. On the parent page I want to show the child terms of the node. Multiple guides i’ve found have suggested using the contextual filter in a view for “Taxonomy: Parent Term” but that contextual filter doesnt seem to exist in Drupal 9.

anyone have suggestions? Thanks

8 – Entity Validation API not invoked on saving the taxonomy overview form – misunderstanding or a bug?

I have a Constraint and ContraintValidator to validate a field of taxonomy terms. Its a hierarchical taxonomy called channel with a field field_product. It’s required that a channel has the same product (term reference) set as it’s parent channel term. It’s working well on taxonomy term form, but on saving the taxonomy overview form after reorder (moving one channel to a parent with a different product set) – while xdebugging the code apparently the validation is not called at all.

Some pseudo-code:

In helper.module:

function helper_entity_bundle_field_info_alter(&$fields, EntityTypeInterface $entity_type, $bundle) {
  if (!empty($fields('field_product')) && 'taxonomy_term' === $entity_type->id() && 'channel' === $bundle) {
    $fields('field_product')->addConstraint('MatchParentChannelProduct', ());
  }
}

helper/src/Plugin/Validation/Constraint/MatchParentChannelProductConstraintValidator.php:

/**
 * Validates the MatchParentChannelProduct constraint.
 */
class MatchParentChannelProductConstraintValidator extends ConstraintValidator {

  /**
   * {@inheritdoc}
   */
  public function validate($items, Constraint $constraint) {
    // This is a single-item field so we only need to
    // validate the first item
    $product_reference = $items->first();

    if ($product_reference && $product_reference->target_id) {
      /** @var DrupaltaxonomyTermInterface $term */
      $term = $product_reference->getEntity();
      /** @var DrupaltaxonomyTermInterface $parent */
      $parent = $term->get('parent')(0)->entity ?? NULL;
      // Nothing to validate, when term has no parent it may have any product.
      if ($parent === NULL) {
        return;
      }

      $parent_tid = $parent->get('field_product')->target_id ?? NULL;
      if ( $parent_tid !== $product_reference->target_id ) {
        $parent_channel_product_name = $parent->get('field_product')->entity->name->value ?? 'unknown';
        $this->context->addViolation($constraint->productDoesNotMatchParentChannelProductMessage, ('%parent_channel_product_name' => $parent_channel_product_name));
      }
    }
  }
}

DrupaltaxonomyFormOverviewTerms::submitForm() calls $term->save(); I would have expected that this will invoke the entity validation API, but it seems that it doesn’t do that. What does it need to validate the therm entity before it is saved? Do I need to implement hook_entity_presave() and there $entity->validate() or $entity->field_product->validate();, as in Using the (Entity Validation) API? Or is there a bug somewhere?

theming – Get taxonomy field value in forum-list.html.twig

I am customizing the appearance of the forums.

I added all my forums and container. Additionally, I added a custom taxonomy field I need to show for each forum category.

screenshot

How can I show the custom taxonomy field in forum-list.html.twig?

I know how to show content fields from nodes in node.html.twig, but how do I show custom taxonomy fields in forum-list.html.twig?

theming – Drupal Forum customizing: Get Taxonomy field value in Forum overview forum-list.html.twig

i am customizing the appearance of the drupal standard forum. Drupals standard forum is based on taxonomy terms. I added all my forums and container. So far so good.

Additionally i added a custom taxonomy field and i want to show the field for each forum category. (See on attached pictures)

how can i call the custom taxonomy field in forum-list.html.twig?

I know how to call content fields from nodes in node.html.twig. for example, but how to call custom taxonomy fields in forum-list.enter image description herehtml.twig (core moduleenter image description here).

(Drupal 9.17)

I appreciate every help.

Thanks in advance!

ACF – get custom taxonomy term image field

I have loop that displays all terms from custom taxonomy. I also have image field, attached to custom taxonomy. Now, I want to display image in my page template:

<section id="sluzby" class="section--padding" style="background: #eff1f5;">
    <div class="container">
        <div class="row">

            <?php       
            $terms = get_terms( array( 'taxonomy' => 'sluzba', 'hide_empty' => false ) );
            $term_image = get_field( 'tax_image' );
                    
            foreach ( $terms as $term ) : ?>
            
                <div class="col-lg-4 col-md-6">
                    <div class="product product-zoom product--card">
                        <div class="product__thumbnail">

                            <?php //if ( $term_image ) : ?>

                                <img src="<?php echo $term_image('url'); ?>" alt="Služba <?php echo $term->name; ?>">

                            <?php //endif; ?>

                        </div>

                        <div class="product-desc">
                            <h4 class="text-center mb-2"><?php echo $term->name; ?></h4>
                        </div>
                    </div>
                </div>              
            
            <?php
            endforeach
            ?>
            
        </div>
    </div>
</section>

enter image description here

8 – Can’t get distinct rows from taxonomy view

Drupal 8 has a problem with creating distinct views, and the distinct views module hasn’t been ported yet. I’ve been researching this today, and haven’t found a good solution. I wrote a custom hook in a module that I ‘d hoped would fix it, but it hasn’t. I have s pretty simple content type that has a taxonomy reference, and this is an attachment that gathers the unique terms for an index.

The SQL generated for my view looks like this:

SELECT DISTINCT taxonomy_term_field_data_node__field_faq_category.name AS taxonomy_term_field_data_node__field_faq_category_name, node_field_data.nid AS nid, taxonomy_term_field_data_node__field_faq_category.tid AS taxonomy_term_field_data_node__field_faq_category_tid
FROM
{node_field_data} node_field_data
LEFT JOIN {node__field_faq_category} node__field_faq_category ON node_field_data.nid = node__field_faq_category.entity_id AND node__field_faq_category.deleted = '0'
LEFT JOIN {taxonomy_term_field_data} taxonomy_term_field_data_node__field_faq_category ON node__field_faq_category.field_faq_category_target_id = taxonomy_term_field_data_node__field_faq_category.tid
WHERE (node_field_data.type IN ('pfaq')) AND (node_field_data.status = '1')
ORDER BY taxonomy_term_field_data_node__field_faq_category_name ASC

I get a result of all rows. So I made this handler. It creates a copy of $view->result with only unique terms, then copies it back.

function wdocs_site_views_post_execute(ViewExecutable $view) {
  if (($view->id() =='faq') && ($view->current_display == 'attachment_1')) {
    $row_ids = ();
    $distinct_results = ();
    foreach ($view->result as $row) {
      $cat = $row->_entity->get('field_faq_category')->getValue();
      $tid = $cat(0)('target_id');
      if (!in_array($tid, $row_ids)) {
        $row_ids() = $row->taxonomy_term_field_data_node__field_faq_category_tid;
        $distinct_results() = $row;
      }
    }
    $view->result = $distinct_results;
  }
}

Seems like it should do the trick, but now I’m only seeing the first two rows. A row is generated in the HTML for each value, but after the first two rows, the span.field-content is null. Looking at the returned values in my handler, they all look like they should render. As a test, I tried adding this right before the $distinct_results array is assigned to $view->result:

$distinct_results(1) = $distinct_results(2);

Still nothing displayed. However, if I assign the value of the first row to the second row, the first two rows are displayed identically:

$distinct_results(1) = $distinct_results(0);

Seems switching the data for the rows in the result should work, this has me baffled. Any suggestions on how to deal with distinct entries would be appreciated.

theming – views.view.unformated.html.twig taxonomy conditional if/else

I am trying to get to the field_news_type term_id/label. I can print the field and I get the term label. Need guideance to be able to select which one I want to use.

{{ fields.field_news_type.content }} //prints the term 'Grid 2' which is correct.

I am trying to get either the label or term_id, so I can do a conditional. The below does not work. I have tried many variations. I have not found an answer that has produced a working result. Can someone guide me to finding the correct way to print this out in a views template page?

{% if fields.field_news_type.target_id == '2871' %}

I can use this for a node template page and it works…but not in the views twig file.

{% if content.field_research_focus_areas('#items').getValue() %}

How to add a shortcode function that returns the taxonomy slug of the actual post within the loop

Circumstances: I have a CPT called “designs” and a taxonomy related to it, called “project_category” so that I can assign a category to each design. I’m building the template for each ‘design’ and I need a shortcode that returns the assigned project category SLUG of the current design within the loop.

It’s important that I retrieve the slug instead of the ID because I’ll be using the shortcode to wrap the whole template and assign it an #ID name so I can then target it with a link.

Example: I have a design post called “New logo for Pepsi” which has “Visual Identity” as it’s project category. So I’d need the shortcode to return “visual_identity” instead of “Visual Identity”.

Facts to consider: each design will have only one category assigned, so I don’t need the shortcode to return an array, only a single slug.

I guess it should be something like this:

add_shortcode( 'return_taxonomy_slug', 'my_shortcode_return_taxonomy_slug' );

function my_shortcode_return_taxonomy_slug() {
    return get_the_terms( $designs, $project_category->slug );
}

…or maybe something like this to work-around:

add_shortcode( 'return_taxonomy_slug', 'my_shortcode_return_taxonomy_slug' );

$terms = wp_get_post_terms( get_the_ID(), 'project_category');

function my_shortcode_return_taxonomy_slug() {
    return $terms->slug;
}