-1

I have a view that searches for indexed entity fields using context filters. I added a custom block to the view like this:

{{ drupal_block('result_entity_product_categories', {arguments}) }}

This block displays categories that match the entered word in the search. If you enter something for which there are no search results, for example, bbbbb, I need to display something like this:

Sorry

No results for: "bbbbb"

But here are some of our most popular products

P.S. The option to add text to the No Results Behavior view setting is not suitable. It is necessary to add text in the custom block.

The build() method code of my custom block:

public function build() {

    $configuration = $this->getConfiguration();
    $term = $configuration['arguments']['0'] ?: '';

    if (empty($term)) {
      return '';
    }
    $index = $this->entityTypeManager->getStorage('search_api_index')->load('entity_product_index');
    $parse_mode = $this->parseModeManager->createInstance('terms');
    $parse_mode->setConjunction('AND');
    $search_query = $index->query();
    $search_query->setParseMode($parse_mode)
      ->keys($term);
    $search_result = $search_query->execute();

    $rows = [];
    foreach ($search_result->getResultItems() as $item) {
      if (($node = $item->getOriginalObject()->getEntity()) && ($node instanceof NodeInterface)) {
        $categoryKey = $node->get('field_entity_product_category')->getString();
        if ($categoryKey) {
          ++$rows[$categoryKey];
        }
      }
    }

    $build['container'] = [
      '#type' => 'container',
      '#attributes' => [
        'class' => ['category-counter-wrapper'],
      ],
    ];

    foreach ($rows as $key => $count) {

      if ($node = $this->entityTypeManager->getStorage('node')->load($key)) {
        $build['container'][$key] = [
          '#type' => 'container',
          '#attributes' => [
            'class' => ['item'],
          ],
          'label' => [
            '#type' => 'container',
            '#markup' => $node->getTitle(),
            '#attributes' => [
              'class' => ['label'],
            ],
          ],
          'count' => [
            '#type' => 'container',
            '#markup' => $count,
            '#attributes' => [
              'class' => ['count'],
            ],
          ],
          'link' => [
            '#type' => 'link',
            '#url' => Url::fromUserInput($node->get('field_custom_url')->getString(), ['query' => ['text' => $term]]),
            '#attributes' => [
              'class' => ['link'],
            ],
          ],

        ];
      }

    }
    return $build;
  }

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.