Skip to content

Instantly share code, notes, and snippets.

@mglaman
Created January 31, 2017 03:17
Show Gist options
  • Save mglaman/4edaba6c13f5b2217af0531bb00929ed to your computer and use it in GitHub Desktop.
Save mglaman/4edaba6c13f5b2217af0531bb00929ed to your computer and use it in GitHub Desktop.
Flag action link plugin which returns login link.
<?php
namespace Drupal\forkdin_core\Plugin\ActionLink;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Url;
use Drupal\flag\FlagInterface;
use Drupal\flag\Plugin\ActionLink\AJAXactionLink;
/**
* Provides the AJAX link type.
*
* This class is an extension of the Reload link type, but modified to
* provide AJAX links.
*
* @ActionLinkType(
* id = "forkdin_core_ajax_link_login",
* label = @Translation("AJAX link (login)"),
* description = "An AJAX JavaScript request will be made without reloading the page."
* )
*/
class AjaxActionLogin extends AJAXactionLink {
/**
* {@inheritdoc}
*/
public function getAsFlagLink(FlagInterface $flag, EntityInterface $entity) {
$render = parent::getAsFlagLink($flag, $entity);
$action = $this->getAction($flag, $entity);
$access = $flag->actionAccess($action, $this->currentUser, $entity);
if (!$access->isAllowed()) {
$render = [
'#type' => 'link',
'#title' => $flag->getFlagShortText(),
'#url' => Url::fromRoute('user.login', [], [
'query' => [
'destination' => $this->getUrl($action, $flag, $entity)->toString(),
]
])
];
CacheableMetadata::createFromRenderArray($render)
->addCacheableDependency($access)
->applyTo($render);
$render = [
'#markup' => \Drupal::getContainer()->get('renderer')->renderPlain($render),
];
}
return $render;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment