Bonsoir

Voila je rencontre un souci avec une relation One to One avec Doctrine.

Ce que je fais

Je voudrais joindre deux entity, une qui override de FosUserBundle "user + controlleur register" et une autre qui independant "SecurityVote".

user.php "override de entity user de Fos":

<?php
// UserBundle/Entity/User.php

namespace UserBundle\Entity;

use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;

use UserBundle\Form\RegistrationType;

use Symfony\Component\Validator\Constraints as Assert;

/**
 * @ORM\Entity
 * @ORM\Table(name="user")
 * @ORM\HasLifecycleCallbacks
 */
class User extends BaseUser
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     *
     * @Assert\Length(
     *     min=2,
     *     max=255,
     *     minMessage="Pseudonyme Twitch trop court",
     *     maxMessage="Pseudonyme Twitch trop long.",
     *     groups={"Registration", "Profile"}
     * )
     */
    public $streamlink;

    /**
      * @ORM\OneToOne(targetEntity="UserBundle\Entity\SecurityVote", cascade={"persist"})
      */
    public $ip;

    public function __construct()
    {
        parent::__construct();
        $this->streamlink = null;

    }

    public function getParent() {
        return 'fos_user_profile';
    }

} 

RegistrationController.php "override du controller de Fos":

<?php
/*
 * This file is part of the FOSUserBundle package.
 *
 * (c) FriendsOfSymfony <http://friendsofsymfony.github.com/>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

// UserBundle/Controller/RegistrationController.php

namespace UserBundle\Controller;

use UserBundle\Entity\SecurityVote;
use UserBundle\Entity\User;

use FOS\UserBundle\FOSUserEvents;
use FOS\UserBundle\Event\FormEvent;
use FOS\UserBundle\Event\GetResponseUserEvent;
use FOS\UserBundle\Event\FilterUserResponseEvent;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use FOS\UserBundle\Model\UserInterface;

/**
 * Controller managing the registration
 *
 * @author Thibault Duplessis <thibault.duplessis@gmail.com>
 * @author Christophe Coevoet <stof@notk.org>
 */
class RegistrationController extends Controller
{
    public $ip;

    public function registerAction(Request $request)
    {
        /** @var $formFactory \FOS\UserBundle\Form\Factory\FactoryInterface */
        $formFactory = $this->get('fos_user.registration.form.factory');
        /** @var $userManager \FOS\UserBundle\Model\UserManagerInterface */
        $userManager = $this->get('fos_user.user_manager');
        /** @var $dispatcher \Symfony\Component\EventDispatcher\EventDispatcherInterface */
        $dispatcher = $this->get('event_dispatcher');

        $user = $userManager->createUser();
        $user->setEnabled(true);

        $event = new GetResponseUserEvent($user, $request);
        $dispatcher->dispatch(FOSUserEvents::REGISTRATION_INITIALIZE, $event);

        if (null !== $event->getResponse()) {
            return $event->getResponse();
        }

        $form = $formFactory->createForm();
        $form->setData($user);

        $form->handleRequest($request);

        if ($form->isValid()) {
            $Sv = new SecurityVote;
            $Sv->setIP($this->getIp());
            $event = new FormEvent($form, $request);
            $dispatcher->dispatch(FOSUserEvents::REGISTRATION_SUCCESS, $event);

            $userManager->updateUser($user);

            if (null === $response = $event->getResponse()) {
                $url = $this->generateUrl('fos_user_registration_confirmed');
                $response = new RedirectResponse($url);
            }

            $dispatcher->dispatch(FOSUserEvents::REGISTRATION_COMPLETED, new FilterUserResponseEvent($user, $request, $response));

            return $response;
        }

        return $this->render('FOSUserBundle:Registration:register.html.twig', array(
            'form' => $form->createView(),
        ));
    }

    /**
     * Tell the user to check his email provider
     */
    public function checkEmailAction()
    {
        $email = $this->get('session')->get('fos_user_send_confirmation_email/email');
        $this->get('session')->remove('fos_user_send_confirmation_email/email');
        $user = $this->get('fos_user.user_manager')->findUserByEmail($email);

        if (null === $user) {
            throw new NotFoundHttpException(sprintf('The user with email "%s" does not exist', $email));
        }

        return $this->render('FOSUserBundle:Registration:checkEmail.html.twig', array(
            'user' => $user,
        ));
    }

    /**
     * Receive the confirmation token from user email provider, login the user
     */
    public function confirmAction(Request $request, $token)
    {
        /** @var $userManager \FOS\UserBundle\Model\UserManagerInterface */
        $userManager = $this->get('fos_user.user_manager');

        $user = $userManager->findUserByConfirmationToken($token);

        if (null === $user) {
            throw new NotFoundHttpException(sprintf('The user with confirmation token "%s" does not exist', $token));
        }

        /** @var $dispatcher \Symfony\Component\EventDispatcher\EventDispatcherInterface */
        $dispatcher = $this->get('event_dispatcher');

        $user->setConfirmationToken(null);
        $user->setEnabled(true);

        $event = new GetResponseUserEvent($user, $request);
        $dispatcher->dispatch(FOSUserEvents::REGISTRATION_CONFIRM, $event);

        $userManager->updateUser($user);

        if (null === $response = $event->getResponse()) {
            $url = $this->generateUrl('fos_user_registration_confirmed');
            $response = new RedirectResponse($url);
        }

        $dispatcher->dispatch(FOSUserEvents::REGISTRATION_CONFIRMED, new FilterUserResponseEvent($user, $request, $response));

        return $response;
    }

    /**
     * Tell the user his account is now confirmed
     */
    public function confirmedAction()
    {
        $user = $this->getUser();
        if (!is_object($user) || !$user instanceof UserInterface) {
            throw new AccessDeniedException('This user does not have access to this section.');
        }

        return $this->render('FOSUserBundle:Registration:confirmed.html.twig', array(
            'user' => $user,
            'targetUrl' => $this->getTargetUrlFromSession(),
        ));
    }

    private function getTargetUrlFromSession()
    {
        // Set the SecurityContext for Symfony <2.6
        if (interface_exists('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')) {
            $tokenStorage = $this->get('security.token_storage');
        } else {
            $tokenStorage = $this->get('security.context');
        }

        $key = sprintf('_security.%s.target_path', $tokenStorage->getToken()->getProviderKey());

        if ($this->get('session')->has($key)) {
            return $this->get('session')->get($key);
        }
    }

    function getIp(){
        return $this->container->get('request_stack')->getCurrentRequest()->getClientIp();
    }
}

SecurityVote.php.php<?php

namespace UserBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**

  • SecurityVote
  • @ORM\Table(name="security_vote")
  • @ORM\Entity(repositoryClass="UserBundle\Repository\SecurityVoteRepository")
    */
    class SecurityVote
    {
    /**

    • @var int
    • @ORM\Column(name="id", type="integer")
    • @ORM\Id
    • @ORM\GeneratedValue(strategy="AUTO")
      */
      private $id;

    /**

    • @var string
    • @ORM\Column(name="ip", type="string", length=100, unique=true)
      */
      public $ip;

    /**

    • Get id
    • @return int
      */
      public function getId()
      {
      return $this->id;
      }

    /**

    • Set ip
    • @param string $ip
    • @return SecurityVote
      */
      public function setIp($ip)
      {
      $this->ip = $ip;

      return $this;
      }

    /**

    • Get ip
    • @return string
      */
      public function getIp()
      {
      return $this->ip;
      }
      }
      :
      
      <?php
      /*
  • This file is part of the FOSUserBundle package.
  • (c) FriendsOfSymfony http://friendsofsymfony.github.com/
  • For the full copyright and license information, please view the LICENSE
  • file that was distributed with this source code.
    */

// UserBundle/Controller/RegistrationController.php

namespace UserBundle\Controller;

use UserBundle\Entity\SecurityVote;
use UserBundle\Entity\User;

use FOS\UserBundle\FOSUserEvents;
use FOS\UserBundle\Event\FormEvent;
use FOS\UserBundle\Event\GetResponseUserEvent;
use FOS\UserBundle\Event\FilterUserResponseEvent;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use FOS\UserBundle\Model\UserInterface;

/**

  • Controller managing the registration
  • @author Thibault Duplessis thibault.duplessis@gmail.com
  • @author Christophe Coevoet stof@notk.org
    */
    class RegistrationController extends Controller
    {
    public $ip;

    public function registerAction(Request $request)
    {
    / @var $formFactory \FOS\UserBundle\Form\Factory\FactoryInterface */
    $formFactory = $this->get('fos_user.registration.form.factory');
    /* @var $userManager \FOS\UserBundle\Model\UserManagerInterface /
    $userManager = $this->get('fos_user.user_manager');
    /
    @var $dispatcher \Symfony\Component\EventDispatcher\EventDispatcherInterface */
    $dispatcher = $this->get('event_dispatcher');

    $user = $userManager->createUser();
    $user->setEnabled(true);
    
    $event = new GetResponseUserEvent($user, $request);
    $dispatcher->dispatch(FOSUserEvents::REGISTRATION_INITIALIZE, $event);
    
    if (null !== $event->getResponse()) {
        return $event->getResponse();
    }
    
    $form = $formFactory->createForm();
    $form->setData($user);
    
    $form->handleRequest($request);
    
    if ($form->isValid()) {
        $Sv = new SecurityVote;
        $Sv->setIP($this->getIp());
        $event = new FormEvent($form, $request);
        $dispatcher->dispatch(FOSUserEvents::REGISTRATION_SUCCESS, $event);
    
        $userManager->updateUser($user);
    
        if (null === $response = $event->getResponse()) {
            $url = $this->generateUrl('fos_user_registration_confirmed');
            $response = new RedirectResponse($url);
        }
    
        $dispatcher->dispatch(FOSUserEvents::REGISTRATION_COMPLETED, new FilterUserResponseEvent($user, $request, $response));
    
        return $response;
    }
    
    return $this->render('FOSUserBundle:Registration:register.html.twig', array(
        'form' => $form->createView(),
    ));

    }

    /**

    • Tell the user to check his email provider
      */
      public function checkEmailAction()
      {
      $email = $this->get('session')->get('fos_user_send_confirmation_email/email');
      $this->get('session')->remove('fos_user_send_confirmation_email/email');
      $user = $this->get('fos_user.user_manager')->findUserByEmail($email);

      if (null === $user) {
      throw new NotFoundHttpException(sprintf('The user with email "%s" does not exist', $email));
      }

      return $this->render('FOSUserBundle:Registration:checkEmail.html.twig', array(
      'user' => $user,
      ));
      }

    /**

    • Receive the confirmation token from user email provider, login the user
      */
      public function confirmAction(Request $request, $token)
      {
      /* @var $userManager \FOS\UserBundle\Model\UserManagerInterface /
      $userManager = $this->get('fos_user.user_manager');

      $user = $userManager->findUserByConfirmationToken($token);

      if (null === $user) {
      throw new NotFoundHttpException(sprintf('The user with confirmation token "%s" does not exist', $token));
      }

      /* @var $dispatcher \Symfony\Component\EventDispatcher\EventDispatcherInterface /
      $dispatcher = $this->get('event_dispatcher');

      $user->setConfirmationToken(null);
      $user->setEnabled(true);

      $event = new GetResponseUserEvent($user, $request);
      $dispatcher->dispatch(FOSUserEvents::REGISTRATION_CONFIRM, $event);

      $userManager->updateUser($user);

      if (null === $response = $event->getResponse()) {
      $url = $this->generateUrl('fos_user_registration_confirmed');
      $response = new RedirectResponse($url);
      }

      $dispatcher->dispatch(FOSUserEvents::REGISTRATION_CONFIRMED, new FilterUserResponseEvent($user, $request, $response));

      return $response;
      }

    /**

    • Tell the user his account is now confirmed
      */
      public function confirmedAction()
      {
      $user = $this->getUser();
      if (!is_object($user) || !$user instanceof UserInterface) {
      throw new AccessDeniedException('This user does not have access to this section.');
      }

      return $this->render('FOSUserBundle:Registration:confirmed.html.twig', array(
      'user' => $user,
      'targetUrl' => $this->getTargetUrlFromSession(),
      ));
      }

    private function getTargetUrlFromSession()
    {
    // Set the SecurityContext for Symfony <2.6
    if (interface_exists('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')) {
    $tokenStorage = $this->get('security.token_storage');
    } else {
    $tokenStorage = $this->get('security.context');
    }

    $key = sprintf('_security.%s.target_path', $tokenStorage->getToken()->getProviderKey());
    
    if ($this->get('session')->has($key)) {
        return $this->get('session')->get($key);
    }

    }

    function getIp(){
    return $this->container->get('request_stack')->getCurrentRequest()->getClientIp();
    }
    }

### Ce que j'obtiens

Le soucie et que la jonction se fais puisque il crée ip_id. mais ne l'implemente pas.

erreur:

An exception occurred while executing 'INSERT INTO user (username, username_canonical, email, email_canonical, enabled, salt, password, last_login, locked, expired, expires_at, confirmation_token, password_requested_at, roles, credentials_expired, credentials_expire_at, streamlink, ip_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)' with params ["testip", "testip", "testip@testip.testip", "testip@testip.testip", 1, "atr3ymml8204kg408koc4koccwc0sww", "$2y$13$3P47PumrXC\/TpbBwlH9..uBmddhndiv8tHSJQU\/O0RLiixXDuDUmG", null, 0, 0, null, null, null, "a:0:{}", 0, null, "aze", null]:

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'ip_id' cannot be null

2 réponses


Tu créer ton SecurityVote, mais a aucun moment tu ne l'affecte à ton user en faisant

$user->setIp($v);

Du coup ton attribut ip est vide, et comme il en a besoin pour enregistrer le user il te plante

ck_hunt
Auteur

a ok désolé pour l'erreur bète mais bon c'est avec les erreur quont apprent. j'ais pas la posibiliter de tester sa pour le moment des que ces posible je donne des new.