Как запостить данные из select2 в ManyToMany одним махом?

Для запоста данных из select2 в ManyToMany одним махом в Symfony есть несколько способов. Один из таких способов - использование Doctrine ORM.

Во-первых, убедитесь, что у вас установлена и правильно настроена Doctrine ORM в вашем проекте Symfony.

Затем, создайте модель, которая будет содержать ManyToMany-отношение. Например, пусть у вас есть сущности Product и Category, и у них есть ManyToMany-связь между ними. Ваша модель может выглядеть примерно так:

// src/Entity/Product.php

use DoctrineCommonCollectionsCollection;
use DoctrineCommonCollectionsArrayCollection;
use DoctrineORMMapping as ORM;

/**
 * @ORMEntity
 * @ORMTable(name="products")
 */
class Product
{
    // ...

    /**
     * @ORMManyToMany(targetEntity="Category", inversedBy="products")
     * @ORMJoinTable(
     *     name="products_categories",
     *     joinColumns={@ORMJoinColumn(name="product_id", referencedColumnName="id")},
     *     inverseJoinColumns={@ORMJoinColumn(name="category_id", referencedColumnName="id")}
     * )
     */
    private $categories;

    public function __construct()
    {
        $this->categories = new ArrayCollection();
    }

    // ...
}
// src/Entity/Category.php

use DoctrineCommonCollectionsCollection;
use DoctrineCommonCollectionsArrayCollection;
use DoctrineORMMapping as ORM;

/**
 * @ORMEntity
 * @ORMTable(name="categories")
 */
class Category
{
    // ...

    /**
     * @ORMManyToMany(targetEntity="Product", mappedBy="categories")
     */
    private $products;

    public function __construct()
    {
        $this->products = new ArrayCollection();
    }

    // ...
}

Далее, в вашей форме создайте поле типа EntityType, которое будет использоваться для выбора категорий в select2. Например:

use AppEntityProduct;
use AppEntityCategory;
use SymfonyBridgeDoctrineFormTypeEntityType;
use SymfonyComponentFormAbstractType;
use SymfonyComponentFormFormBuilderInterface;
use SymfonyComponentOptionsResolverOptionsResolver;

class ProductFormType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            // ...
            ->add('categories', EntityType::class, [
                'class' => Category::class,
                'multiple' => true,
                'expanded' => true,
                'by_reference' => false,
            ]);
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => Product::class,
        ]);
    }
}

В вашем контроллере обработайте отправку формы и сохраните выбранные категории к продукту. Например:

use AppFormProductFormType;
use SymfonyBundleFrameworkBundleControllerAbstractController;
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentRoutingAnnotationRoute;

class ProductController extends AbstractController
{
    /**
     * @Route("/products/new", name="product_new", methods={"GET", "POST"})
     */
    public function new(Request $request): Response
    {
        $product = new Product();
        $form = $this->createForm(ProductFormType::class, $product);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $entityManager = $this->getDoctrine()->getManager();
            $entityManager->persist($product);
            $entityManager->flush();

            return $this->redirectToRoute('product_show', ['id' => $product->getId()]);
        }

        return $this->render('product/new.html.twig', [
            'form' => $form->createView(),
        ]);
    }
}

В данном примере при сохранении формы выбранные категории будут автоматически добавлены к продукту и сохранены в базу данных благодаря форме и Doctrine ORM.

Надеюсь, этот ответ помог вам разобраться, как запостить данные из select2 в ManyToMany одним махом при использовании Symfony и Doctrine ORM.