我正在尝试为包含其某些属性的其他学说实体的教义实体创建特定的表单类型 . 在请求正文中,映射到正文密钥的值是实体的主键 . 例如:
namespace MyProject\MyBundle\Form;
class SomeFormType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
parent::buildForm($builder, $options);
$builder->add('name');
// This field in the form **does** use a primary key in the request body.
$builder->add('thisEntity',
'entity',
[
'class' => 'MyProject\MyBundle\Entity\ThisEntity',
'property' => 'id'
]
);
// This field in the form **does not** use a primary key in the request body.
$builder->add('thatEntity',
'entity',
[
'class' => 'MyProject\MyBundle\Entity\ThatEntity',
'property' => 'nonPK'
]
);
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver
->setDefaults([
'data_class' => 'Pulse\APIBundle\Entity\Project',
'csrf_protection' => false
]);
}
// ...
}
在我的测试中,我希望我的请求体的格式基于其非主键值检索实体 . 如下图所示:
<?php
namespace MyProject\MyBundle\Tests\Controller;
class SomeControllerTest extends WebTestCase
{
public function testPostRequest()
{
$client = static::createClient();
$bodyContent = [
"name" => "HelloWorld",
"thisEntity" => 1, // primary key (labeled @Id in doctrine annotation mapping)
"thatEntity" => 1234, // non primary key identifier (not labeled as @Id in doctrine annotation mapping)
];
$jsonContent = json_encode($bodyContent);
$client->request(
'POST',
'/test',
[],
[],
['CONTENT_TYPE' => 'application/json'],
$jsonContent
);
$response = $client->getResponse();
// ...
}
}
现在,在我的请求之后,我收到'thatEntity'实体的空值,而'thisEntity'将正确映射到我加载了我在请求中传递的ID的一些装置 . 那么如何将我在请求中发送的这个值映射到我想要的特定实体而不将值作为主键?我对如何实现这一点感到茫然 . 我尝试使用Symfony表单事件侦听器没有运气,因为属性映射在FormEvents :: PRE_SUBMIT和FormEvents :: SUBMIT事件之间将值转换为null . 此外,每个实体中都有正确的getter和setter,因此这不是问题所在 .
有任何想法吗?谢谢!