EntityType Form SYmfony添加为实体而不是int



我来这里是因为我找不到解决问题的方法。我在Symfony 6中有一个表单,其中一个值是id_client,并指另一个实体,Client(关系ManyToOne)。

我测试了一些方法,以使字段成为所有客户端的选择(我显示客户端的名称)。它们都能工作,但提交表单时,这个值是作为整个实体添加的,而不仅仅是id。这是一个问题,因为我以这个结尾:

Expected argument of type "int", "App\Entity\Client" given at property path "id_client".

在我的表单中是这样的:

<?php
namespace AppForm;
use AppEntityClient;
use AppEntityGroup;
use AppRepositoryClientRepository;
use SymfonyBridgeDoctrineFormTypeEntityType;
use SymfonyComponentFormAbstractType;
use SymfonyComponentFormFormBuilderInterface;
use SymfonyComponentOptionsResolverOptionsResolver;
use SymfonyComponentFormExtensionCoreTypeCheckboxType;
use SymfonyComponentFormExtensionCoreTypeChoiceType;
use SymfonyComponentFormExtensionCoreTypeTextType;
class Group1Type extends AbstractType
{
private $clientRepository;
public function __construct(ClientRepository $clientRepository)
{
$this->clientRepository = $clientRepository;
$this->clients = $clientRepository->findAll();
}
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->add('name', TextType::class, [
'attr' => [
'class' => 'form-control'
],
'label' => 'Name: '
])
->add('can_display', CheckboxType::class, [
'label' => 'Can display : ',
'attr' => [
'class' => 'my-3 mx-2'
]
])
->add('id_client', EntityType::class, [
'class' => Client::class,
// 'choices' => $this->clientRepository->findAllNameAlphabetical(),
// 'query_builder' => function (ClientRepository $client) {
//     return $client->findAllNameAlphabetical();
// },
'choice_label' => 'name',
'expanded' => false,
'multiple' => false,
'attr' => [
'class' => 'form-control'
]
])
;
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'data_class' => Group::class,
]);
}
}

枝:

<section class="container my-3">
<div class="row">
<div class="col">
{{ form_start(form) }}
{{ form_row(form.name) }}
{{ form_row(form.can_display) }}
{{ form_row(form.id_client) }}
<button class="btn btn-primary my-3">{{ button_label|default('Save') }}</button>
{{ form_end(form) }}
</div>
</div>
</section>

控制器(如果我让它与开始时一样,我将得到相同的结果):

#[Route('/new', name: 'app_group_new', methods: ['GET', 'POST'])]
public function new(Request $request, GroupRepository $groupRepository): Response
{
$group = new Group();
$form = $this->createForm(Group1Type::class, $group);
$form->handleRequest($request);
// $group->id_client = $group->id_client->id;

if ($form->isSubmitted()) {
// dd('submit');
// if(gettype($group->id_client)=="Client"){
// dd($group);
if($form->isValid()){
dd('valid');
$groupRepository->save($group, true);
$this->addFlash('success', 'The creation went successfully.');
return $this->redirectToRoute('app_group_index', [], Response::HTTP_SEE_OTHER);
// }
}
}
return $this->renderForm('group/new.html.twig', [
'group' => $group,
'form' => $form,
]);
}

我的实体:

#[ORMColumn]
private ?int $id_client = null;

在您的实体中,不要使用id_*命名属性。组中的客户-属性(?)实体应该命名为$client,而不是$id_client

然后,在表单中,将该字段命名为与Group-Entity中的属性完全相同的名称。Doctrine(就像DBAL应该做的那样)通过实际id为您在幕后关联对象。

Group1Type.php

->add('client', EntityType::class, [
'class' => Client::class,
// ...
])

Group-Entity(或Group1 ?)

class Group
{
// ...
#[ORMManyToOne(targetEntity: Client::class, inversedBy: 'groups')]
#[ORMJoinColumn(nullable: false)]
private $client;
// ...
}

表单本身提交并处理所选客户端的Entity-Instance是完全正确的。您几乎从不处理$id值。这是教义的特征之一!

有关如何使用EntityType字段的更多信息,请参阅Symfony文档。


注意:从你给的命名来看,我怀疑是你有错误的关系,也许应该是OneToMany?你能告诉我们GroupClient有什么关系吗?1组是否有多个客户端?)


旁注:在极少数情况下,当你真的需要一个与实体相关的数字时(例如,在文本输入中,用户可以输入一个客户号码,然后转换为一个真实的客户实体),你可以使用DataTransformer来转换这些值。但这不是你想要的!

简单的解决方案是使用选择类型,这样你不需要关系,当你提交时,你将有客户端的id。如果加载表单进行编辑(加载实体,它将显示从提交中选择的值)

public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->add('client', ChoiceType::class, [
'choices'=> $this->getClients(),
])
}
public function getClients(){
$conn = $this->getEntityManager()->getConnection();
$query = "SELECT `name`, `id` FROM `clients` order by `name`";
$stmt = $conn->executeQuery($query);
return $stmt->fetchAllKeyValue(); 
}

它将生成一个下拉菜单,其中值是id,选项是客户端名称

相关内容

  • 没有找到相关文章

最新更新