Symfony EasyAdmin3:传递的参数 1 必须是 App\Entity 的实例

Symfony EasyAdmin3: Argument 1 passed must be an instance of App\Entity

我在 Symfony 上使用 easyadmin(我是初学者),我被这个问题困住了:

传递给 App\Entity\MyOrder::setCarrier() 的参数 1 必须是 App\Entity\Carrier 的实例或 null,给定的整数,在 /Users/My/Sites/test/src/Controller/Admin/MyOrderCrudController.php 中调用 (代码行:$myorder->setCarrier(2);)

我对所有有关系的字段都有这个问题。

然而,我的实体:

    /**
     * @ORM\ManyToOne(targetEntity=Delivery::class, inversedBy="myOrder")
     */
    private $delivery;
...
    public function getCarrier(): ?carrier
    {
        return $this->carrier;
    }

    public function setCarrier(?carrier $carrier): self
    {
        $this->carrier = $carrier;

        return $this;
    }
...

我的 CrudController:

 namespace App\Controller\Admin;

use App\Entity\MyOrder;
use App\Entity\Carrier;

use Doctrine\ORM\EntityManagerInterface;
use EasyCorp\Bundle\EasyAdminBundle\Config\Action;
use EasyCorp\Bundle\EasyAdminBundle\Config\Actions;
use EasyCorp\Bundle\EasyAdminBundle\Config\Crud;
use EasyCorp\Bundle\EasyAdminBundle\Context\AdminContext;
use EasyCorp\Bundle\EasyAdminBundle\Controller\AbstractCrudController;
use EasyCorp\Bundle\EasyAdminBundle\Field\ArrayField;
use EasyCorp\Bundle\EasyAdminBundle\Field\ChoiceField;
use EasyCorp\Bundle\EasyAdminBundle\Field\IdField;
use EasyCorp\Bundle\EasyAdminBundle\Field\TextField;
use EasyCorp\Bundle\EasyAdminBundle\Field\AssociationField;
use EasyCorp\Bundle\EasyAdminBundle\Router\CrudUrlGenerator;
use EasyCorp\Bundle\EasyAdminBundle\Router\AdminUrlGenerator;

class MyOrderCrudController extends AbstractCrudController
{
    private $entityManager;
    private $adminUrlGenerator;

    public function __construct(EntityManagerInterface $entityManager, AdminUrlGenerator $adminUrlGenerator)
    {
        $this->entityManager = $entityManager;
        $this->adminUrlGenerator = $adminUrlGenerator;
    }

    public static function getEntityFqcn(): string
    {
        return MyOrder::class;
    }

    public function configureCrud(Crud $crud): Crud
    {
        return $crud->setDefaultSort(['id' => 'DESC']);
    }


       public function configureActions(Actions $actions): Actions
    {
        $updateDelivery = Action::new('updateDelivery', 'Delivery up', 'fas fa-truck')->linkToCrudAction('updateDelivery');

        return $actions
            ->add('detail', $updateDelivery)
            ->add('index', 'detail');
    }

    public function updateDelivery(AdminContext $context)
    {
        $myorder = $context->getEntity()->getInstance();
        $myorder->setCarrier(2);
        $this->entityManager->flush();
        $url = $this->adminUrlGenerator->setRoute('admin', [])->generateUrl();
        return $this->redirect($url);
    }

setCarrier 只接受一个 Carrier 对象。您不能传递“2”(我想这是运营商 ID)。

试试这个:

$carrier = $this->entityManager->find(Carrier::class, 2);
$myorder->setCarrier($carrier);

PS:您的实体中有错字(class 名称的首字母大写,因此“Carrier”而不是“carrier”)