Commit 222d0f94 authored by Gorodkov Denis's avatar Gorodkov Denis

refactor local_task

parent 5ffec161
name: Local task
description: Custom task
package: Tasks
type: module
core: 8.x
core_version_requirement: ^8 || ^9
mymodule.node.swapi:
route_name : local_task.task
title: Swapi
base_route: entity.node.canonical
local_task.task:
path: '/node/{node}/swapi'
defaults:
_controller: '\Drupal\local_task\Controller\SwapiLocalTask::exampleTabContent'
_title_callback: '\Drupal\Core\Entity\Controller\EntityController::title'
requirements:
_custom_access: '\Drupal\local_task\Controller\SwapiLocalTask::access'
<?php
namespace Drupal\local_task\Controller;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Session\AccountInterface;
use Drupal\node\NodeInterface;
class SwapiLocalTask extends ControllerBase {
public function exampleTabContent($node) {
$nid = $node;
$api = \Drupal::service('swapi.service_swapi');
$node = \Drupal::entityTypeManager()
->getStorage('node')
->load($nid);
$bundle = $node->bundle();
$swapi_id = $node->get('field_swapi_id')->getValue();
$url = 'https://swapi.dev/api/' . $bundle . '/' . $swapi_id[0]['value'];
$result = $api->setUrl($url)->getResponse();
foreach ($result as $key => $value) {
if (is_array($value)) {
$build = $build . "\"$key\"" . ": [<br>";
foreach ($value as $value2) {
$build = $build . " \"$value2\"" . ",<br>";
}
$build = $build . "],<br>";
} else {
$build = $build . "\"$key\": \"$value\",<br>";
}
}
$build = substr($build,0,-5);
return ['#markup' => $build];
}
public function access(AccountInterface $account, $node) {
$nid = $node;
$node = \Drupal::entityTypeManager()
->getStorage('node')
->load($nid);
$bundle = $node->bundle();
return AccessResult::allowedIfHasPermission($account, "edit any $bundle content");
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment