Symfony通过表单处理Api请求

问题描述 投票:0回答:1

我正在使用Symfony 4.4作为一个宁静的API,根本没有任何视图。我想避免像这样令人讨厌的代码:


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

因为一个实体具有很多属性,所以我不得不花费大量时间从request-> get('property')]获取每个变量。>因此,我决定尝试使用Symfony表单。

但是我总是会收到此错误:

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

我的用户类别

<?php

namespace App\Entity;

use DateTime;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Serializer\Annotation\Groups;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * @ORM\Entity(repositoryClass="App\Repository\UserRepository")
 */
class User implements UserInterface
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     * @Groups({"public"})
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=180, unique=true)
     * @Assert\Email
     * @Assert\NotBlank
     * @Assert\NotNull
     * @Groups({"public"})
     */
    private $email;

    /**
     * @ORM\Column(type="json")
     * @Groups({"public"})
     */
    private $roles = [];

    /**
     * @var string The hashed password
     * @ORM\Column(type="string")
     * @Assert\Type("string")
     * @Assert\NotBlank
     * @Assert\NotNull
     */
    private $password;

    /**
     * @ORM\Column(type="datetime")
     * @Groups({"public"})
     */
    private $createdAt;

    /**
     * @ORM\Column(type="datetime")
     * @Groups({"public"})
     */
    private $updatedAt;

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\Log", 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 protected]&password=1234

我正在使用Symfony 4.4作为一个宁静的API,根本没有任何视图。我想避免这样令人讨厌的代码:$ email = $ request-> get('email'); $ password = $ request-> get('password'); ...

php symfony http-post symfony4
1个回答
0
投票

您的setRoles函数确实希望将数组作为参数。但是,由于您没有将任何值传递给url从而使角色字段或值留空,因此会提交“ null”。因此,您会收到一个错误消息,期望使用数组,但将null传递给角色字段。

要在没有提供任何值的情况下将一个空数组设置为默认值,您可能希望查看表单字段(https://symfony.com/doc/current/reference/forms/types/form.html#empty-data)的“ empty_data”选项

© www.soinside.com 2019 - 2024. All rights reserved.