枚举对象无法转换为字符串

问题描述 投票:0回答:2

我尝试使用此指南在我的实体中使用枚举。我可以将数据保存到数据库中。但这行有错误

'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 中返回字符串是否被认为是正确的做法。或者我错过了什么,因为我读到教义应该支持 Enum?或者我应该只在实体上使用字符串并在表单上使用数据转换器?

php symfony
2个回答
0
投票

您应该通过以下任一方式在 Twig 模板中使用它:

{{ booking_fee.status.value }}
{{ booking_fee.status.name}}

或者你可以制作你的枚举实现

TranslatableInterface

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

    public function trans(TranslatorInterface $translator, ?string $locale = null): string
    {
        return match ($this) {
            self::Hold => "Hold...",
            self::Deal => "Deal ...",
        };
    }
}

最后在你的模板中:

{{ booking_fee.status|trans }}

-2
投票

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

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;


...

我错过了什么?

© www.soinside.com 2019 - 2024. All rights reserved.