首页 > 解决方案 > 以表格形式显示数据库的信息以持久保存在另一个数据库中 Php-Symfony

问题描述

我有 2 个数据库默认数据库和客户数据库两次配置良好doctrine.yamlArticle我想在表单上显示来自客户数据库的表信息,以填充默认数据库的实体 Demandes 并在之后保留它。这两个实体通过外键(idArticle在 Demandes 中)链接,但如有必要,我可以取消它。

但问题是我总是有错误

给定类型为“App\Entity\Main\Article 或 null”、“App\Entity\Customer\Article 的实例”的预期参数。或其他错误,如 The class 'App\Entity\Main\Demandes' was not found in the chain configured namespaces App\Entity\Customer

我该怎么做才能理解我只想用信息文章填充实体 Demandes?

->add('idArticle', EntityType::class, [
    'class' => 'App\Entity\Customer\Article',
    'mapped' => true,
    'em' => $options['customer_entity_manager'],
    'choice_label' => 'idArticle'

])

还有我的控制器

$customerEntityManager = $this->getDoctrine()->getManager('customer');
$demande = new Demandes();
$demande->setTypeDai("Article");
$demande->setDate(new \DateTime());
$form = $this->createForm(DemandesTypeArticles::class, $demande, [
    'customer_entity_manager' => $customerEntityManager
]);
$form->handleRequest($request);
dump($demande);
if ($form->isSubmitted() && $form->isValid()) {

    $entityManager = $this->getDoctrine()->getManager('default');
    $entityManager->persist($demande);
    $entityManager->flush();
}

标签: phpformssymfonyentitymanager

解决方案


您可以使用ChoiceType::class如下代码所示:

class DemandesTypeArticles extends AbstractType {

    /**
     * @var EntityManager
     */
    private $em;

    public function __construct(EntityManagerInterface $em) {
        $this->em = $em; // Pass 'EntityManager' as Service argument.
    }

    // ...

    public function buildForm(FormBuilderInterface $builder, array $options): void {

        $articles = $this->em->getRepository(Article::Class)->findAll();

        $arctileChoices = [];
        foreach($articles as $article) {
            $label = 'Title: '.$article->getTitle().'; Id: '.$article->getId(); // Change how article choice label showed get rendert.
            $arctileChoices[$label] = $article->getId();
        }

        $builder
            // ...
            ->add('idArticle', ChoiceType::class, [
                'mapped' => true, // Is true by default.
                'choices' => $articleChoices,
            ])

        ;
    }

    // ...configureOptions and stuff
}

推荐阅读