簡體   English   中英

如何在 symfony 表單中使用當前登錄用戶?

[英]How can I use the current login user in a symfony form?

我試圖做一個使用登錄用戶填寫 EntityType 並像“作者”一樣使用它的表單

    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
    $builder
           ->add('Title')
            >add('Comment')
        ->add('Author', EntityType::class, [
        'class' => User::class,
        'choice_label' => ['name']
        ]);
    }

我試着去做,但我找不到方法

這可以根據 SubCore 提到的您的 controller 在個人操作的基礎上完成。 但是,如果您希望它始終在您堅持使用實體的任何地方自動工作,請使用事件偵聽器

這是我在 Symfony 4.4.8 項目中使用的一個,它在實體的 createdBy/editedBy 字段中設置當前用戶:

namespace App\EventListener;

use App\Application\Sonata\UserBundle\Entity\User;
use App\Entity\CMSPage;
use Doctrine\Persistence\Event\LifecycleEventArgs;
use Symfony\Component\Security\Core\Security;

class CMSPageListener
{
  private $security;

  public function __construct(Security $security)
  {
    // Avoid calling getUser() in the constructor: auth may not
    // be complete yet. Instead, store the entire Security object.
    $this->security = $security;
  }

  // the entity listener methods receive two arguments:
  // the entity instance and the lifecycle event
  public function preUpdate(CMSPage $page, LifecycleEventArgs $event)
  {
    // returns User object or null if not authenticated
    $user = $this->fetchCurrentUser($event);

    $page
      ->setEditedBy($user)
      ->setUpdatedAt(new \DateTime())
    ;
  }

  public function prePersist(CMSPage $page, LifecycleEventArgs $event)
  {
    $now = new \DateTime();
    if (null === $page->getCreatedBy()) {
      $page->setCreatedBy($this->fetchCurrentUser($event));
    }
    $page
      ->setCreatedAt($now)
      ->setUpdatedAt($now)
    ;
  }

  public function fetchCurrentUser(LifecycleEventArgs $event)
  {
    // returns User object or null if not authenticated
    $coreUser = $this->security->getUser();
    /** @var User $user */
    $user = $event->getObjectManager()->getRepository(User::class)->findOneBy([
      'username' => $coreUser->getUsername(),
    ])
    ;

    return $user;
  }
}

這是config/services.yaml

    App\EventListener\CMSPageListener:
        tags:
            -
                # these are the basic options that define the entity listener
                name: 'doctrine.orm.entity_listener'
                event: 'preUpdate'
                entity: 'App\Entity\CMSPage'

                # set the 'lazy' option to TRUE to only instantiate listeners when they are used
                lazy: true

                # you can also associate an entity listener to a specific entity manager
                #entity_manager: 'custom'

                # by default, Symfony looks for a method called after the event (e.g. postUpdate())
                # if it doesn't exist, it tries to execute the '__invoke()' method, but you can
                # configure a custom method name with the 'method' option
                #method: 'checkUserChanges'
            - { name: 'doctrine.orm.entity_listener', event: 'prePersist', entity: 'App\Entity\CMSPage', lazy: true }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM