EC-CUBE4で商品ごとに購入年齢制限を設定する方法です。
dtb_productテーブルに年齢制限カラムを追加
dtb_productテーブルに年齢制限カラムを追加します。
サンプルコードは以下のとおりです。
<?php
namespace Customize\Entity;
use Doctrine\ORM\Mapping as ORM;
use Eccube\Annotation\EntityExtension;
/**
* dtb_productテーブルに年齢制限カラムを追加
*
* @EntityExtension("Eccube\Entity\Product")
*/
trait ProductTrait
{
/**
* @ORM\Column(type="integer", nullable=true)
*/
private $age_limit;
public function getAgeLimit(): ?int
{
return $this->age_limit;
}
public function setAgeLimit(?int $age_limit): self
{
$this->age_limit = $age_limit;
return $this;
}
}
商品登録フォームに年齢制限項目を追加
商品登録フォームに年齢制限項目を追加します。
<?php
namespace Customize\Form\Extension;
use Eccube\Form\Type\Admin\ProductType;
use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\Form\Extension\Core\Type\NumberType;
use Symfony\Component\Form\FormBuilderInterface;
/**
* 商品登録フォームに年齢制限を追加
*
* Class ProductTypeExtension
* @package Customize\Form\Extension
*/
class ProductTypeExtension extends AbstractTypeExtension
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('age_limit', NumberType::class, [
'label' => '年齢制限',
'required' => false,
'eccube_form_options' => [
'auto_render' => true
]
])
;
}
/**
* {@inheritdoc}
*/
public function getExtendedType()
{
return ProductType::class;
}
}
購入手続きで年齢チェックするバリデーションを追加
PurchaseFlowを利用して購入手続きで年齢チェックをするバリデーションを追加します。
<?php
namespace Customize\Service\PurchaceFlow\Validator;
use Eccube\Annotation\ShoppingFlow;
use Eccube\Entity\Customer;
use Eccube\Entity\ItemInterface;
use Eccube\Service\PurchaseFlow\ItemValidator;
use Eccube\Service\PurchaseFlow\PurchaseContext;
/**
* 商品毎に年齢制限チェック
*
* @ShoppingFlow()
*
* Class AgeLimitValidator
* @package Customize\Service\PurchaceFlow\Validator
*/
class AgeLimitValidator extends ItemValidator
{
/**
* @inheritDoc
*/
protected function validate(ItemInterface $item, PurchaseContext $context)
{
if(!$item->isProduct()) {
return;
}
$User = $context->getUser();
if($User instanceof Customer) {
// 誕生日が登録されている場合
if($User->getBirth()) {
// 年齢を計算
$age = floor(((new \DateTime())->format("Ymd") - $User->getBirth()->format("Ymd")) / 10000);
$ageLimit = $item->getProductClass()->getProduct()->getAgeLimit();
// 年齢制限の値と年齢を比較
if($ageLimit >= $age) {
$this->throwInvalidItemException("「%product%」は{$ageLimit}歳以上じゃないと購入できません。", $item->getProductClass());
}
}
}
}
protected function handle(ItemInterface $item, PurchaseContext $context)
{
$item->setQuantity(0);
}
}
以上で完成です。
商品に制限年齢を登録していて顧客が誕生日を登録している場合、以下のように表示されます。

