Symfony handle Api request by form

I’m using Symfony 4.4 as a restful API with no views at all. I want to avoid annoying code like this:


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

Because if one entity has a lot of properties I have to spend a lot of time getting every variable from the request->get(‘property’). So I decided to try to use Symfony forms.

But I always get this error:

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

My user class

<?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;
    }
}

The form that I’ve created simply using the 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,
        ]);
    }

And my controller

    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

The data that I’m sending through postman is something like:

[email protected]&password=1234

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *