symfony 枚举对象未能转换为字符串

sczxawaw  于 2023-03-19  发布在  其他
关注(0)|答案(1)|浏览(170)

我尝试使用guide在我的实体中使用枚举。我可以将数据持久化到数据库中。但是在这一行中有错误

'booking_fees' => $bookingFeeRepository->findAll(),

错误显示为Object of class App\Enum\BookingFeeStatusEnum could not be converted to string
枚举

<?php

namespace App\Enum;

enum BookingFeeStatusEnum: string
{
    case Hold = 'HOLD';
    case Deal = 'DEAL';
}

实体

...

class BookingFee
{
    
    #[ORM\Column(type: 'string', nullable: false, enumType: BookingFeeStatusEnum::class)]
    private BookingFeeStatusEnum $status = BookingFeeStatusEnum::Hold;

...

主计长

#[Route('', name: 'app_booking_fee_index', methods: ['GET'])]
    public function index(BookingFeeRepository $bookingFeeRepository): Response
    {
        return $this->render('booking_fee/index.html.twig', [
            'booking_fees' => $bookingFeeRepository->findAll(),
        ]);
    }

表格

<?php

namespace App\Form;

use App\Entity\BookingFee;
use App\Enum\BookingFeeStatusEnum;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\EnumType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class BookingFeeType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->add('status', EnumType::class, [
                'class' => BookingFeeStatusEnum::class
            ])
            ->add('note')
            ->add('fee')
        ;
    }

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

如果我将getter更改为

public function getStatus(): string
{
    return $this->status->value;
}

public function setStatus(BookingFeeStatusEnum $status): self
{
    $this->status = $status;

    return $this;
}

那么就没有错误了。我不确定在这种情况下,在getter中返回字符串是否被认为是正确的做法。或者是我错过了什么,因为我读到了应该支持枚举的原则?或者我应该只在实体上使用字符串,而在表单上使用数据转换器?

z4bn682m

z4bn682m1#

只是想知道你为什么要这么做...

class BookingFee
{
    
    #[ORM\Column(type: 'string', nullable: false, enumType: BookingFeeStatusEnum::class)]
    private BookingFeeStatusEnum $status = BookingFeeStatusEnum::Hold;

...

而不是像这样
...

class BookingFee
{
    
    #[ORM\Column(type: 'string', nullable: false)]
    private string $status = BookingFeeStatusEnum::Hold->value;

...

我错过了什么吗?

相关问题