php - Symfony 5 与 EasyAdmin Bundle | 更新具有用户相关值的实体属性
问题描述
我正在尝试使用一个字段更新我的数据库的实体,该字段应包含当前登录的用户 ID,但出现此错误:
传递给 App\Entity\Book::setIsBorrowedBy() 的参数 1 必须是 App\Entity\User 的实例或 null,int 给定
由于我是该主题的新手,因此我将不胜感激任何帮助。
工作
公共函数更新实体(...
在哪里领域
setIsBorrowedBy
应该得到当前的 UserID
非常感谢。
实体书.php
<?php
namespace App\Entity;
use App\Repository\MediaRepository;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity(repositoryClass=MediaRepository::class)
*/
class Book
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string", length=255)
*/
private $title;
/**
* @ORM\Column(type="string", length=255, nullable=true)
*/
private $coverPicture;
/**
* @ORM\Column(type="date_immutable")
*/
private $dateOfPublication;
/**
* @ORM\Column(type="string", length=255)
*/
private $description;
/**
* @ORM\Column(type="string", length=255)
*/
private $author;
/**
* @ORM\Column(type="datetime", nullable=true)
*/
private $isBorrowedAt;
/**
* @ORM\Column(type="boolean", nullable=true)
*/
private $isConfirmed = false;
/**
* @ORM\ManyToOne(targetEntity=Genre::class, inversedBy="books")
*/
private $genre;
/**
* @ORM\ManyToOne(targetEntity=User::class, inversedBy="books")
*/
private $isBorrowedBy;
/**
* @ORM\Column(type="boolean", nullable=true)
*/
private $isRequested;
public function __toString(): string
{
return $this->title;
}
public function getId(): ?int
{
return $this->id;
}
public function getTitle(): ?string
{
return $this->title;
}
public function setTitle(string $title): self
{
$this->title = $title;
return $this;
}
public function getCoverPicture(): ?string
{
return $this->coverPicture;
}
public function setCoverPicture(?string $coverPicture): self
{
$this->coverPicture = $coverPicture;
return $this;
}
public function getDateOfPublication(): ?\DateTimeImmutable
{
return $this->dateOfPublication;
}
public function setDateOfPublication(\DateTimeImmutable $dateOfPublication): self
{
$this->dateOfPublication = $dateOfPublication;
return $this;
}
public function getDescription(): ?string
{
return $this->description;
}
public function setDescription(string $description): self
{
$this->description = $description;
return $this;
}
public function getAuthor(): ?string
{
return $this->author;
}
public function setAuthor(string $author): self
{
$this->author = $author;
return $this;
}
public function getIsBorrowed(): ?bool
{
return $this->isBorrowed;
}
public function setIsBorrowed(?bool $isBorrowed): self
{
$this->isBorrowed = $isBorrowed;
return $this;
}
public function getIsBorrowedAt(): ?\DateTimeInterface
{
return $this->isBorrowedAt;
}
public function setIsBorrowedAt(?\DateTimeInterface $isBorrowedAt): self
{
$this->isBorrowedAt = $isBorrowedAt;
return $this;
}
public function getIsConfirmed(): ?bool
{
return $this->isConfirmed;
}
public function setIsConfirmed(?bool $isConfirmed): self
{
$this->isConfirmed = $isConfirmed;
return $this;
}
public function getGenre(): ?Genre
{
return $this->genre;
}
public function setGenre(?Genre $genre): self
{
$this->genre = $genre;
return $this;
}
public function getIsBorrowedBy(): ?User
{
return $this->isBorrowedBy;
}
public function setIsBorrowedBy(?User $isBorrowedBy): self
{
$this->isBorrowedBy = $isBorrowedBy;
return $this;
}
public function getIsRequested(): ?bool
{
return $this->isRequested;
}
public function setIsRequested(?bool $isRequested): self
{
$this->isRequested = $isRequested;
return $this;
}
}
实体 user.php
<?php
namespace App\Entity;
use App\Repository\UserRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* @ORM\Entity(repositoryClass=UserRepository::class)
*/
class User implements UserInterface, PasswordAuthenticatedUserInterface
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string", length=180, unique=true)
*/
private $email;
/**
* @ORM\Column(type="json")
*/
private $roles = ["ROLE_USER"];
/**
* @var string The hashed password
* @ORM\Column(type="string")
*/
private $password;
/**
* @ORM\Column(type="string", length=255)
*/
private $firstname;
/**
* @ORM\Column(type="string", length=255)
*/
private $surname;
/**
* @ORM\Column(type="date")
*/
private $birthdate;
/**
* @ORM\Column(type="string", length=255)
*/
private $adress;
/**
* @ORM\Column(type="boolean")
*/
private $isEnabled = false;
/**
* @ORM\OneToMany(targetEntity=Book::class, mappedBy="isBorrowedBy")
*/
private $books;
public function __construct()
{
$this->books = new ArrayCollection();
}
public function __toString(): string
{
return $this->email;
}
public function getId(): ?int
{
return $this->id;
}
public function getEmail(): ?string
{
return $this->email;
}
public function setEmail(string $email): self
{
$this->email = $email;
return $this;
}
/**
* A visual identifier that represents this user.
*
* @see UserInterface
*/
public function getUserIdentifier(): string
{
return (string) $this->email;
}
/**
* @deprecated since Symfony 5.3, use getUserIdentifier instead
*/
public function getUsername(): string
{
return (string) $this->email;
}
public function getRoles(): ?array
{
return $this->roles;
}
public function setRoles(array $roles): self
{
$this->roles = $roles;
return $this;
}
public function getPassword(): ?string
{
return $this->password;
}
public function setPassword(string $password): self
{
$this->password = $password;
return $this;
}
/**
* Returning a salt is only needed, if you are not using a modern
* hashing algorithm (e.g. bcrypt or sodium) in your security.yaml.
*
* @see UserInterface
*/
public function getSalt(): ?string
{
return null;
}
/**
* @see UserInterface
*/
public function eraseCredentials()
{
// If you store any temporary, sensitive data on the user, clear it here
// $this->plainPassword = null;
}
public function getFirstname(): ?string
{
return $this->firstname;
}
public function setFirstname(string $firstname): self
{
$this->firstname = $firstname;
return $this;
}
public function getSurname(): ?string
{
return $this->surname;
}
public function setSurname(string $surname): self
{
$this->surname = $surname;
return $this;
}
public function getBirthdate(): ?\DateTimeInterface
{
return $this->birthdate;
}
public function setBirthdate(\DateTimeInterface $birthdate): self
{
$this->birthdate = $birthdate;
return $this;
}
public function getAdress(): ?string
{
return $this->adress;
}
public function setAdress(string $adress): self
{
$this->adress = $adress;
return $this;
}
public function getIsEnabled(): ?bool
{
return $this->isEnabled;
}
public function setIsEnabled(bool $isEnabled): self
{
$this->isEnabled = $isEnabled;
return $this;
}
/**
* @return Collection|Book[]
*/
public function getBooks(): Collection
{
return $this->books;
}
public function addBook(Book $book): self
{
if (!$this->books->contains($book)) {
$this->books[] = $book;
$book->setIsBorrowedBy($this);
}
return $this;
}
public function removeBook(Book $book): self
{
if ($this->books->removeElement($book)) {
// set the owning side to null (unless already changed)
if ($book->getIsBorrowedBy() === $this) {
$book->setIsBorrowedBy(null);
}
}
return $this;
}
}
控制器.php
<?php
namespace App\Controller\Media;
use App\Entity\Book;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\QueryBuilder;
use EasyCorp\Bundle\EasyAdminBundle\Collection\FieldCollection;
use EasyCorp\Bundle\EasyAdminBundle\Collection\FilterCollection;
use EasyCorp\Bundle\EasyAdminBundle\Config\Action;
use EasyCorp\Bundle\EasyAdminBundle\Config\Actions;
use EasyCorp\Bundle\EasyAdminBundle\Config\Crud;
use EasyCorp\Bundle\EasyAdminBundle\Config\Filters;
use EasyCorp\Bundle\EasyAdminBundle\Controller\AbstractCrudController;
use EasyCorp\Bundle\EasyAdminBundle\Dto\EntityDto;
use EasyCorp\Bundle\EasyAdminBundle\Dto\SearchDto;
use EasyCorp\Bundle\EasyAdminBundle\Field\AssociationField;
use EasyCorp\Bundle\EasyAdminBundle\Field\BooleanField;
use EasyCorp\Bundle\EasyAdminBundle\Field\DateField;
use EasyCorp\Bundle\EasyAdminBundle\Field\TextField;
use EasyCorp\Bundle\EasyAdminBundle\Filter\EntityFilter;
use EasyCorp\Bundle\EasyAdminBundle\Orm\EntityRepository;
class MediaCrudController extends AbstractCrudController
{
public static function getEntityFqcn(): string
{
return Book::class;
}
public function configureCrud(Crud $crud): Crud
{
return $crud
->setEntityLabelInSingular('Available Mediatheque Item')
->setEntityLabelInPlural('Available Mediatheque Items')
->setSearchFields(['title', 'author', 'genre.type'])
->setDefaultSort(['dateOfPublication' => 'ASC'])
->showEntityActionsInlined();
}
public function configureFilters(Filters $filters): Filters
{
return $filters
->add(EntityFilter::new('genre')->setLabel('Genre'));
}
public function configureFields(string $pageName): iterable
{
yield TextField::new('title')->hideOnForm();
yield TextField::new('author')->hideOnForm();
yield TextField::new('coverPicture')->hideOnForm();
yield AssociationField::new('genre')->hideOnForm();
yield DateField::new('dateOfPublication')->hideOnForm();
yield BooleanField::new('isRequested')->onlyOnForms()
->setLabel('Make a Borrow Request')
->setHelp('If you want to borrow this Item, please flip the switch and save your Request');
}
public function configureActions(Actions $actions): Actions
{
return $actions
->setPermission(Action::NEW, 'ROLE_EDITOR')
->setPermission(Action::DELETE, 'ROLE_EDITOR')
->setPermission(Action::DETAIL, 'ROLE_EDITOR')
->setPermission(Action::EDIT, 'ROLE_USER')
->setPermission(Action::BATCH_DELETE, 'ROLE_EDITOR')
->update(Crud::PAGE_INDEX, Action::EDIT, function (Action $action)
{
return $action->setLabel('Borrow')->setIcon('fa fa-star');
});
}
public function createIndexQueryBuilder(SearchDto $searchDto, EntityDto $entityDto, FieldCollection $fields, FilterCollection $filters): QueryBuilder
{
$qb = $this->get(EntityRepository::class)->createQueryBuilder($searchDto, $entityDto, $fields, $filters);
$qb->andWhere('entity.isBorrowedBy IS NULL');
return $qb;
}
public function updateEntity(EntityManagerInterface $entityManager, $entityInstance): void
{
$entityInstance->setIsBorrowedAt(new \DateTime());
$entityInstance->setIsBorrowedBy($this->getUser()->getId());
parent::updateEntity($entityManager, $entityInstance);
}
}
解决方案
推荐阅读
- php - 无法使用php mysql通过数组和内爆函数将数据插入数据库
- django - Django:如何使用 APIClient 在单元测试用例中上传 csv 文件
- go - golang 的 GC 会释放仅由 goroutine 引用的对象的内存吗?
- java - 我的 Struts.xml 文件无法重定向到我的操作类并给我 404 错误
- ios - 当单元格底部可见时,UICollectionView 触发单元格动画
- android - 以编程方式创建一个带有渐变笔触的按钮?
- r - 如何从 R 中的 aov 摘要中进行子集化?
- kentico - Kentico:与 XML 数据源相关的问题,403 错误
- android-studio - 为什么 Android Studio 在运行 Flutter 应用时找不到 x86 模拟器?
- javascript - 在没有 Jquery 的情况下单击将类添加到子元素