IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Symfony PHP Discussion :

erreur lors de l'inscription


Sujet :

Symfony PHP

  1. #1
    Inactif  
    Homme Profil pro
    Développeur Web
    Inscrit en
    Mai 2019
    Messages
    14
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 45
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Développeur Web

    Informations forums :
    Inscription : Mai 2019
    Messages : 14
    Par défaut erreur lors de l'inscription
    Bonjour !


    je débute avec symfony, en ce moment je monte un projet bidon histoire d'apprendre et de progresser , je me trouve confronté a une erreur au moment de l'inscription
    An exception occurred while executing 'INSERT INTO user (username, password, email, gender, newsletter, is_blocked, role_id, purchase_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?)' with params ["momo", "$2y$13$TVacivFf0zcOil.68.dWMuxZRy0zdGtIxm9SOnD\/.l1xCTP7RK1lG", "momo@test.fr", "1", 0, 0, null, null]:

    SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'role_id' cannot be null
    voiçi mon entity User :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    <?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;
        }
    }
    mon entity Role

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    <?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;
        }
    }
    SecurityController

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    <?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() {}
    }
    mon UserType

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    <?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,
            ]);
        }
    }
    Voila je vous remercie d'avance pour l'aide que vous pourrez m'apporter.

  2. #2
    Membre chevronné
    Homme Profil pro
    Étudiant
    Inscrit en
    Juillet 2011
    Messages
    351
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Ain (Rhône Alpes)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Juillet 2011
    Messages : 351
    Par défaut
    Salut,

    Sur ton entité User tu as une propriété "role" qui est obligatoire, or a priori cette propriété n'est jamais valorisée ni dans le formulaire d'inscription ni dans le contrôleur.
    D'où le message d'erreur obtenu : "Integrity constraint violation: 1048 Column 'role_id' cannot be null"

    Si l'utilisateur qui s'inscrit peut choisir son rôle parmi une liste de valeur possible, il faut que tu ajoutes un champ dans le formulaire (cf. https://symfony.com/doc/current/refe...es/entity.html).
    Sinon tu peux éventuellement attribuer un rôle par défaut à tous les nouveaux utilisateurs en faisant un setRole($role) dans ton SecurityController avant de persister le user (ce que tu sembles avoir commencé à faire puisqu'il y a une ligne commentée dans ton code).

  3. #3
    Inactif  
    Homme Profil pro
    Développeur Web
    Inscrit en
    Mai 2019
    Messages
    14
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 45
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Développeur Web

    Informations forums :
    Inscription : Mai 2019
    Messages : 14
    Par défaut
    Re !

    je te remercier pour ton explication cohérente, j'ai résolu le problème en changeant au niveau User entity
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    $roles = $this->roles;
            // guarantee every user at least has ROLE_USER
            $roles[] = '';
     
           return array_unique($roles);
    par
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    return [$this->role->getDescription()];

  4. #4
    Membre chevronné
    Homme Profil pro
    Étudiant
    Inscrit en
    Juillet 2011
    Messages
    351
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Ain (Rhône Alpes)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Juillet 2011
    Messages : 351
    Par défaut
    Super, n'oublie pas de mettre la discussion en "résolue" si c'est bien le cas !

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. [MySQL] erreur lors de l'affichage du programme d'inscription des enseignants
    Par fleurrouge dans le forum PHP & Base de données
    Réponses: 1
    Dernier message: 22/11/2012, 10h41
  2. Erreur lors de la date d'inscription à une certification
    Par huner dans le forum Certifications
    Réponses: 1
    Dernier message: 05/07/2011, 13h10
  3. Erreur lors de l'execution d'un script jsp
    Par tuxor dans le forum Servlets/JSP
    Réponses: 4
    Dernier message: 06/08/2004, 12h35
  4. Erreur lors de modification d'une table
    Par seb.49 dans le forum SQL
    Réponses: 11
    Dernier message: 13/01/2003, 17h16
  5. [VB6] Erreur lors de l'ouverture d'un document Word
    Par Marco le Pouillot dans le forum VB 6 et antérieur
    Réponses: 3
    Dernier message: 03/01/2003, 09h30

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo