ECCUBE4

FormTypeについて

EC-CUBE4ではフォーム入力はFormTypeで管理されています。

1つのページのフォーム全体をTypeというファイルを作成していく形となります。

コントローラーで、このTypeを読み出し、フォームを生成し、Viewへと渡していきます。

EC-CUBE4の管理画面で商品カテゴリを作成・編集するフォームを例にみてみましょう。

商品カテゴリのフォームはカテゴリーネームの入力フォームのみとなります。

でわ、そのフォームを生成している元となるファイルをみていきましょう

<?php

/*
 * This file is part of EC-CUBE
 *
 * Copyright(c) EC-CUBE CO.,LTD. All Rights Reserved.
 *
 * http://www.ec-cube.co.jp/
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Eccube\Form\Type\Admin;

use Eccube\Common\EccubeConfig;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints as Assert;

class CategoryType extends AbstractType
{
    /**
     * @var EccubeConfig
     */
    protected $eccubeConfig;

    /**
     * CategoryType 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'],
                    ]),
                ],
            ])
        ;
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => 'Eccube\Entity\Category',
        ]);
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return 'admin_category';
    }
}
解説

43〜55行目のbuildFormメソッドでフォームを作成します

46行目からのaddメソッドでフォームを1つづつ追加していきます、カテゴリのフォームは1つだけですが、複数ある場合はaddを連鎖させていきます。

46行目の’name’はフォームのinput name=””のnameにあたる箇所です。ここのフォームnameは基本的にデータベースのテーブルのカラム名とマッピングしている変数名です。今回であれば、Categoryエンティティに書いている$nameとなります。

46行目のTextType…はinput type=”text”を生成するクラスとなります。

47〜50行目はTextTypeのオプションを設定していて、空白NGとタイトルの長さをバリデーションしています。

60〜65行目でCategoryエンティティと関係性を持っていますと宣言します。

70〜73行目では、フォームを生成した際にinput nameの中身を’admin_category[name]’という形で生成し、postされた際にadmin_categoryという配列で取得されます。ですので、nameはadmin_category[name]で取得できます。

以上です