无法创建新用户

时间:2019-05-25 12:13:31

标签: symfony

当我尝试注册新用户时,出现此错误

  

在使用参数执行“ INSERT INTO用户(用户名,密码,电子邮件,性别,新闻,is_blocked,role_id,purchase_id)VALUES(?,?,?,?,?,?,?,?)”时发生异常[“ momo”,“ $ 2y $ 13 $ qCw4ZjU6k4s / dIwTeseEVud / zdjVu3xVper8oHAqsd / fKihq05Ga2”,“ momo@test.fr”,“ 1”,0、0,null,null]:

SQLSTATE [23000]:违反完整性约束:1048列'role_id'不能为空

先谢谢了。

这是我的用户实体:

<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\Collection;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;

/**
 * @ORM\Entity(repositoryClass="App\Repository\UserRepository")
* * @UniqueEntity(
*  fields = {"username"},
*  message = "Le nom d'utilisateur existe déjà",
* )
* @UniqueEntity(
*  fields = {"email"},
*  message = "L'email existe déjà",
* )
*/
class User implements UserInterface
{
/**
 * @ORM\Id()
 * @ORM\GeneratedValue()
 * @ORM\Column(type="integer")
 */
private $id;

/**
 * @ORM\Column(type="string", length=180, unique=true)
 */
private $username;

private $roles = [];

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

/**
 * @ORM\Column(type="string", length=180, unique=true)
 */
private $email;

/**
 * @ORM\Column(type="string", length=255)
 */
private $gender;

/**
 * @ORM\Column(type="boolean", nullable=true)
 */
private $newsletter;

/**
 * @ORM\Column(type="boolean")
 */
private $isBlocked;

/**
 * @ORM\ManyToOne(targetEntity="App\Entity\Role", inversedBy="users")
 * @ORM\JoinColumn(nullable=false)
 */
private $role;

/**
 * @ORM\ManyToMany(targetEntity="App\Entity\Article", inversedBy="users")
 */
private $article;

/**
 * @ORM\ManyToMany(targetEntity="App\Entity\Firmware", inversedBy="users")
 */
private $firmware;

/**
 * @ORM\ManyToOne(targetEntity="App\Entity\Purchase", inversedBy="users")
 */
private $purchase;

/**
 * @ORM\OneToMany(targetEntity="App\Entity\Note", mappedBy="user", 
orphanRemoval=true)
 */
private $notes;

/**
 * @ORM\OneToMany(targetEntity="App\Entity\Comment", mappedBy="user", 
orphanRemoval=true)
 */
private $comments;

public function __construct()
{
    $this->article = new ArrayCollection();
    $this->firmware = new ArrayCollection();
    $this->notes = new ArrayCollection();
    $this->comments = new ArrayCollection();
}

public function getId(): ?int
{
    return $this->id;
}

/**
 * A visual identifier that represents this user.
 *
 * @see UserInterface
 */
public function getUsername(): string
{
    return (string) $this->username;
}

public function setUsername(string $username): self
{
    $this->username = $username;

    return $this;
}

/**
 * @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;

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

public function getEmail(): ?string
{
    return $this->email;
}

public function setEmail(string $email): self
{
    $this->email = $email;

    return $this;
}

public function getGender(): ?string
{
    return $this->gender;
}

public function setGender(string $gender): self
{
    $this->gender = $gender;

    return $this;
}

public function getNewsletter(): ?bool
{
    return $this->newsletter;
}

public function setNewsletter(bool $newsletter): self
{
    $this->newsletter = $newsletter;

    return $this;
}

public function getIsBlocked(): ?bool
{
    return $this->isBlocked;
}

public function setIsBlocked(bool $isBlocked): self
{
    $this->isBlocked = $isBlocked;

    return $this;
}

public function getRole(): ?Role
{
    return $this->role;
}

public function setRole(?Role $role): self
{
    $this->role = $role;

    return $this;
}

/**
 * @return Collection|Article[]
 */
public function getArticle(): Collection
{
    return $this->article;
}

public function addArticle(Article $article): self
{
    if (!$this->article->contains($article)) {
        $this->article[] = $article;
    }

    return $this;
}

public function removeArticle(Article $article): self
{
    if ($this->article->contains($article)) {
        $this->article->removeElement($article);
    }

    return $this;
}

/**
 * @return Collection|Firmware[]
 */
public function getFirmware(): Collection
{
    return $this->firmware;
}

public function addFirmware(Firmware $firmware): self
{
    if (!$this->firmware->contains($firmware)) {
        $this->firmware[] = $firmware;
    }

    return $this;
}

public function removeFirmware(Firmware $firmware): self
{
    if ($this->firmware->contains($firmware)) {
        $this->firmware->removeElement($firmware);
    }

    return $this;
}

public function getPurchase(): ?Purchase
{
    return $this->purchase;
}

public function setPurchase(?Purchase $purchase): self
{
    $this->purchase = $purchase;

    return $this;
}

/**
 * @return Collection|Note[]
 */
public function getNotes(): Collection
{
    return $this->notes;
}

public function addNote(Note $note): self
{
    if (!$this->notes->contains($note)) {
        $this->notes[] = $note;
        $note->setUser($this);
    }

    return $this;
}

public function removeNote(Note $note): self
{
    if ($this->notes->contains($note)) {
        $this->notes->removeElement($note);
        // set the owning side to null (unless already changed)
        if ($note->getUser() === $this) {
            $note->setUser(null);
        }
    }

    return $this;
}

/**
 * @return Collection|Comment[]
 */
public function getComments(): Collection
{
    return $this->comments;
}

public function addComment(Comment $comment): self
{
    if (!$this->comments->contains($comment)) {
        $this->comments[] = $comment;
        $comment->setUser($this);
    }

    return $this;
}

public function removeComment(Comment $comment): self
{
    if ($this->comments->contains($comment)) {
        $this->comments->removeElement($comment);
        // set the owning side to null (unless already changed)
        if ($comment->getUser() === $this) {
            $comment->setUser(null);
        }
    }

    return $this;
}
}

角色实体

<?php

namespace App\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;

/**
  * @ORM\Entity(repositoryClass="App\Repository\RoleRepository")
  */
class Role
{
/**
 * @ORM\Id()
 * @ORM\GeneratedValue()
 * @ORM\Column(type="integer")
 */
private $id;

/**
 * @ORM\Column(type="string", length=255)
 */
private $name;

/**
 * @ORM\Column(type="string", length=255)
 */
private $description;

/**
 * @ORM\OneToMany(targetEntity="App\Entity\User", mappedBy="role")
 */
private $users;

public function __construct()
{
    $this->users = new ArrayCollection();
}

public function getId(): ?int
{
    return $this->id;
}

public function getName(): ?string
{
    return $this->name;
}

public function setName(string $name): self
{
    $this->name = $name;

    return $this;
}

public function getDescription(): ?string
{
    return $this->description;
}

public function setDescription(string $description): self
{
    $this->description = $description;

    return $this;
}

/**
 * @return Collection|User[]
 */
public function getUsers(): Collection
{
    return $this->users;
}

public function addUser(User $user): self
{
    if (!$this->users->contains($user)) {
        $this->users[] = $user;
        $user->setRole($this);
    }

    return $this;
}

public function removeUser(User $user): self
{
    if ($this->users->contains($user)) {
        $this->users->removeElement($user);
        // set the owning side to null (unless already changed)
        if ($user->getRole() === $this) {
            $user->setRole(null);
        }
    }

    return $this;
}

public function __toString()
{
    return $this->name;
}
}

UserType

<?php

namespace App\Form;

use App\Entity\User;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\RepeatedType;

class UserType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array 
$options)
    {
    $builder
        ->add('username', TextType::class, [
            'empty_data' => '',
            ])
        ->add('password', RepeatedType::class, [
            'type' => PasswordType::class,
            'empty_data' => '',
            'invalid_message' => 'Valeur no correcte',
            'options' => ['attr' => ['class' => 'password-field']],
            'required' => true,
            'first_options'  => ['label' => 'Password','empty_data' => 
         ''],
            'second_options' => ['label' => 'Repeat Password','empty_data' 
                  => ''],
        ])
        ->add('email',EmailType::class, [
            'empty_data' => '', 
        ])
        ->add('gender', ChoiceType::class, [
            'help' => 'Un choix possible',
            'choices' => [
            'Femme' => true,
            'Homme' => true,
            'Autre' => true,
            ],
        ])
        ->add('newsletter')




    ;
}

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

SecutityController

<?php

namespace App\Controller;

use App\Entity\User;
use App\Form\UserType;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;

class SecurityController extends AbstractController
{
/**
 * @Route("/login", name="app_login")
 */
public function login(AuthenticationUtils $authenticationUtils): Response
{
    // get the login error if there is one
    $error = $authenticationUtils->getLastAuthenticationError();
    // last username entered by the user
    $lastUsername = $authenticationUtils->getLastUsername();

    return $this->render('security/login.html.twig', ['last_username' => 
$lastUsername, 'error' => $error]);
}

 /**
 * @Route("/inscription", name="registration")
 */
public function registration(Request $request, EntityManagerInterface $em, 
UserPasswordEncoderInterface $passwordEncoder)
{
    $user = new User();
    // $role = $user->getRoles();

    $form = $this->createForm(UserType::class, $user);

    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {

        $password = $passwordEncoder->encodePassword($user, $user- 
>getPassword());
        $user->setPassword($password);
        $user->setIsBlocked(false);
        // $user->setRole($role);


        $em->persist($user);
        $em->flush();

        $this->addFlash('success', 'Votre compte à bien été enregistré.');
    }

    return $this->render('security/registration.html.twig', ['form' => 
$form->createView()]);
}

 /**
 * @Route("/logout", name="logout")
 */
public function logout() {}
}

1 个答案:

答案 0 :(得分:0)

在角色属性上,将nullable=false更改为nullable=true并更新数据库

 * @ORM\JoinColumn(nullable=true)
 */
private $role;