Symfony通过表格处理Api请求



我使用Symfony 4.4作为一个完全没有视图的restful API。我想避免像这样烦人的代码:


$email = $request->get('email');
$password = $request->get('password');
$newUser = new User();
$newUser->setEmail($email)->setPassword($password));

因为如果一个实体有很多属性,我必须花费大量时间从请求->get('property'(中获取每个变量。所以我决定尝试使用Symfony形式。

但我总是遇到这样的错误:

Expected argument of type "array", "null" given at property path "roles"."

我的用户类

<?php
namespace AppEntity;
use DateTime;
use DoctrineCommonCollectionsArrayCollection;
use DoctrineCommonCollectionsCollection;
use DoctrineORMMapping as ORM;
use SymfonyComponentSecurityCoreUserUserInterface;
use SymfonyComponentSerializerAnnotationGroups;
use SymfonyComponentValidatorConstraints as Assert;
/**
* @ORMEntity(repositoryClass="AppRepositoryUserRepository")
*/
class User implements UserInterface
{
/**
* @ORMId()
* @ORMGeneratedValue()
* @ORMColumn(type="integer")
* @Groups({"public"})
*/
private $id;
/**
* @ORMColumn(type="string", length=180, unique=true)
* @AssertEmail
* @AssertNotBlank
* @AssertNotNull
* @Groups({"public"})
*/
private $email;
/**
* @ORMColumn(type="json")
* @Groups({"public"})
*/
private $roles = [];
/**
* @var string The hashed password
* @ORMColumn(type="string")
* @AssertType("string")
* @AssertNotBlank
* @AssertNotNull
*/
private $password;
/**
* @ORMColumn(type="datetime")
* @Groups({"public"})
*/
private $createdAt;
/**
* @ORMColumn(type="datetime")
* @Groups({"public"})
*/
private $updatedAt;
/**
* @ORMOneToMany(targetEntity="AppEntityLog", mappedBy="user")
*/
private $logs;
/**
* User constructor.
*/
public function __construct()
{
$this->createdAt = new DateTime();
$this->updatedAt = new DateTime();
$this->logs = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getEmail(): ?string
{
return $this->email;
}
public function setEmail(string $email): self
{
$this->email = strtolower($email);
return $this;
}
/**
* A visual identifier that represents this user.
*
* @see UserInterface
*/
public function getUsername(): string
{
return (string) $this->email;
}
/**
* @see UserInterface
*/
public function getRoles(): array
{
$roles = $this->roles;
// guarantee every user at least has ROLE_USER
$roles[] = 'ROLE_USER';
return array_unique($roles);
}
public function setRoles(array $roles): self
{
$this->roles = $roles;
return $this;
}
/**
* @see UserInterface
*/
public function getPassword(): string
{
return (string) $this->password;
}
public function setPassword(string $password): self
{
$this->password = $password;
$this->updatedAt = new DateTime(); // updates the updatedAt field
return $this;
}
/**
* @see UserInterface
*/
public function getSalt()
{
// not needed when using the "bcrypt" algorithm in security.yaml
}
/**
* @see UserInterface
*/
public function eraseCredentials()
{
// If you store any temporary, sensitive data on the user, clear it here
// $this->plainPassword = null;
}
/**
* Get the value of createdAt
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* Set the value of createdAt
*
* @return  self
*/
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
return $this;
}
public function getUpdatedAt(): ?DateTimeInterface
{
return $this->updatedAt;
}
public function setUpdatedAt(DateTimeInterface $updatedAt): self
{
$this->updatedAt = $updatedAt;
return $this;
}
/**
* @return Collection|Log[]
*/
public function getLogs(): Collection
{
return $this->logs;
}
public function addLog(Log $log): self
{
if (!$this->logs->contains($log)) {
$this->logs[] = $log;
$log->setUser($this);
}
return $this;
}
public function removeLog(Log $log): self
{
if ($this->logs->contains($log)) {
$this->logs->removeElement($log);
// set the owning side to null (unless already changed)
if ($log->getUser() === $this) {
$log->setUser(null);
}
}
return $this;
}
}

我简单地使用makerbundle创建的表单

class UserType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options):void
{
$builder
->add('email')
->add('roles')
->add('password')
->add('createdAt')
->add('updatedAt')
;
}
public function configureOptions(OptionsResolver $resolver):void
{
$resolver->setDefaults([
'data_class' => User::class,
]);
}

还有我的控制器

public function postUsersAction(Request $request): View
{
$data = json_decode($request->getContent(), true);
$user = new User();
$form = $this->createForm(UserType::class);
$form->handleRequest($request);
$form->submit($data);
return $this->view(['message' => $form->isValid()], Response::HTTP_OK); // for testing purposes

我通过邮递员发送的数据类似于:

email=duuuu@gmail.com&password=1234

您的setRoles函数确实需要一个数组作为参数。但是,由于您不向url传递任何值,因此将角色字段或值留空,因此会提交"null"。因此,您会得到一个错误,即需要一个数组,但将null传递给了roles字段。

若要在未提供值的情况下将空数组设置为默认值,您可能需要查看表单字段的"empty_data"选项(https://symfony.com/doc/current/reference/forms/types/form.html#empty-数据(

所以在你的表格类型中,你可以做:

$builder->add('roles', null, ['empty_data' => []])

每当您提交没有角色值的表单时,它都会将角色设置为空数组。

如果您只想更新几个值(如PATCH请求中(,则submit函数接受第二个参数,该参数定义丢失的字段是用空值覆盖还是从表单中删除(https://symfony.com/doc/current/form/direct_submit.html)

调用

$form->submit($data, false);

因此,将保持对象角色的原样,并且只更新随请求传递的字段。

我找到了一个解决方案:

控制器:

$user = new User();
$form = $this->createForm(UserType::class, $user);
$form->handleRequest($request);
$form->submit($request->request->all(), false);
return $this->view(['message' => $form->isValid()], Response::HTTP_OK); // for testing purposes

我还不得不通过以下方式禁用csrf保护:

public function configureOptions(OptionsResolver $resolver):void
{
$resolver->setDefaults([
'data_class' => User::class,
'csrf_protection' => false,
]);
}

最新更新