[英]Validation form with Symfony 3 and FOSrestBundle
I'm following a tutorial about making some REST api based on FOSrestBundle but I got stuck in a part about forms validation. 我正在跟踪有关基于FOSrestBundle制作一些REST api的教程,但是我陷入了有关表单验证的问题。
I try to add a new user in my database using a POST request at that endpoint: http://127.0.0.1:8000/users 我尝试使用该端点上的POST请求在数据库中添加新用户: http : //127.0.0.1 : 8000/users
But it only return an error about values that should not be blank. 但是它只会返回有关不应为空的值的错误。
My class UserController has this method: 我的类UserController具有此方法:
/**
* @Rest\View(statusCode=Response::HTTP_CREATED, serializerGroups={"user"})
* @Rest\Post("/users")
*/
public function postUsersAction(Request $request)
{
$user = new User();
$form = $this->createForm(UserType::class, $user, ['validation_groups'=>['Default', 'New']]);
$form->submit($request->request->all());
if ($form->isValid()) {
$encoder = $this->get('security.password_encoder');
$encoded = $encoder->encodePassword($user, $user->getPlainPassword());
$user->setPassword($encoded);
$em = $this->get('doctrine.orm.entity_manager');
$em->persist($user);
$em->flush();
return $user;
} else {
return $form;
}
}
My validation.yml: 我的validation.yml:
AppBundle\Entity\User:
constraints:
- Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity: email
properties:
firstname:
- NotBlank: ~
- Type: string
lastname:
- NotBlank: ~
- Type: string
email:
- NotBlank: ~
- Email: ~
plainPassword:
- NotBlank: { groups: [New, FullUpdate] }
- Type: string
- Length:
min: 4
max: 50
Here is my entity User: 这是我的实体用户:
/**
* @ORM\Entity()
* @ORM\Table(name="users",
* uniqueConstraints={@ORM\UniqueConstraint(name="users_email_unique",columns={"email"})}
* )
*/
class User implements UserInterface
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue
*/
protected $id;
/**
* @ORM\Column(type="string")
*/
protected $firstname;
/**
* @ORM\Column(type="string")
*/
protected $lastname;
/**
* @ORM\Column(type="string")
*/
protected $email;
/**
* @ORM\Column(type="string")
*/
protected $password;
protected $plainPassword;
public function getId()
{
return $this->id;
}
public function setId($id)
{
$this->id = $id;
}
public function getFirstname()
{
return $this->firstname;
}
public function setFirstname($firstname)
{
$this->firstname = $firstname;
}
public function getLastname()
{
return $this->lastname;
}
public function setLastname($lastname)
{
$this->lastname = $lastname;
}
public function getEmail()
{
return $this->email;
}
public function setEmail($email)
{
$this->email = $email;
}
public function getPassword()
{
return $this->password;
}
public function setPassword($password)
{
$this->password = $password;
}
public function getPlainpassword()
{
return $this->plainPassword;
}
public function getRoles()
{
return [];
}
public function getSalt()
{
return null;
}
public function getUsername()
{
return $this->email;
}
public function eraseCredentials()
{
// Suppression des données sensibles
$this->plainPassword = null;
}
}
And the part who create the form in UserType.php: 以及在UserType.php中创建表单的部分:
namespace AppBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
class UserType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('firstname');
$builder->add('lastname');
$builder->add('plainPassword');
$builder->add('email', EmailType::class);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => 'AppBundle\Entity\User',
'csrf_protection' => false,
"allow_extra_fields" => true
]);
}
}
I use Postman to send my POST request, with that payload: 我使用邮递员发送带有该有效负载的POST请求:
{
"firstname": "foo",
"lastname": "bar",
"email": "test@test.com",
"password": "qwerty"
}
But I receive an 400 error: 但是我收到一个400错误:
{
"code": 400,
"message": "Validation Failed",
"errors": {
"children": {
"firstname": [],
"lastname": [],
"plainPassword": {
"errors": [
"This value should not be blank."
]
},
"email": []
}
}
}
EDIT 1 编辑1
If I replace plainPassword by password in my validation.yml, that error will be return: 如果我在validation.yml中用密码替换plainPassword,将返回该错误:
{
"code": 400,
"message": "Validation Failed",
"errors": {
"errors": [
"This value should not be blank."
],
"children": {
"firstname": [],
"lastname": [],
"plainPassword": [],
"email": []
}
}
}
If you need to view other files tell me. 如果您需要查看其他文件,请告诉我。
Anyway, thanks for your help! 无论如何,谢谢您的帮助!
RESOLVED 解决
So @kunicmarko20 thankfully helped me, I made an error in the payload that I send with POST request, here's the correct one: 所以@ kunicmarko20幸好帮助了我,我在用POST请求发送的有效负载中出错了,这是正确的:
{
"firstname": "foo",
"lastname": "bar",
"email": "test@test.com",
"plainPassword": "qwerty"
}
And more than anything, I completely forget to put a setter in my User entity, here we go: 最重要的是,我完全忘记了在我的User实体中放置一个setter,我们开始吧:
public function getPlainPassword()
{
return $this->plainPassword;
}
public function setPlainPassword($plainpassword)
{
$this->plainPassword = $plainpassword;
}
If you are going to use $form->submit()
then the value you pass to it should be an array, and it would look like: 如果要使用
$form->submit()
那么传递给它的值应该是一个数组,它看起来像:
$data = json_decode($request->getContent(), true);
$form->submit($data);
Have exactly the same thing and it works without a problem. 具有完全相同的东西,并且可以正常工作。
Edit: 编辑:
I just took another look and you are defining plainPassword
and sending password
in your json, try like this: 我只是再
plainPassword
,您正在定义plainPassword
并在json中发送password
,请尝试如下操作:
{
"firstname": "foo",
"lastname": "bar",
"email": "test@test.com",
"plainPassword": "qwerty"
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.