ECCUBE4

【EC-CUBE4】 商品名を英語のみ登録可能にする

変更方法

商品のフォーム機能を変更するには、「src/Eccube/Form/Type/Admin/ProductType.php」に対して、変更イベントを実施する必要があります。

フォームの変更イベントは、「Symfony\Component\Form\AbstractTypeExtension」クラスを継承したクラスを作成することで実行可能です。

実装

「app/Customize/Form/Extension/Admin」ディレクトリを作成しましょう。

作成したディレクトリの中に、更に「ProductTypeExtension.php」ファイルを作成しましょう。

でわ、「ProductTypeExtension.php」に追記します。

今回の実装では、既存の商品フォーム機能を書き換える形で実装します。

<?php

namespace Customize\Form\Extension\Admin;

use Eccube\Common\EccubeConfig;
use Eccube\Form\Type\Admin\ProductType;
use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Validator\Constraints as Assert;

class ProductTypeExtension extends AbstractTypeExtension
{
    /**
     * @var EccubeConfig
     */
    protected $eccubeConfig;

    /**
     * ProductTypeExtension constructor.
     *
     * @param EccubeConfig $eccubeConfig
     */
    public function __construct(
        EccubeConfig $eccubeConfig
    ) {
        $this->eccubeConfig = $eccubeConfig;
    }
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
        ->add('name', TextType::class, [
            'constraints' => [
                new Assert\NotBlank(),
                new Assert\Length(['max' => $this->eccubeConfig['eccube_stext_len']]),
                new Assert\Regex(
                    [
                        'pattern' => '/^[a-zA-Z ]+$/',
                        'message' => '英語で入力してください。'
                    ]
                ),
            ],
        ]);
}

    /**
     * {@inheritdoc}
     *
     * @return string
     */
    public function getExtendedType()
    {
        return ProductType::class;
    }
}

解説

54行目の「getExtendedType」メソッドで、既存のフォームクラスを設定し、既存の商品フォームが生成されるタイミングで呼び出すことができます。

39 – 44行目に、正規表現でのバリデーションクラスを追加します。ちなみに英語の半角の小文字、大文字、半角スペースが入力可能となります。

テスト

英語以外を入力すると、下記のようにエラーメッセージが出て登録できません。

以上です。