EC-CUBE4で年齢確認するプラグインを作る方法です。
まずは以下のコマンドでプラグインの雛形を作ります。
プラグインコードはなんでも良いのですが、今回は「VerifyAge4」にしてください。
bin/console eccube:plugin:generate
年齢確認をするためのモーダルウィンドウを表示するTwigファイルを用意
モーダルウィンドウを表示するため今回はiziModal.jpを使用します。
以下のTwigファイルをPlugin/VerifyAge4/Resource/template/default/snippet.twigに設置してください。
<div id="modal-default" data-izimodal-title="{{ modalTitle }}"> <p>{{ modalDescription }}</p> </div> <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/izimodal/1.5.1/js/iziModal.min.js"></script> <script type="text/javascript"> $("#modal-default").iziModal({ autoOpen: true, headerColor: "#26A69A", width: 400, overlayColor: "rgba(0, 0, 0, 0.5)", fullscreen: true, transitionIn: "fadeInUp", transitionOut: "fadeOutDown" }); </script>
もう一つiziModal.jp用のcssを読み込むTwigファイルをPlugin/VerifyAge4/Resource/template/default/asset.twigに設置してください。
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/izimodal/1.5.1/css/iziModal.min.css">
フロントの場合のみTwigファイルを読み込む
上記で用意したTwigファイルをフロントの場合のみ読み込むイベントを用意します。
以下の内容をEvent.phpに追記してください。
<?php namespace Plugin\VerifyAge4; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\HttpKernel\KernelEvents; use Symfony\Component\HttpKernel\Event\FilterControllerEvent; use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Eccube\Request\Context; use Eccube\Event\TemplateEvent; /** * @author Akira Kurozumi <info@a-zumi.net> */ class Event implements EventSubscriberInterface { public static function getSubscribedEvents(): array { return [ KernelEvents::CONTROLLER_ARGUMENTS => [['onKernelController', 100000000]] ]; } /** * @var \Eccube\Request\Context */ protected $requestContext; /** * @var \Symfony\Component\EventDispatcher\EventDispatcherInterface */ protected $eventDispatcher; public function __construct(Context $requestContext, EventDispatcherInterface $eventDispatcher) { $this->requestContext = $requestContext; $this->eventDispatcher = $eventDispatcher; } public function onKernelController(FilterControllerEvent $event) { // フロントページではない場合スルー if(!$this->requestContext->isFront()) { return; } if ($event->getRequest()->attributes->has('_template')) { $template = $event->getRequest()->attributes->get('_template'); $this->eventDispatcher->addListener($template->getTemplate(), function (TemplateEvent $templateEvent) { $templateEvent->addAsset('@VerifyAge4/default/asset.twig'); $templateEvent->addSnippet('@VerifyAge4/default/snippet.twig'); // snippet.twigに値を渡す // 文言を動的に操作したい場合はこのへんで調整してください $templateEvent->setParameter('modalTitle', "年齢確認"); $templateEvent->setParameter('modalDescription', "20歳以上ですか?"); }); } } }
プラグインのインストールと有効化
プラグインのインストールと有効化を行うと動作します。
ちなみに上記の実装ではページをリロードするたびにモーダルウィンドウが表示されます。
このプラグインのファイル一式はこちら。