@seo-maru  2021/07/25更新

Symfonyナレッジ


Entity

交差テーブル(中間テーブル)のアノテーション定義

https://www.doctrine-project.org/projects/doctrine-orm/en/2.9/reference/annotations-reference.html#jointable

Form

関連テーブル

外部テーブル参照するときはEntitytypeを使う

Entitytypeマニュアル

ManyToManyで複数選択のチェックボックスフォームを作る

class ShopPaymentSelectType extends AbstractType
{
    /**
     * @var PaymentRepository
     */
    protected $paymentRepository;

    public function __construct(PaymentRepository $paymentRepository)
    {
        $this->paymentRepository = $paymentRepository;
    }

    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        /** @var Shop $Shop */
        $Shop = $options["data"];

        $builder
            ->add(
                'paymentIds',
                ChoiceType::class,
                [
                    'choices' => $this->nameChoices(),
                    'expanded' => true,
                    'multiple' => true,
                    'data' => $Shop->getPaymentIds(), // デフォルト値設定
                ]
            );
    }

    private function nameChoices()
    {
        $choices = [];
        /** @var Payment $Payment */
        foreach ($this->paymentRepository->findAll() as $Payment) {
            $choices[$Payment->getMethod()] = $Payment->getId();
        }

        return $choices;
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(
            [
                'data_class' => Shop::class,
            ]
        );
    }
}
タイトルとURLをコピーしました