使用 EntityType 显示选择时,无法从 Symfony 表单中保存实体 [英] When using EntityType to show a select, can't save entity from Symfony form

查看:23
本文介绍了使用 EntityType 显示选择时,无法从 Symfony 表单中保存实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 symfony 项目中有两个相关实体 - 它们使用 Doctrine 存储.一个实体是具有 id 和名称的广告商".另一个导致问题的实体是一个报告",它有一个自己的 id 以及一个名为advertiser_id"的字段.

在为广告商添加报告时,在 Symfony 表单中,我将 EntityType 用于广告商 ID 字段,以便我可以显示选择的广告商.这部分效果很好,但是当我尝试提交表单时,我收到一个错误,因为它正在将一个 Advertiser 对象而不是广告商的 id 传递给 adsr_id 字段.

这是我在表单构建器中的内容:

$builder->add('advertiser_id', EntityType::class, ['类' =>广告商::班级,'query_builder' =>$this->advertiserRepository->findAllNotDeletedUnpaginated(),'选择标签' =>'姓名',])->add('submit', SubmitType::class, ['标签' =>'提交',]);

当我提交表单时,出现此错误:应提供类型为整数"、App\Entity\Advertiser"的参数.

关于如何强制 symfony 仅尝试保存所选广告商的 ID 而不是传递整个广告商的任何想法?

<块引用><块引用>

更新:现在我已经对其进行了重构,以便广告商成为要报告的相关实体,我正在尝试弄清楚如何使广告商成为隐藏字段而无处可去.

我已经尝试了 iiirxs 之前提到的带有回调转换器的代码 - 将advertiser_id"更改为advertiser" - 但我对此并不走运.我一直在阅读这样的帖子 Symfony hiddenType using data_class对于实体而不是转换器,但我在获取广告商"的价值时遇到了麻烦,就像他们在该示例中获取 $options['selected_course'] 的方式一样.

当我尝试(出于测试目的)为广告商硬编码值 1,然后将其放在表单上时,表单会显示,但在提交时出现错误:

 $advertiser=1;$builder->add('advertiser', HiddenType::class,['data' => $advertiser, 'data_class' => null])

提交表单时出现的错误是:类型为App\Entity\Advertiser 或 null"的预期参数,给出字符串".

我很抱歉在这件事上打了一个死马.这似乎应该是一件很常见/容易做的事情,但我很难找到如何使它成为隐藏字段.任何想法将不胜感激!

解决方案

问题是您没有在 Report 实体中正确定义与 Advertiser 实体的关联.您应该已经定义了这样的关联:

//在 Report.php 类中/*** @ORM\ManyToOne(targetEntity="App\Entity\Advertiser")*/私人 $advertiser;

而不是定义一个包含外键 advertiser_id 的字段.Doctrine 足够聪明,可以将广告商字段自己映射到数据库上的 advertiser_id 外键,因此最好使用关联映射.您可以在文档中找到更多信息.

但是,如果您确实出于自己的原因必须仅使用整数将 advertiser_id 存储为整数,则应该使用 Symfony 的数据转换器将广告商实体转换为如下所示的整数:

$advertiserRepository = $this->advertiserRepository;$builder->get('advertiser_id')->addModelTransformer(new CallbackTransformer(函数 ($advertiserAsInteger) 使用 ($advertiserRepository) {//将整数转换为实体对象返回 $advertiserRepository->find($advertiserAsInteger);},函数($advertiserAsEntity){//将实体转换回整数返回 $advertiserAsEntity->getId();}));

在我上面的代码中,我使用 CallbackTransformer 来实现转换,但您也可以使用转换器类来实现.您还可以在数据转换器文档中找到更多相关信息.

I have two related entities in my symfony project - which are stored using Doctrine. One entity is "Advertiser" which has an id and a name. The other entity - which is causing the problem - is for a "Report" which has an id of it's own along with a field called "advertiser_id".

When adding a report for an advertiser, in the Symfony form, I'm using EntityType for the advertiser_id field so that I can display a select of advertisers. That part is working great, but when I try to submit the form, I get an error because it's passing an Advertiser object instead of the id of the advertiser to the advertiser_id field.

Here's what I have in my form's builder:

$builder
    ->add('advertiser_id', EntityType::class, [
        'class'        => Advertiser::class,
        'query_builder' => $this->advertiserRepository->findAllNotDeletedUnpaginated(),
        'choice_label' => 'name',

    ])
    ->add('submit', SubmitType::class, [
        'label' => 'Submit',
    ])
;

When I submit the form, I get this error: Expected argument of type "integer", "App\Entity\Advertiser" given.

Any idea on how I can force symfony to only try to save the id of the advertiser that was selected rather than passing the entire advertiser?

UPDATE: Now that I've refactored it so that the advertiser is a related entity to report, I'm trying to figure out how to make the advertiser a hidden field and getting nowhere.

I've tried the code the iiirxs mentioned previously with the callback transformer - changing 'advertiser_id' to 'advertiser' - but I've had no luck with that. I've been reading posts like this Symfony hiddenType using data_class for entity instead of transformer, but I'm having trouble getting the value for 'advertiser' the way they are getting $options['selected_course'] in that example.

When I try (for testing purposes) hard coding a value of 1 for advertiser, then putting this on the form, the form shows, but I get an error when submitting it:

    $advertiser=1;

    $builder
        ->add('advertiser', HiddenType::class,['data' => $advertiser, 'data_class' => null])

The error I get when submitting the form is: Expected argument of type "App\Entity\Advertiser or null", "string" given.

I'm sorry for beating a dead horse about this. This seems like it should be such a common/easy thing to do, but I'm having a hard time finding how to make it a hidden field. Any ideas would be greatly appreciated!

解决方案

The problem is that you have not defined correctly an association with Advertiser entity in your Report entity. You should have defined an association like this:

// inside Report.php class

/**
 * @ORM\ManyToOne(targetEntity="App\Entity\Advertiser")
 */
private $advertiser;

instead of defining a field that holds the foreign key advertiser_id. Doctrine is smart enough to map the advertiser field to an advertiser_id foreign key on your database on its own, so it would be better to use an association mapping. You can find more in the documentation.

However, if you indeed have to use only an integer to store the advertiser_id as an integer for your own reasons, you should use Symfony's Data Transformer to transform the advertiser entity to an integer like this:

$advertiserRepository = $this->advertiserRepository;
$builder->get('advertiser_id')
        ->addModelTransformer(new CallbackTransformer(
            function ($advertiserAsInteger) use ($advertiserRepository) {
                // transform the integer to an entity object
                return $advertiserRepository->find($advertiserAsInteger);
            },
            function ($advertiserAsEntity) {
                // transform the entity back to an integer
                return $advertiserAsEntity->getId();
            }
        ))
    ;

In my code above I used a CallbackTransformer to implement the transformation but you could also use a transformer class to do it. You can find also more about this in the data transformers documentation.

这篇关于使用 EntityType 显示选择时,无法从 Symfony 表单中保存实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆