我的工作项目中基于 Symfony 5 和 PHP 7.4 的代码
- 扩展
EasyAdminController
:
<?php
declare(strict_types=1);
namespace App\Controller;
use App\Entity\User;
use EasyCorp\Bundle\EasyAdminBundle\Controller\EasyAdminController;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
/**
* Class AdminController.
*
* @author Dmitriy Atamaniuc <d.atamaniuc@gmail.com>
*/
final class AdminController extends EasyAdminController
{
private UserPasswordEncoderInterface $encoder;
private function setUserPlainPassword(User $user): void
{
if ($user->getPlainPassword()) {
$user->setPassword($this->encoder->encodePassword($user, $user->getPlainPassword()));
}
}
/**
* @required
*/
public function setEncoder(UserPasswordEncoderInterface $encoder): void
{
$this->encoder = $encoder;
}
public function persistUserEntity(User $user): void
{
$this->setUserPlainPassword($user);
$this->persistEntity($user);
}
public function updateUserEntity(User $user): void
{
$this->setUserPlainPassword($user);
$this->updateEntity($user);
}
}
- 在 EasyAdminBundle 中注册您的控制器,编辑
config/routes/easy_admin.yaml
:
easy_admin_bundle:
resource: 'App\Controller\AdminController'
prefix: /admin
type: annotation
- 将
plainPassword
“虚拟”属性添加到您的User
实体:
/**
* @Assert\NotBlank()
* @Assert\Length(min=5, max=128)
*/
private ?string $plainPassword = null;
public function getPlainPassword(): ?string
{
return $this->plainPassword;
}
public function setPlainPassword(string $password): void
{
$this->plainPassword = $password;
}
- 更新
easy_admin.yaml
easy_admin:
entities:
User:
class: App\Entity\User
label: label.user
new:
title: field.user.add_new
fields:
# some fields like username here
- { property: username, label: field.user.username }
- { property: fullname, label: field.user.fullname, type: 'text' }
# plain password
- { property: plainPassword, label: field.user.password, type: 'password' }