services – Pager for custom view query plugin which displays data from external api Drupal 8

Hi I have a requirement to display the data from external api but should not be imported into any entities. What I did is I have written a custom view query plugin which displays the data from external api. What I did is I have used the GuzzleHttp Client to get the data. Here is how my service looks like


namespace Drupal***_services;

use DrupalComponentSerializationJson;

class NewsBlogsClient {

  /**
   * @var GuzzleHttpClient
   */
  protected $client;

  /**
   * NewsBlogsClient constructor.
   *
   * @param $http_client_factory DrupalCoreHttpClientFactory
   */
  public function __construct($http_client_factory) {
    $this->client = $http_client_factory->fromOptions((
      'base_uri' => 'https://****************/',
    ));
  }

  /**
   * Get all the news.
   *
   * @return array
   */
  public function getNews() {
    $response = $this->client->get('****');

    $data = Json::decode($response->getBody());

    return $data;
  }

  /**
   * Get all the blogs.
   *
   * @return array
   */
  public function getBlogs() {
    $response = $this->client->get('****');

    $data = Json::decode($response->getBody());

    return $data;
  }

}

I called the service into my plugin query and mapped it to the view fields that I have created using hook_views_data(). Here is how my plugin query looks like.

namespace Drupal****Pluginviewsquery;

use DrupalviewsViewExecutable;
use DrupalviewsResultRow;
use DrupalviewsAnnotationViewsQuery;
use DrupalCoreAnnotationTranslation;
use DrupalviewsPluginviewsqueryQueryPluginBase;
use DrupalCorePluginContainerFactoryPluginInterface;
use SymfonyComponentDependencyInjectionContainerInterface;
use DrupalCoreDatetimeDrupalDateTime;

/**
 * Views query plugin which wraps calls to the *** API in order to
 * expose the results to views.
 *
 * @ViewsQuery(
 *   id = "news",
 *   title = @Translation("News"),
 *   help = @Translation("Query against the API.")
 * )
 */
class News extends QueryPluginBase implements ContainerFactoryPluginInterface {

  /**
   * @var Drupal*****NewsBlogsClient
   */
  protected $newsBlogsClient;

  /**
   * FeaturedNews constructor.
   *
   * @param array $configuration
   * @param $plugin_id
   * @param $plugin_definition
   * @param $newsBlogsClient Drupal****NewsBlogsClient
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, $news_blogs_client) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->newsBlogsClient = $news_blogs_client;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('news_blogs_client')
    );
  }

  /**
   *
   * {@inheritdoc}
   */

  public function execute(ViewExecutable $view) {
    $index = 0;
    if ($news_items = $this->newsBlogsClient->getNews()) {
      foreach ($news_items as $news_item) {
        $row('title') = $news_item('title');
        $row('link') = $news_item('view_node');
        $date = $news_item('field_published_date');
        $dateTime = new DrupalDateTime($date);
        $timestamp = $dateTime->format('U');
        $row('pubdate') = $timestamp;
        $row('summary') = $news_item('field_short_description');
        $row('thumbnail') = $news_item('uri');
        // 'index' key is required.
        $row('index') = $index++;
        $view->result() = new ResultRow($row);
      }
    }
  }

  /**
   * Ensures a table exists in the query.
   *
   * This replicates the interface of Views' default SQL backend to simplify
   * the Views integration of the API. Since the API has no
   * concept of "tables", this method implementation does nothing. If you are
   * writing API-specific Views code, there is therefore no reason at all
   * to call this method.
   * See https://www.drupal.org/node/2484565 for more information.
   *
   * @return string
   *   An empty string.
   */
  public function ensureTable($table, $relationship = NULL) {
    return '';
  }

  /**
   * Adds a field to the table. In our case, the API has no
   * notion of limiting the fields that come back, so tracking a list
   * of fields to fetch is irrelevant for us. Hence this function body is more
   * or less empty and it serves only to satisfy handlers that may assume an
   * addField method is present b/c they were written against Views' default SQL
   * backend.
   *
   * This replicates the interface of Views' default SQL backend to simplify
   * the Views integration of the API.
   *
   * @param string $table
   *   NULL in most cases, we could probably remove this altogether.
   * @param string $field
   *   The name of the metric/dimension/field to add.
   * @param string $alias
   *   Probably could get rid of this too.
   * @param array $params
   *   Probably could get rid of this too.
   *
   * @return string
   *   The name that this field can be referred to as.
   *
   * @see DrupalviewsPluginviewsquerySql::addField()
   */
  public function addField($table, $field, $alias = '', $params = array()) {
    return $field;
  }
}

Everything is working great. I can display and control the data through views. The only missing thing is paging. The API is also from another Drupal application which supports pagination. I also need to setup a pager for this query. Tried lot of things but didn’t work. I don’t know how actually a view pager works. Can anyone explain and provide me any example snippet or code to work with.

Pager not working on products

I am using Magento 2.3.3, somehow products pager is not working on this page https://eotrace.com/UniversalOleoresins/collection
I tried to look for ajax response in chrome developer toolbar status is 200 and preview is also ok, but not reflecting/showing on the page.

Design an engaging one pager for your ico whitepaper for $10

Design an engaging one pager for your ico whitepaper

Hello sir,

A one pager as the name implies is basically a one pager summary of an ICO whitepaper.

It must therefore be concise, precise and straight to the point.

ICOs, or token sales, act as an early funding mechanism for product launches and their success is proportional to the industry interest they can generate. But landing funding and building hype is difficult when a product is at the concept stage; especially so when a field or technology is uncharted. Their teams need first to cast a vision, then fund a runway to execute on it — and they depend on the white paper to generate those dollars.

Writing your one pager with us would increase maximize your project exposure and give people who may not be able to fully read a whitepaper an idea of your project.

AN IDEAL ONE PAGER MUST CONTAIN AN EXECUTIVE SUMMARY, ABOUT US, ROAD MAP, AND THE PROJECT’S CROWDFUNDING PROCESS.

I can deliver a premium and high quality one pager. I look forward to doing business with you

order now

.

views – Pager labels aren’t translated

I have a site using Drupal 8.4.1 with all core language modules enabled, 3 active languages, and where English is the default language. The pager labels (e.g. “Last »”) for my own views aren’t translated, although the string “Last »” is available in the translation page. I can manually translate the pager labels by adding a translation for the whole view and then overriding the pager labels, but I think this isn’t the right way to do it because the built-in views (e.g. /admin/content) are translated just fine, without any manual override.

How can pager labels be translated without manually adding the translation?

8 – How to programmatically replace the view pager parameter?

I have a class method that I call when I need to get a view rendering table. I pass the required parameters like view name, display, etc.

public function getView(string $view_name, string $display, array $args = (), int $pager = NULL): ?array {
$view = Views::getView($view_name);
if (is_object($view)) {
  if (!empty($args)) {
    $view->setArguments($args);
  }
  $view->setDisplay($display);
  $view->preExecute();
  $view->execute();
  if (!is_null($pager)) {
    $view->pager->setItemsPerPage($pager);
    $view->pager->updatePageInfo();
  }
  return $view->buildRenderable($display, $args);
}

}

It works well, however, I can't change a number of items for view blocks.
I have two view blocks with the parameter "Show a specified number of items", but I cannot replace it.

Domain pager – premium domain start pages

Hi guys,

Do you own a domain? Can someone reach out to buy / offer a business opportunity? Never miss an opportunity with the Domain Pager start pages. Unlimited traffic and messages, free SSL, commission fees of 0% and more! https://domainpager.com

Any feedback / recommendation would be great. You can choose between a BIN form, an Make an offer form and a Contact form.


Marc
SEMrush

views – Sticky content item on each pager page

When I set the promotion option for a piece of content to "sticky at the top of the page" and then first sort a view of content by sticky, I get a view that show my sticky content and then all other content items according to other sort settings.

But is it possible to make a piece of content sticky at the top of each page (pager)? What I want to achieve is a piece of content that is always displayed as the first item in a view, even if the view is paginated on page = 1, page = 2, …

Thank you

7 – Delete Duplicate Records from View Result with Pager

My project is set up in Drupal 7 and I use the search API to display my custom search results. In fact, I want to display the search result based on the content of two types of content, which allows me to configure the search API for this type of content and select the fields I want to search for, then select index the content.

To display the search result, I drupal the View of Index node type.
But the problem is that in my search results, I get duplicate results because some content has the same title but a different body of text.

I want to delete search results that have a duplicate title. (Custom field created by myself)

I've tried a custom solution with View hook, but it does not work properly

function custom_views_pre_render(&$view) {
  if ($view->name == 'search_books') {
   $view_ISBN = array();
    foreach ($view->result AS $key => $res_view) {
        $ISBN = $res_view->entity->field_isbn(und)(0)('value');
       if (!in_array($ISBN,$view_ISBN)) {
                    $view_ISBN() = $ISBN;
             unset($view->result($key));
            }
    }

    $view->query->pager->total_items = count($view->result);
    $view->query->pager->update_page_info();

 } 
}

This deletes the duplicate result but gives an incorrect pagination result.

I've also tried Query query hook but that does not work for me.

function custom_query_alter($query) {

  if (isset($query->alterMetaData)) {
    if (isset($query->alterMetaData('view'))) {
      if($query->alterMetaData('view')->name == 'search_books') {
        $fields =& $query->getGroupBy();
        // Tried various fields to check which was the field creating the problem.

        $query->groupBy('field_isbn');
        $query->distinct = TRUE;

      }
    }
  }
}

I've also tried to install the module "views_distinct" and distinguish the field of view, but it also gives me a problem of pager.

An idea how to solve this problem?

Attachment pager problem

I've created a view with a block that displays articles of a content type.
Then I added an attachment that selects 4 random items to display them on the left.

The problem is that when I scroll down to block articles on the attachment changes too (as the attachment is executed after each scroll).

An idea to stop the attachment of refreshment?

Thank you

How to make a percentage pager in the views?

I need to expose a text field to users. After a user has entered a percentage and clicked the Apply button, the view will display that percentage of rows in the view's result. How to do it? Which hook should I put in place?