Drupal 10 Help: Drupal 10 Upkeep and Help Service Constructing Views Question Plugins for 8, Half 2

Welcome to Drupal Development Company second installment of our three-part sequence on writing Views question plugins. Partly one, we talked about Drupal Development Company type of thought and design work that should happen earlier than coding begins. Partly two, we’ll begin coding our plugin and find yourself with a fundamental functioning instance. We’ve talked explicitly about needing to construct a Views question plugin to perform our objective of getting a custom-made Fitbit leaderboard, however we’ll additionally want area plugins to show that knowledge to Views, filter plugins to restrict outcomes units, and, probably, relationship plugins to span a number of API endpoints. There’s so much to do, so let’s dive in.   Getting began In 8, plugins are Drupal Development Company customary substitute for information hooks. In case you haven’t but had trigger to study Drupal Development Company plugin system in 8, I recommend Drupal Development Company Drupal 10 Help: 8 Drupal 10 Help Growth Information, which incorporates a wonderful primer on 8 plugins. Step 1 Drupal 10 Upkeep and Help Service Create a views.inc file Though most Views hooks required for Views plugins have gone Drupal Development Company means of Drupal Development Company dodo, there’s nonetheless one which survives in 8 Drupal 10 Upkeep and Help Service hook_views_data. Drupal Developer Views Drupal 10 module seems to be for that hook in a file named [Drupal 10 module].views.inc, which lives in your Drupal 10 module’s root listing. hook_views_data and hook_views_data_alter are Drupal Development Company principal belongings you’ll discover right here, however since Views is loading this file routinely for you, take benefit and put any Views-related procedural code it’s possible you’ll want on this file. Step 2 Drupal 10 Upkeep and Help Service Implement hook_views_data() Normally hook_views_data is used to explain Drupal Development Company SQL tables {that a} Drupal 10 module is making obtainable to Views. Nonetheless, in Drupal Development Company case of a question plugin it’s used to explain Drupal Development Company knowledge offered by Drupal Development Company exterior service. /** * Implements hook_views_data(). */ operate fitbit_views_example_views_data() { $knowledge = []; // Base knowledge. $knowledge[‘fitbit_profile’][‘table’][‘group’] = t(‘Fitbit profile’); $knowledge[‘fitbit_profile’][‘table’][‘base’] = [ ‘title’ => t(‘Fitbit profile’), ‘help’ => t(‘Fitbit profile data provided by the Fitbit API’s User Profile endpoint.’), ‘query_id’ => ‘fitbit’, ]; return $knowledge; } Drupal Developer format of Drupal Development Company array is often $knowledge[table_name][‘table’], however since there isn’t a desk I’ve used a brief title for Drupal Development Company Fitbit API endpoint, prefixed by Drupal Development Company Drupal 10 module title as an alternative. To date, I’ve discovered that exposing every distant endpoint as a Views “desk”—one-to-one—works nicely. It might be totally different in your implementation. This array must declare two keys—‘group’ and ‘base.’ When Views UI refers to your knowledge, it makes use of Drupal Development Company ‘group’ worth as a prefix. Whereas, Drupal Development Company ‘base’ key alerts Views that this desk is a base desk—a core piece of knowledge obtainable to assemble Views from (similar to nodes, customers and Drupal Development Company like). Drupal Developer worth of Drupal Development Company ‘base’ secret is an associative array with just a few required keys. Drupal Developer ‘title’ and ‘assist’ keys are self-explanatory and are additionally utilized in Drupal Development Company Views UI. While you create a brand new view, ‘title’ is what exhibits up in Drupal Development Company “Present” drop-down beneath “View Settings” Drupal 10 Upkeep and Help Service undefined Drupal Developer ‘query_id’ secret is Drupal Development Company most necessary. Drupal Developer worth is Drupal Development Company title of our question plugin. Extra on that later. Step 3 Drupal 10 Upkeep and Help Service Expose fields Drupal Developer knowledge you get out of a distant API isn’t going to be a lot use to individuals except they’ve fields they will show. These fields are additionally uncovered by hook_views_data. // Fields. $knowledge[‘fitbit_profile’][‘display_name’] = [ ‘title’ => t(‘Display name’), ‘help’ => t(‘Fitbit users’ display name.’), ‘field’ => [ ‘id’ => ‘standard’, ], ]; $knowledge[‘fitbit_profile’][‘average_daily_steps’] = [ ‘title’ => t(‘Average daily steps’), ‘help’ => t(‘The average daily steps over all the users logged Fitbit data.’), ‘field’ => [ ‘id’ => ‘numeric’, ], ]; $knowledge[‘fitbit_profile’][‘avatar’] = [ ‘title’ => t(‘Avatar’), ‘help’ => t(‘Fitbit users’ account picture.’), ‘field’ => [ ‘id’ => ‘fitbit_avatar’, ], ]; $knowledge[‘fitbit_profile’][‘height’] = [ ‘title’ => t(‘Height’), ‘help’ => t(‘Fibit users’s height.’), ‘field’ => [ ‘id’ => ‘numeric’, ‘float’ => TRUE, ], ]; Drupal Developer keys that make up a single area definition embody ‘title’ and ‘assist’— once more self-explanatory—utilized in Drupal Development Company Views UI. Drupal Developer ‘area’ secret is used to inform Views easy methods to deal with this area. There is just one required sub-key, ‘id,’ and it’s Drupal Development Company title of a Views area plugin.  Drupal Developer Views Drupal 10 module features a handful of area plugins, and in case your knowledge matches considered one of them, you should utilize it with out implementing your personal. Right here we use customary, which works for any plain textual content knowledge, and numeric, which works for, nicely, numeric knowledge. There are a handful of others. Have a look inside /core/Drupal 10 modules/views/src/Plugin/views/area to see all of Drupal Development Company area plugins Views offers out-of-the-box. Discover Drupal Development Company worth for ‘id’ in every area plugin’s annotation. As an apart, Views eats its personal pet food and implements a variety of its core performance as Views plugins, offering examples for if you’re implementing your Views plugins. A phrase of warning, many core Views plugins assume they’re working with an SQL-based question back-end. As such you’ll wish to watch out mixing core Views plugins in together with your customized question plugin implementation. We’ll mitigate a few of this after we implement our question plugin shortly. Step 4 Drupal 10 Upkeep and Help Service Discipline plugins Typically knowledge out of your exterior useful resource doesn’t line up with a area plugin that ships with Views core. In these instances, it’s worthwhile to implement a area plugin. For our use case, avatar is such a area. Drupal Developer API returns a URI for Drupal Development Company avatar picture. We’ll need Views to render that as an <img> tag, however Views core doesn’t provide a area plugin like that. You’ll have observed that we set a area ‘id’ of ‘fitbit_avatar’ in hook_views_data above. That’s Drupal Development Company title of our customized Views area plugin, which seems to be like this Drupal 10 Upkeep and Help Service <?php namespace fitbit_views_examplePluginviewsfield; use viewsPluginviewsfieldFieldPluginBase; use viewsResultRow; /** * Class Avatar * * @ViewsField(“fitbit_avatar”) */ class Avatar extends FieldPluginBase { /** * {@inheritdoc} */ public operate render(ResultRow $values) { $avatar = $this->getValue($values); if ($avatar) { return [ ‘#theme’ => ‘image’, ‘#uri’ => $avatar, ‘#alt’ => $this->t(‘Avatar’), ]; } } } Naming and file placement is necessary, as with every 8 plugin. Save Drupal Development Company file at Drupal 10 Upkeep and Help Service fitbit_views_example/src/Plugin/views/area/Avatar.php. Discover Drupal Development Company namespace follows Drupal Development Company file path, and likewise discover Drupal Development Company annotation Drupal 10 Upkeep and Help Service @ViewsField(“fitbit_avatar”). Drupal Developer annotation declares this class as a Views area plugin with Drupal Development Company ‘id’ ‘fitbit_avatar,’ therefore Drupal Development Company use of that title again in our hook_views_data operate. Additionally necessary, we’re extending FieldPluginBase, which provides us a variety of base performance without spending a dime. Yay OOO! As you’ll be able to see, Drupal Development Company render methodology will get Drupal Development Company worth of Drupal Development Company area from Drupal Development Company row and returns a render array in order that it seems as an <img> tag. Step 5 Drupal 10 Upkeep and Help Service Create a category that extends QueryPluginBase In any case that setup, we’re nearly able to work together with a distant API. We’ve another process Drupal 10 Upkeep and Help Service to create Drupal Development Company class for our question plugin. Once more, we’re making a 8 plugin, and naming is necessary so Drupal Development Company system is aware of that our plugin exists. We’ll create a file named Drupal 10 Upkeep and Help Service  fitbit_views_example/src/Plugin/views/question/Fitbit.php  …that appears like this Drupal 10 Upkeep and Help Service <?php namespace fitbit_views_examplePluginviewsquery; use viewsPluginviewsqueryQueryPluginBase; /** * Fitbit views question plugin which wraps calls to Drupal Development Company Fitbit API in an effort to * expose Drupal Development Company outcomes to views. * * @ViewsQuery( * id = “fitbit”, * title = @Translation(“Fitbit”), * assist = @Translation(“Question in opposition to Drupal Development Company Fitbit API.”) * ) */ class Fitbit extends QueryPluginBase { } Right here we use Drupal Development Company @ViewsQuery annotation to establish our class as a Views question plugin, declaring our ‘id’ and offering some useful meta info. We lengthen QueryPluginBase to inherit a variety of free performance. Inheritance is a recurring theme with Views plugins. I’ve but to return throughout a Views plugin kind that doesn’t ship with a base class to increase. At this level, we’ve acquired sufficient code applied to see some leads to Drupal Development Company UI. We are able to create a brand new view of kind Fitbit profile and add Drupal Development Company fields we’ve outlined and we’ll get this Drupal 10 Upkeep and Help Service undefined Not terribly thrilling, we nonetheless haven’t queried Drupal Development Company distant API, so it doesn’t really do something, nevertheless it’s good to cease right here to verify we haven’t made any syntax errors and that can discover and use Drupal Development Company plugins we’ve outlined. As I discussed, elements of Views core assume an SQL-query backend. To mitigate that, we have to implement two strategies which can, in a way, ignore core Views as a approach to work round this limitation.  Let’s get these out of Drupal Development Company means Drupal 10 Upkeep and Help Service public operate ensureTable($desk, $relationship = NULL) { return ”; } public operate addField($desk, $area, $alias = ”, $params = array()) { return $area; } ensureTable is utilized by Views core to ensure that Drupal Development Company generated SQL question accommodates Drupal Development Company acceptable JOINs to make sure that a given desk is included in Drupal Development Company outcomes. In our case, we don’t have any idea of desk joins, so we return an empty string, which satisfies plugins that will name this methodology. addField is utilized by Views core to restrict Drupal Development Company fields which might be a part of Drupal Development Company outcome set. In our case, Drupal Development Company Fitbit API has no approach to restrict Drupal Development Company fields that come again in an API response, so we don’t want this. We’ll all the time present values from Drupal Development Company outcome set, which we outlined in hook_views_data. Views takes care to solely present Drupal Development Company fields which might be chosen in Drupal Development Company Views UI. To maintain Views completely satisfied, we return $area, which is solely Drupal Development Company title of Drupal Development Company area. Earlier than we come to Drupal Development Company coronary heart of our plugin question, Drupal Development Company execute methodology, we’re going to wish a few distant providers to make this work. Drupal Developer base Fitbit Drupal 10 module handles authenticating customers, storing their entry tokens, and offering a shopper to question Drupal Development Company API. With a purpose to work our magic then, we’ll want Drupal Development Company fitbit.shopper and fitbit.access_token_manager providers offered by Drupal Development Company base Drupal 10 module. To get them, observe a well-recognized 8 sample Drupal 10 Upkeep and Help Service /** * Fitbit constructor. * * @param array $configuration * @param string $plugin_id * @param blended $plugin_definition * @param FitbitClient $fitbit_client * @param FitbitAccessTokenManager $fitbit_access_token_manager */ public operate __construct(array $configuration, $plugin_id, $plugin_definition, FitbitClient $fitbit_client, FitbitAccessTokenManager $fitbit_access_token_manager) { guardian Drupal 10 Upkeep and Help Service Drupal 10 Upkeep and Help Service__construct($configuration, $plugin_id, $plugin_definition); $this->fitbitClient = $fitbit_client; $this->fitbitAccessTokenManager = $fitbit_access_token_manager; } /** * {@inheritdoc} */ public static operate create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) { return new static( $configuration, $plugin_id, $plugin_definition, $container->get(‘fitbit.shopper’), $container->get(‘fitbit.access_token_manager’) ); } It is a widespread means of doing dependency injection in 8. We’re grabbing Drupal Development Company providers we’d like from Drupal Development Company service container in Drupal Development Company create methodology, and storing them on our question plugin occasion in Drupal Development Company constructor.  Now we’re lastly prepared for Drupal Development Company coronary heart of it, Drupal Development Company execute methodology Drupal 10 Upkeep and Help Service /** * {@inheritdoc} */ public operate execute(ViewExecutable $view) { if ($access_tokens = $this->fitbitAccessTokenManager->loadMultipleAccessToken()) { $index = 0; foreach ($access_tokens as $uid => $access_token) { if ($knowledge = $this->fitbitClient->getResourceOwner($access_token)) { $knowledge = $data->toArray(); $row[‘display_name’] = $knowledge[‘displayName’]; $row[‘average_daily_steps’] = $knowledge[‘averageDailySteps’]; $row[‘avatar’] = $knowledge[‘avatar’]; $row[‘height’] = $knowledge[‘height’]; // ‘index’ secret is required. $row[‘index’] = $index++; $view->outcome[] = new ResultRow($row); } } } } Drupal Developer execute methodology is open ended. At a minimal, you’ll wish to assign ResultRow objects to Drupal Development Company $view->outcome[] member variable. As was talked about in Drupal Development Company first a part of Drupal Development Company sequence, Drupal Development Company Fitbit API is atypical as a result of we’re hitting Drupal Development Company API as soon as per row. For every profitable request we construct up an associative array, $row, the place Drupal Development Company keys are Drupal Development Company area names we outlined in hook_views_data and Drupal Development Company values are made up of knowledge from Drupal Development Company API response. Right here we’re utilizing Drupal Development Company Fitbit shopper offered by Drupal Development Company Fitbit base Drupal 10 module to make a request to Drupal Development Company Consumer profile endpoint. This endpoint accommodates Drupal Development Company knowledge we wish for a primary iteration of our leaderboard, specifically Drupal 10 Upkeep and Help Service show title, avatar, and common every day steps. Observe that it’s necessary to trace an index for every row. Views requires it, and with out it, you’ll be scratching your head as to why Views isn’t displaying your knowledge. Lastly, we create a brand new ResultRow object with Drupal Development Company $row variable we constructed up and add it to $view->outcome. There are different issues which might be necessary to do in execute like paging, filtering and sorting. For now, this is sufficient to get us off Drupal Development Company floor. That’s it! We must always now have a easy however functioning question plugin that may work together with Drupal Development Company Fitbit API. After following Drupal Development Company set up directions for Drupal Development Company Fitbit base Drupal 10 module, connecting a number of Fitbit accounts and enabling Drupal Development Company fitbit_views_example sub-Drupal 10 module, it’s best to be capable to create a brand new View of kind Fitbit profile, add Show title, Avatar, and Common Each day Steps fields and get a rudimentary leaderboard Drupal 10 Upkeep and Help Service undefined Debugging issues If Drupal Development Company message ‘damaged or lacking handler’ seems when trying so as to add a area or different kind of handler, it often factors to a category naming downside someplace. Undergo your keys and sophistication definitions and just remember to’ve acquired all the pieces spelled appropriately. One other widespread situation is throwing errors as a result of it will probably’t discover your plugins. As with all plugin in 8, ensure your information are named appropriately, put in Drupal Development Company proper folder, with Drupal Development Company proper namespace, and with Drupal Development Company appropriate annotation. Abstract Most of Drupal Development Company work right here has nothing to do with interacting with distant providers in any respect—it’s all about declaring the place your knowledge lives and what its known as. As soon as we get previous Drupal Development Company quite a few steps which might be obligatory for outlining any Views plugins, Drupal Development Company meat of making a brand new question plugin is fairly easy. Create a category that extends QueryPluginBase Implement some empty strategies to mitigate assumptions a few SQL question backend Inject any wanted providers Override Drupal Development Company execute methodology to retrieve your knowledge right into a ResultRow object with properties named in your fields, and retailer that object on Drupal Development Company outcomes array of Drupal Development Company Views object. In actuality, most of your work shall be spent investigating Drupal Development Company API you might be interacting with and determining easy methods to mannequin Drupal Development Company knowledge to suit into Drupal Development Company array of fields that Views expects. Subsequent steps In Drupal Development Company third a part of this text, we’ll have a look at Drupal Development Company following subjects Drupal 10 Upkeep and Help Service Exposing configuration choices in your question object Including choices to area plugins Creating filter plugins Till subsequent time! Drupal 10 Growth and Help

This article was republished from its original source.
Call Us: 1(800)730-2416

Pixeldust is a 20-year-old web development agency specializing in Drupal and WordPress and working with clients all over the country. With our best in class capabilities, we work with small businesses and fortune 500 companies alike. Give us a call at 1(800)730-2416 and let’s talk about your project.

FREE Drupal SEO Audit

Test your site below to see which issues need to be fixed. We will fix them and optimize your Drupal site 100% for Google and Bing. (Allow 30-60 seconds to gather data.)

Powered by

Drupal 10 Help: Drupal 10 Upkeep and Help Service Constructing Views Question Plugins for 8, Half 2

On-Site Drupal SEO Master Setup

We make sure your site is 100% optimized (and stays that way) for the best SEO results.

With Pixeldust On-site (or On-page) SEO we make changes to your site’s structure and performance to make it easier for search engines to see and understand your site’s content. Search engines use algorithms to rank sites by degrees of relevance. Our on-site optimization ensures your site is configured to provide information in a way that meets Google and Bing standards for optimal indexing.

This service includes:

  • Pathauto install and configuration for SEO-friendly URLs.
  • Meta Tags install and configuration with dynamic tokens for meta titles and descriptions for all content types.
  • Install and fix all issues on the SEO checklist module.
  • Install and configure XML sitemap module and submit sitemaps.
  • Install and configure Google Analytics Module.
  • Install and configure Yoast.
  • Install and configure the Advanced Aggregation module to improve performance by minifying and merging CSS and JS.
  • Install and configure Schema.org Metatag.
  • Configure robots.txt.
  • Google Search Console setup snd configuration.
  • Find & Fix H1 tags.
  • Find and fix duplicate/missing meta descriptions.
  • Find and fix duplicate title tags.
  • Improve title, meta tags, and site descriptions.
  • Optimize images for better search engine optimization. Automate where possible.
  • Find and fix the missing alt and title tag for all images. Automate where possible.
  • The project takes 1 week to complete.