目前我正在Symfony 6的食谱应用程序上工作。到目前为止一切顺利。现在我想让用户能够更改他的用户名。用户名同时也是UserIdentifier。
用户名也可以修改成功。我有一个约束来设置用户名的长度。然而,具有无效值的表单无论如何都会被提交,并且用户将注销。
也许我在某个地方犯了错,但我真的很绝望。其实,这个问题很简单,但我就是找不到正确的解决办法。非常感谢你的帮助!
我的控制器'
<?php
namespace AppController;
use AppFormProfileUsernameType;
use AppRepositoryUserRepository;
use DoctrineORMEntityManagerInterface;
use SymfonyBundleFrameworkBundleControllerAbstractController;
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentRoutingAnnotationRoute;
class ProfileChangeUsernameController extends AbstractController
{
#[Route('/profile/changeUsername')]
public function changeUsername(UserRepository $userRepository, EntityManagerInterface $entityManager, Request $request)
{
$user = $this->getUser()->getUserIdentifier();
$username = $userRepository->findOneBy(['username' => $user ]);
$form = $this->createForm(ProfileUsernameType::class, $username);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$username->setUsername($form->get('username')->getData());
$entityManager->persist($username);
$entityManager->flush();
}
return $this->render('profile/changeUsername.html.twig', [
'form' => $form,
]);
}
}
<我的形式/strong>'
<?php
namespace AppForm;
use AppEntityUser;
use SymfonyComponentFormAbstractType;
use SymfonyComponentFormExtensionCoreTypeSubmitType;
use SymfonyComponentFormExtensionCoreTypeTextType;
use SymfonyComponentFormFormBuilderInterface;
use SymfonyComponentOptionsResolverOptionsResolver;
use SymfonyComponentValidatorConstraintsLength;
use SymfonyComponentValidatorConstraintsNotBlank;
class ProfileUsernameType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->add('username', TextType::class,[
'data_class' => null,
'attr' => [
'placeholder' => 'Username',
'autocomplete' => 'off',
],
'constraints' => [
new NotBlank(),
new Length(['min' => 5])],
])
->add('submit', SubmitType::class, ['label' => 'Submit your username'])
->getForm();
;
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'data_class' => User::class,
]);
}
}
My Twig file
{% extends 'base.html.twig' %}
{% form_theme form 'bootstrap_5_layout.html.twig' %}
{% block body %}
{{ form_start(form)}}
{{ form_errors(form) }}
{{ form_widget(form.username) }}
{{ form_row(form.submit) }}
{{ form_end(form) }}
{% endblock %}
我在前一段时间遇到了同样的问题,并找到了这个解决方案:在你的ProfileUsernameType.php中,这样做:
$builder
->add('username', TextType::class, [
'attr' => [
'class' => 'form-control',
'readonly' => 'readonly',
'value' =>$user['username']
],
'label' => 'Username: '
])