-1

**上下文:** 我有 2 个关联实体,分别是“persona”和“ingreso”。

我试图捕获登录用户并将其作为默认变量以如下形式发送:

    TextField::new('person','Person')
        ->formatValue(function ($value) {
            return $value = $this->getUser();
        })
        ->hideOnForm() 
    

但是:这在数据库中作为 Null 值到达。

这就是为什么我尝试捕获用户并将其从实体中保存,但我不知道正确的方法

4

1 回答 1

0

您正在使用 ->hideOnForm,它会删除表单中的字段,因此不会发送任何关于person的内容。

有多种方法可以做你想做的事,包括类似的答案,比如你的用户有一个隐藏的选择,但我不认为这是一个好的解决方案。

您是否考虑过使用 Event ?

在您的情况下,您可以使用 Doctrine 事件或 EasyAdmin 事件进行监听。

Symfony 事件

<?php

namespace App\EventSubscriber;

use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityUpdatedEvent;
//... other imports

class EasyAdminSubscriber implements EventSubscriberInterface
{
    private $tokenStorage

    public function __construct(TokenStorageInterface $tokenStorage)
    {
        $this->tokenStorage = $tokenStorage
    }
    public static function getSubscribedEvents()
    {
        return [BeforeEntityUpdatedEvent => ['beforeEntityUpdatedEvent'], ];
    }

    public function beforeEntityUpdatedEvent(BeforeEntityUpdatedEvent $event)
    {
        $entity = $event->getEntityInstance();
        
        if ($entity instanceof YourEntityYouWantToListenTo) {
            $entity->setPerson($this->tokenStorage->getToken()->getUser());
        }

    }
于 2021-03-22T08:50:16.703 回答