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 :

Enregistrement de nouvelles données pour un utilisateur


Sujet :

Symfony PHP

  1. #1
    Membre confirmé
    Profil pro
    Étudiant
    Inscrit en
    Avril 2009
    Messages
    96
    Détails du profil
    Informations personnelles :
    Localisation : France, Charente Maritime (Poitou Charente)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Avril 2009
    Messages : 96
    Par défaut Enregistrement de nouvelles données pour un utilisateur
    Bonjour à tous !

    Me revoilà avec mes petits problèmes.

    Donc dans un premier temps, j'ai un utilisateur (héritant de FOSUserBundle). Mon utilisateur possède une civilité et une école.
    Pour cela j'ai fait :

    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
        public function buildForm(FormBuilder $builder, array $options)
        {
            parent::buildForm($builder, $options);
     
            $builder
                    // about yourself
                    ->add('firstname', 'text', array('attr' => array('placeholder' => 'First name')))
                    ->add('lastname', 'text', array('attr' => array('placeholder' => 'Last name')))
                    ->add('phone', 'text')
                    ->add('email', 'email')
                    ->add('civility', new CivilityType())
                    ->add('nationality', new NationalityType())
                    ->add('birthday', 'date')
     
                    // school
                    ->add('school', new SchoolType());
        }
    Pour la civilité :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
        public function buildForm(FormBuilder $builder, array $options)
        {
            $builder
                ->add('civility','entity', array( 
                                            'label' => 'Civility',
                                            'class' =>'monsite\\UserBundle\\Entity\\Civility',
                                            'property' => 'libel',
                                            'query_builder' => function(EntityRepository $er) 
                                            {  
                                                return $er->createQueryBuilder('c');
                                            }
                                            ));
        }
    mon twig :

    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
    {% extends "::base_menuleft_account.html.twig" %}
     
    {% block body %}
        <form action="{{ path('mon_site_user_me') }}" {{ form_enctype(form) }} method="POST" class="fos_user_registration_register">
     
            <div>Join Us !</div>
     
                <div class="#">
     
                        About yourself
     
                            {{ form_errors(form.firstname) }}
                            {{ form_widget(form.firstname) }}
     
                            {{ form_errors(form.lastname) }}
                            {{ form_widget(form.lastname) }}
     
                            {{ form_errors(form.phone) }}
                            {{ form_widget(form.phone) }}
     
                            {{ form_errors(form.email) }}
                            {{ form_widget(form.email) }}
     
                            {{ form_errors(form.civility) }}
                            {{ form_widget(form.civility) }}
     
                            {{ form_errors(form.nationality) }}
                            {{ form_widget(form.nationality) }}
     
                            {{ form_label(form.birthday) }}
                            {{ form_errors(form.birthday) }}
                            {{ form_widget(form.birthday) }}
     
     
                    {{ form_rest( form ) }}
                    <input type="submit" value="{{ 'registration.submit'|trans({}, 'FOSUserBundle') }}">
     
               </div>
        </form>
    {% endblock body %}
    ma route :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    mon_site_user_me:
        pattern:   /monBoard/Me
        defaults:  { _controller: monsiteUserBundle:monBoard:me }
    mon controller :

    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
        public function meAction()
        {
            if(!$this->get('security.context')->isGranted('ROLE_USER'))
            {
                throw new AccessDeniedHttpException('Accès limité aux auteurs');
            }
            else
            {
                $userManager = $this->get('fos_user.user_manager');
                $userCurrent = $this->container->get('security.context')->getToken()->getUser();
                $user = $userManager->findUserBy(array('username' => $userCurrent));
     
                $form = $this->createForm(new UserType($this->getDoctrine()->getEntityManager()), $user);
                $formHandler = new UserHandler($form, 
                                               $this->get('request'), 
                                               $this->getDoctrine()->getEntityManager());
                var_dump($user);
                if($formHandler->process())
                {
                    return $this->redirect( $this->generateUrl('mon_site_user_me', array('id' => $user->getId())) );
                }
                return $this->render('monsiteUserBundle:monBoard:me.html.twig', array('form' => $form->createView()));
            }
        }
    Mon erreur :

    Neither property "civility" nor method "getCivility()" nor method "isCivility()" exists in class "monsite\UserBundle\Entity\Civility"

    Je ne comprends pas très bien pourquoi il fait un getCivility dans la classe civility ! Qu'est ce que je fais de mal ?

    Merci de votre aide

  2. #2
    Membre éclairé
    Homme Profil pro
    Développeur Web
    Inscrit en
    Avril 2012
    Messages
    394
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Hauts de Seine (Île de France)

    Informations professionnelles :
    Activité : Développeur Web
    Secteur : High Tech - Multimédia et Internet

    Informations forums :
    Inscription : Avril 2012
    Messages : 394
    Par défaut
    je crois que ton soucis vient de monsite\UserBundle\Entity\Civility.php. fais nous voir ce fichier.

  3. #3
    Membre confirmé
    Profil pro
    Étudiant
    Inscrit en
    Avril 2009
    Messages
    96
    Détails du profil
    Informations personnelles :
    Localisation : France, Charente Maritime (Poitou Charente)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Avril 2009
    Messages : 96
    Par défaut
    Citation Envoyé par aitiahcene Voir le message
    je crois que ton soucis vient de monsite\UserBundle\Entity\Civility.php. fais nous voir ce fichier.
    Je ne vois pas pourquoi ça viendrait de là. En fait il me demande un getCivility DANS la table civility, ce que je trouve idiot, non ? Se serait quoi la définition de cette méthode getCivility : {return $this;} ?
    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
    <?php
     
    namespace monsite\UserBundle\Entity;
     
    use Doctrine\ORM\Mapping as ORM;
     
    /**
     * monsite\UserBundle\Entity\Civility
     *
     * @ORM\Table(name="civility")
     * @ORM\Entity
     */
    class Civility
    {
        /**
         * @var integer $id
         *
         * @ORM\Column(name="id", type="integer", nullable=false)
         * @ORM\Id
         * @ORM\GeneratedValue(strategy="IDENTITY")
         */
        private $id;
     
        /**
         * @var string $libel
         *
         * @ORM\Column(name="libel", type="string", length=255, nullable=true)
         */
        private $libel;
     
     
        public function getLibel()
        {
            return $this->libel;
        }
     
        public function setLibel($libel)
        {
            $this->libel = $libel;
        }    
     
    }

  4. #4
    Membre confirmé
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Avril 2012
    Messages
    73
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 34
    Localisation : France, Yvelines (Île de France)

    Informations professionnelles :
    Activité : Développeur informatique
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Avril 2012
    Messages : 73
    Par défaut
    Le problème viens probablement de ta classe User.
    Symfony2 a besoin de pouvoir accéder aux propriétés soit directement si ils sont public soit au moyens de méthode avec des prefixes comme "get", "set"[, "is" (plus pour les type boolean), ....]
    Vérifie que ces méthodes sont bien présentes et sinon implémente les

  5. #5
    Membre confirmé
    Profil pro
    Étudiant
    Inscrit en
    Avril 2009
    Messages
    96
    Détails du profil
    Informations personnelles :
    Localisation : France, Charente Maritime (Poitou Charente)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Avril 2009
    Messages : 96
    Par défaut
    Citation Envoyé par Teudjy Voir le message
    Le problème viens probablement de ta classe User.
    Symfony2 a besoin de pouvoir accéder aux propriétés soit directement si ils sont public soit au moyens de méthode avec des prefixes comme "get", "set"[, "is" (plus pour les type boolean), ....]
    Vérifie que ces méthodes sont bien présentes et sinon implémente les
    Déjà fait, dans la table user :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
        public function getCivility()
        {
            return $this->civility;
        }
     
        public function setCivility(Civility $civility)
        {
            $this->civility = $civility;
        }

  6. #6
    Membre confirmé
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Avril 2012
    Messages
    73
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 34
    Localisation : France, Yvelines (Île de France)

    Informations professionnelles :
    Activité : Développeur informatique
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Avril 2012
    Messages : 73
    Par défaut
    Autant pour moi ^^

    Maintenant dans ton type Civility, au lieu de mettre les options du champ dans la méthode buildForm, met les dans la méthode getDefaultOptions comme suit :

    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
     
    class CivilityType extends AbstractType {
     
        public function getDefaultOptions(array $options) {
            return array(
                'label' => 'Civility',
                'property' => 'libel',
                'class' => 'UserBundle:Fuel',
                'query_builder' => function(EntityRepository $er) 
                                            {  
                                                return $er->createQueryBuilder('c');
                                            },
            );
        }
     
        public function getParent(array $options) {
            return 'entity';
        }
     
        public function getName() {
            return 'civility';
        }
    }

  7. #7
    Membre confirmé
    Profil pro
    Étudiant
    Inscrit en
    Avril 2009
    Messages
    96
    Détails du profil
    Informations personnelles :
    Localisation : France, Charente Maritime (Poitou Charente)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Avril 2009
    Messages : 96
    Par défaut
    Citation Envoyé par Teudjy Voir le message
    Autant pour moi ^^

    Maintenant dans ton type Civility, au lieu de mettre les options du champ dans la méthode buildForm, met les dans la méthode getDefaultOptions comme suit :
    Dans un premier temps, merci de ton aide qui m'est très précieuse !

    mais j'ai encore une erreur avec ta solution : Expected argument of type "scalar", "array" given

  8. #8
    Membre confirmé
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Avril 2012
    Messages
    73
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 34
    Localisation : France, Yvelines (Île de France)

    Informations professionnelles :
    Activité : Développeur informatique
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Avril 2012
    Messages : 73
    Par défaut
    Vérifie le type que génère ton formulaire et le type que ton entité attends, il y a peut-être une histoire de choix multiple

    http://stackoverflow.com/questions/1...ar-array-given

  9. #9
    Membre confirmé
    Profil pro
    Étudiant
    Inscrit en
    Avril 2009
    Messages
    96
    Détails du profil
    Informations personnelles :
    Localisation : France, Charente Maritime (Poitou Charente)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Avril 2009
    Messages : 96
    Par défaut
    Citation Envoyé par Teudjy Voir le message
    Vérifie le type que génère ton formulaire et le type que ton entité attends, il y a peut-être une histoire de choix multiple

    http://stackoverflow.com/questions/1...ar-array-given
    Justement, je suis aussi tombé sur ce site, mais je n'ai pas compris

    Et le fait que eux travail sur le "builder" me rassure. Je ne comprends pas très bien comment fait le framework avec ta solution.

    Ce que je veux c'est lister les Civilités (Male / Female) dans une combobox, et mettre a jour mon utilisateur avec la fonction Me. Je n'ai pas envi de passer par Choises, parce que si je fais ça , je devrais changer mon code si j'ajoute "Doctor" par exemple, donc je veux récupérer les données de ma table Civilité. Je suis désolé, je n'ai pas compris le lien que tu m'as passé

  10. #10
    Membre confirmé
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Avril 2012
    Messages
    73
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 34
    Localisation : France, Yvelines (Île de France)

    Informations professionnelles :
    Activité : Développeur informatique
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Avril 2012
    Messages : 73
    Par défaut
    Ok j'ai compris ce que tu veux

    Si j'ai bien compris ce qu'il se passe c'est que dans ton entité User tu ne veux qu'une seul civilité, seulement le formulaire t'envoie un tableau.
    Regarde si les options par défaut sont bien en choix unique, ou alors re-précise le (rien ne vaut de re-préciser des valeurs définies par défaut ^^).

    Quand j'ai des soucis comme ça j'utilise var_dump(), c'est très pratique parfois

  11. #11
    Membre confirmé
    Profil pro
    Étudiant
    Inscrit en
    Avril 2009
    Messages
    96
    Détails du profil
    Informations personnelles :
    Localisation : France, Charente Maritime (Poitou Charente)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Avril 2009
    Messages : 96
    Par défaut
    Citation Envoyé par Teudjy Voir le message
    Ok j'ai compris ce que tu veux
    Quand j'ai des soucis comme ça j'utilise var_dump(), c'est très pratique parfois
    Je l'utilise énormément aussi, le problème est à la validation de mon formulaire. Dans mon user j'ai ça (grâce a var_dump):

    private 'civility' => null

    et l'erreur symfony : Expected argument of type "scalar", "array" given.

    Je ne comprends pas se qui se passe, c'est pour ça que je suis bloqué ^^

  12. #12
    Membre confirmé
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Avril 2012
    Messages
    73
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 34
    Localisation : France, Yvelines (Île de France)

    Informations professionnelles :
    Activité : Développeur informatique
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Avril 2012
    Messages : 73
    Par défaut
    Et il ne te dise pas a quel ligne cette erreur surviens ?
    tu n'as pas plus d'infos au sujet de cette erreur ? pas moyen d'afficher la trace de cette erreur ?

  13. #13
    Membre confirmé
    Profil pro
    Étudiant
    Inscrit en
    Avril 2009
    Messages
    96
    Détails du profil
    Informations personnelles :
    Localisation : France, Charente Maritime (Poitou Charente)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Avril 2009
    Messages : 96
    Par défaut
    Citation Envoyé par Teudjy Voir le message
    Et il ne te dise pas a quel ligne cette erreur surviens ?
    tu n'as pas plus d'infos au sujet de cette erreur ? pas moyen d'afficher la trace de cette erreur ?
    Si mais j'espère que ça ne va pas t'être trop imbuvable :

    Expected argument of type "scalar", "array" given
    500 Internal Server Error - UnexpectedTypeException

    Stack Trace
    in C:\wamp\www\monsite\vendor\symfony\src\Symfony\Component\Form\Extension\Core\DataTransformer\ScalarToChoiceTransformer.php at line 32
    public function reverseTransform($value)
    {
    if (null !== $value && !is_scalar($value)) {
    throw new UnexpectedTypeException($value, 'scalar');
    }
    return $value;
    at ScalarToChoiceTransformer ->reverseTransform (array('school' => '3'))
    in C:\wamp\www\monsite\vendor\symfony\src\Symfony\Component\Form\Form.php at line 1011
    at Form ->clientToNorm (array('school' => '3'))
    in C:\wamp\www\monsite\vendor\symfony\src\Symfony\Component\Form\Form.php at line 528
    at Form ->bind (array('school' => '3'))
    in C:\wamp\www\monsite\vendor\symfony\src\Symfony\Component\Form\Form.php at line 500
    at Form ->bind (array('firstname' => 'faivre', 'lastname' => 'sylvain', 'phone' => '0649895532', 'email' => 'faivre.sylvain@gmail.com', 'civility' => '1', 'nationality' => array('nationality' => '6'), 'birthday' => array('year' => '2007', 'month' => '1', 'day' => '3'), '_token' => 'c6b6059cd9af5f70ab110d14f1f2232c25a84ee1', 'school' => array('school' => '3')))
    in C:\wamp\www\monsite\vendor\symfony\src\Symfony\Component\Form\Form.php at line 592
    at Form ->bindRequest (object(Request))
    in C:\wamp\www\monsite\src\monsite\UserBundle\Form\Handler\UserHandler.php at line 27
    at UserHandler ->process ()
    in C:\wamp\www\monsite\src\monsite\UserBundle\Controller\SwitchBoardController.php at line 73
    at SwitchBoardController ->meAction ()
    at call_user_func_array (array(object(SwitchBoardController), 'meAction'), array())
    in C:\wamp\www\monsite\app\cache\dev\classes.php at line 3905
    at HttpKernel ->handleRaw (object(Request), '1')
    in C:\wamp\www\monsite\app\cache\dev\classes.php at line 3875
    at HttpKernel ->handle (object(Request), '1', true)
    in C:\wamp\www\monsite\app\cache\dev\classes.php at line 4879
    at HttpKernel ->handle (object(Request), '1', true)
    in C:\wamp\www\monsite\app\bootstrap.php.cache at line 552
    at Kernel ->handle (object(Request))
    in C:\wamp\www\monsite\web\app_dev.php at line 27
    Logs 1 error
    Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\ProfilerListener::onKernelRequest".
    Notified event "kernel.request" to listener "Symfony\Bundle\FrameworkBundle\EventListener\RouterListener::onEarlyKernelRequest".
    Notified event "kernel.request" to listener "Symfony\Bundle\FrameworkBundle\EventListener\SessionListener::onKernelRequest".
    Notified event "kernel.request" to listener "Symfony\Component\Security\Http\Firewall::onKernelRequest".
    Read SecurityContext from the session
    Reloading user from user provider.
    SET NAMES UTF8 ([])
    SELECT t0.username AS username1, t0.username_canonical AS username_canonical2, t0.email AS email3, t0.email_canonical AS email_canonical4, t0.enabled AS enabled5, t0.salt AS salt6, t0.password AS password7, t0.last_login AS last_login8, t0.locked AS locked9, t0.expired AS expired10, t0.expires_at AS expires_at11, t0.confirmation_token AS confirmation_token12, t0.password_requested_at AS password_requested_at13, t0.roles AS roles14, t0.credentials_expired AS credentials_expired15, t0.credentials_expire_at AS credentials_expire_at16, t0.id AS id17, t0.firstname AS firstname18, t0.lastname AS lastname19, t0.date_birth AS date_birth20, t0.phone AS phone21, t0.description AS description22, t0.civility_id AS civility_id23, t0.nationality_id AS nationality_id24, t0.school_id AS school_id25, t0.lodgement_id AS lodgement_id26, t0.address_id AS address_id27 FROM user t0 WHERE t0.username_canonical = ? (["faivre.sylvain@gmail.com"])
    Username "faivre.sylvain@gmail.com" was reloaded from user provider.
    Notified event "kernel.request" to listener "Symfony\Bundle\FrameworkBundle\EventListener\RouterListener::onKernelRequest".
    Matched route "switch_around_user_me" (parameters: "_controller": "monsite\UserBundle\Controller\SwitchBoardController::meAction", "_route": "switch_around_user_me")
    Notified event "kernel.request" to listener "Symfony\Bundle\AsseticBundle\EventListener\RequestListener::onKernelRequest".
    Notified event "kernel.controller" to listener "Symfony\Bundle\FrameworkBundle\DataCollector\RequestDataCollector::onKernelController".
    Notified event "kernel.controller" to listener "Sensio\Bundle\FrameworkExtraBundle\EventListener\ControllerListener::onKernelController".
    Notified event "kernel.controller" to listener "Sensio\Bundle\FrameworkExtraBundle\EventListener\ParamConverterListener::onKernelController".
    Notified event "kernel.controller" to listener "Sensio\Bundle\FrameworkExtraBundle\EventListener\TemplateListener::onKernelController".
    Notified event "kernel.controller" to listener "JMS\SecurityExtraBundle\Controller\ControllerListener::onCoreController".
    SELECT t0.username AS username1, t0.username_canonical AS username_canonical2, t0.email AS email3, t0.email_canonical AS email_canonical4, t0.enabled AS enabled5, t0.salt AS salt6, t0.password AS password7, t0.last_login AS last_login8, t0.locked AS locked9, t0.expired AS expired10, t0.expires_at AS expires_at11, t0.confirmation_token AS confirmation_token12, t0.password_requested_at AS password_requested_at13, t0.roles AS roles14, t0.credentials_expired AS credentials_expired15, t0.credentials_expire_at AS credentials_expire_at16, t0.id AS id17, t0.firstname AS firstname18, t0.lastname AS lastname19, t0.date_birth AS date_birth20, t0.phone AS phone21, t0.description AS description22, t0.civility_id AS civility_id23, t0.nationality_id AS nationality_id24, t0.school_id AS school_id25, t0.lodgement_id AS lodgement_id26, t0.address_id AS address_id27 FROM user t0 WHERE t0.username = ? ([{}])
    SELECT c0_.id AS id0, c0_.libel AS libel1 FROM civility c0_ ([])
    SELECT n0_.id AS id0, n0_.nationality AS nationality1 FROM nationality n0_ ([])
    Notified event "kernel.exception" to listener "Symfony\Component\Security\Http\Firewall\ExceptionListener::onKernelException".
    Notified event "kernel.exception" to listener "Symfony\Component\HttpKernel\EventListener\ProfilerListener::onKernelException".
    Notified event "kernel.exception" to listener "Symfony\Component\HttpKernel\EventListener\ExceptionListener::onKernelException".
    Symfony\Component\Form\Exception\UnexpectedTypeException: Expected argument of type "scalar", "array" given (uncaught exception) at C:\wamp\www\monsite\vendor\symfony\src\Symfony\Component\Form\Extension\Core\DataTransformer\ScalarToChoiceTransformer.php line 32
    Notified event "kernel.request" to listener "Symfony\Component\HttpKernel\EventListener\ProfilerListener::onKernelRequest".
    Notified event "kernel.request" to listener "Symfony\Bundle\FrameworkBundle\EventListener\RouterListener::onEarlyKernelRequest".
    Notified event "kernel.request" to listener "Symfony\Bundle\FrameworkBundle\EventListener\SessionListener::onKernelRequest".
    Notified event "kernel.request" to listener "Symfony\Component\Security\Http\Firewall::onKernelRequest".
    Notified event "kernel.request" to listener "Symfony\Bundle\FrameworkBundle\EventListener\RouterListener::onKernelRequest".
    Notified event "kernel.request" to listener "Symfony\Bundle\AsseticBundle\EventListener\RequestListener::onKernelRequest".
    Notified event "kernel.controller" to listener "Symfony\Bundle\FrameworkBundle\DataCollector\RequestDataCollector::onKernelController".
    Notified event "kernel.controller" to listener "Sensio\Bundle\FrameworkExtraBundle\EventListener\ControllerListener::onKernelController".
    Notified event "kernel.controller" to listener "Sensio\Bundle\FrameworkExtraBundle\EventListener\ParamConverterListener::onKernelController".
    Notified event "kernel.controller" to listener "Sensio\Bundle\FrameworkExtraBundle\EventListener\TemplateListener::onKernelController".
    Notified event "kernel.controller" to listener "JMS\SecurityExtraBundle\Controller\ControllerListener::onCoreController".

  14. #14
    Membre confirmé
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Avril 2012
    Messages
    73
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 34
    Localisation : France, Yvelines (Île de France)

    Informations professionnelles :
    Activité : Développeur informatique
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Avril 2012
    Messages : 73
    Par défaut
    Regarde les champs nationality et school
    Je pense que ce sont ces champs la qui posent problème

  15. #15
    Membre confirmé
    Profil pro
    Étudiant
    Inscrit en
    Avril 2009
    Messages
    96
    Détails du profil
    Informations personnelles :
    Localisation : France, Charente Maritime (Poitou Charente)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Avril 2009
    Messages : 96
    Par défaut
    Citation Envoyé par Teudjy Voir le message
    Regarde les champs nationality et school
    Je pense que ce sont ces champs la qui posent problème
    J'ai bien revu mon code, et j'en suis là :
    Mon meAction n'a pas bouger. Mon handler est comme ça :

    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
    <?php
     
    namespace monsite\UserBundle\Form\Handler;
     
    use FOS\UserBundle\Model\UserInterface;
    use Symfony\Component\Form\Form;
    use Symfony\Component\HttpFoundation\Request;
    use FOS\UserBundle\Entity\UserManager;
     
    class UserHandler
    {        
        protected $form;
        protected $request;
        protected $em;
     
        public function __construct(Form $form, Request $request, UserManager $em)
        {
            $this->form    = $form;
            $this->request = $request;
            $this->em      = $em;
        }
     
        public function process()
        {
            if( $this->request->getMethod() == 'POST' )
            {
                $this->form->bindRequest($this->request);
     
                if( $this->form->isValid() )
                {
                   $this->onSuccess($this->form->getData());
     
                    return true;
                }
            }
            return false;
        }  
     
        protected function onSuccess(UserInterface $user)
        {
            var_dump($user);
            $this->em->updateUser($user);
        }
    }
    Mon 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
    <?php
     
    namespace monsite\UserBundle\Entity;
    use Doctrine\ORM\Mapping as ORM;
    use FOS\UserBundle\Entity\User as BaseUser;
    use Symfony\Component\Validator\Constraints as Assert;
    use Doctrine\Common\Collections\ArrayCollection;
     
    /**
     * monsite\UserBundle\Entity\User
     *
     * @ORM\Entity
     * @ORM\Table(name="user")
     */
    class User extends BaseUser
    {
        /**
         * @var integer $id
         *
         * @ORM\Id
         * @ORM\Column(name="id", type="integer", nullable=false)
         * @ORM\GeneratedValue(strategy="IDENTITY")
         */
        protected $id;
     
        /**
         * @var string $name
         *
         * @ORM\Column(name="firstname", type="string", length=255, nullable=true)
         */
        private $firstname;
     
        /**
         * @var string $surname
         *
         * @ORM\Column(name="lastname", type="string", length=255, nullable=true)
         */
        private $lastname;
     
        /**
         * @var date $dateBirth
         *
         * @ORM\Column(name="date_birth", type="date", nullable=true)
         */
        private $birthday;
     
        /**
         * @var string $phone
         *
         * @ORM\Column(name="phone", type="string", length=20, nullable=true) 
         * @Assert\MinLength(limit="6", message="Too shot")
         * @Assert\MaxLength(limit="10", message="Too long")
         * 
         */
        private $phone;
     
        /**
         * @var Civility $civility
         *
         * @ORM\ManyToOne(targetEntity="monsite\UserBundle\Entity\Civility", cascade={"persist"})
         */
        private $civility;
     
        /**
         * @var Nationality $nationality
         *
         * @ORM\ManyToOne(targetEntity="monsite\UserBundle\Entity\Nationality", cascade={"persist"})
         */
        private $nationality;
     
        /**
         * @var School $school
         *
         * @ORM\ManyToOne(targetEntity="monsite\UserBundle\Entity\School", cascade={"persist"})
         */
        private $school;
     
        /**
         * @var Language $language
         *
         * @ORM\ManyToMany(targetEntity="monsite\UserBundle\Entity\Language", mappedBy="id", cascade={"remove", "persist"}))
         */
        private $language;
     
        /**
         * @var string $description
         *
         * @ORM\Column(name="description", type="string", length=1000, nullable=true)
         */
        private $description;
     
        /**
         * @var Interest $interest
         *
         * @ORM\ManyToMany(targetEntity="monsite\UserBundle\Entity\Interest")
         */
        private $interest;
     
        /**
         * @var Lodgement $lodgement
         *
         * @ORM\ManyToOne(targetEntity="monsite\UserBundle\Entity\Lodgement")
         */
        private $lodgement;
     
        /**
         * @var UserPhoto $photo
         *
         * @ORM\OneToMany(targetEntity="monsite\UserBundle\Entity\UserPhoto", mappedBy="id", cascade={"remove", "persist"}))
         */
        private $photo;
     
        /**
         * @var Address $address
         *
         * @ORM\ManyToOne(targetEntity="monsite\UserBundle\Entity\Address")
         */
        private $address;
     
        public function __construct()
        {
            parent::__construct();
            $this->interest = new ArrayCollection();
            $this->language = new ArrayCollection();
        }
     
        public function getFirstname()
        {
            return $this->firstname;
        }
     
        public function setFirstname($firstname)
        {
            $this->firstname = $firstname;
        }
     
        public function getLastname()
        {
            return $this->lastname;
        }
     
        public function setLastname($lastname)
        {
            $this->lastname = $lastname;
        }
     
        public function setEmail($email)
        {
            parent::setEmail($email);
            $this->setUsername($email);
        }
     
        public function getPhone()
        {
            return $this->phone;
        }
     
        public function setPhone($phone)
        {
            $this->phone = $phone;
        }
     
        public function getCivility()
        {
            return $this->civility;
        }
     
        public function setCivility(Civility $civility)
        {
            $this->civility = $civility;
        }
     
        public function getNationality()
        {
            return $this->nationality;
        }
     
        public function setNationality(Nationality $nationality)
        {
            $this->nationality = $nationality;
        }
     
        public function getBirthday()
        {
            return $this->birthday;
        }
     
        public function setBirthday(\DateTime $birthday)
        {
            $this->birthday = $birthday;
        }
     
        public function getSchool()
        {
            return $this->school;
        }
     
        public function setSchool(School $school)
        {
            $this->school = $school;
        }
     
        public function addInterest(Interest $interest)
        {
            $this->interest[] = $interest;
        }
     
        public function getInterest()
        {
            return $this->interest;
        }
     
        public function addLanguage(Language $language)
        {
            $this->language[] = $language;
        }
     
        public function getLanguage()
        {
            return $this->language;
        }
    }
    Mon user type (non fini, mais fonctionnel) :
    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
    <?php
     
    namespace monsite\UserBundle\Form\Type;
     
    use Symfony\Component\Form\FormBuilder;
    use Symfony\Component\Form\AbstractType;
    use Symfony\Component\Validator\Constraints\CallbackValidator;
    use Symfony\Component\Form\FormValidatorInterface;
    use Symfony\Component\Form as Form;
    use Doctrine\ORM\EntityManager ;
     
    class UserType extends AbstractType
    {
        protected $em;
     
        function __construct(EntityManager $em) {
            $this->em=$em;
        }
     
        public function buildForm(FormBuilder $builder, array $options)
        {
            parent::buildForm($builder, $options);
     
            $builder
                    // about yourself
                    ->add('firstname', 'text', array('attr' => array('placeholder' => 'First name')))
                    ->add('lastname', 'text', array('attr' => array('placeholder' => 'Last name')))
                    ->add('phone', 'text')
                    ->add('email', 'email')
                    ->add('civility', new CivilityType())
                    ->add('nationality', new NationalityType())
                    ->add('birthday', 'date')
     
                    // school
                    ->add('school', new SchoolType());
        }
     
        public function getName()
        {
            return 'mon_around_user_type';
        }
     
        public function getDefaultOptions(array $options)
        {
            return array(
                'data_class' => 'monsite\UserBundle\Entity\User',
            );
        }
    }
    Mon school type :
    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
    <?php 
     
    namespace monsite\UserBundle\Form\Type;
     
    use Symfony\Component\Form\FormBuilder; 
    use Symfony\Component\Form\AbstractType;
    use monsite\UserBundle\Entity\School;
    use Doctrine\ORM\EntityManager ;
    use Doctrine\ORM\EntityRepository;
     
    class SchoolType extends AbstractType 
    {
        public function buildForm(FormBuilder $builder, array $options)
        {
            $builder->add('name', 'entity', array(
                                            'label' => 'School',
                                            'property' => 'name',
                                            'class' =>'monsite\\UserBundle\\Entity\\School',
                                            'query_builder' => function(EntityRepository $er) 
                                            {  
                                                return $er->createQueryBuilder('c');
                                            }))
                    ->add('speciality', 'entity', array(
                                            'label' => 'Speciality',
                                            'property' => 'libel',
                                            'class' =>'monsite\\UserBundle\\Entity\\Speciality',
                                            'query_builder' => function(EntityRepository $er) 
                                            {  
                                                return $er->createQueryBuilder('s');
                                            }))
                    ->add('diplomalevel', 'entity', array(
                                            'label' => 'DiplomaLevel',
                                            'property' => 'libel',
                                            'class' =>'monsite\\UserBundle\\Entity\\DiplomaLevel',
                                            'query_builder' => function(EntityRepository $er) 
                                            {  
                                                return $er->createQueryBuilder('d');
                                            }))
                    ->add('association', 'entity', array(
                                            'label' => 'association',
                                            'property' => 'name',
                                            'class' =>'monsite\\UserBundle\\Entity\\Association',
                                            'query_builder' => function(EntityRepository $er) 
                                            {  
                                                return $er->createQueryBuilder('d');
                                            }));
     
        }
     
        public function getDefaultOptions(array $options)
        {
            return array(
                'data_class' => 'monsite\UserBundle\Entity\School',
            );
        }
        public function getName() 
        {
            return 'school';
        }
    }
    Mon erreur est maintenant celle ci :

    Catchable Fatal Error: Argument 1 passed to Doctrine\Common\Collections\ArrayCollection::__construct() must be an array, object given, called in C:\wamp\www\monsite\vendor\doctrine\lib\Doctrine\ORM\UnitOfWork.php on line 426 and defined in C:\wamp\www\monsite\vendor\doctrine-common\lib\Doctrine\Common\Collections\ArrayCollection.php line 46

    La par contre je comprends pas du tout !

    L'erreur survient si je laisse la ligne suivante $this->em->updateUser($user) ici dans mon Handler :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
       protected function onSuccess(UserInterface $user)
        {
            var_dump($user);
            $this->em->updateUser($user);
        }

  16. #16
    Membre confirmé
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Avril 2012
    Messages
    73
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 34
    Localisation : France, Yvelines (Île de France)

    Informations professionnelles :
    Activité : Développeur informatique
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Avril 2012
    Messages : 73
    Par défaut
    Essaye de faire ce test :
    Récupère une entité de type User dans la base de données, affiche la.
    Récupère une entité via ton formulaire, affiche la.

    Vérifie si les deux sont bien similaire, si les types sont bien les mêmes.

  17. #17
    Membre confirmé
    Profil pro
    Étudiant
    Inscrit en
    Avril 2009
    Messages
    96
    Détails du profil
    Informations personnelles :
    Localisation : France, Charente Maritime (Poitou Charente)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Avril 2009
    Messages : 96
    Par défaut
    Citation Envoyé par Teudjy Voir le message
    Essaye de faire ce test :
    Récupère une entité de type User dans la base de données, affiche la.
    Récupère une entité via ton formulaire, affiche la.

    Vérifie si les deux sont bien similaire, si les types sont bien les mêmes.
    Encore merci de m'aider, c'est vraiment super sympa.

    Alors, mon formulaire s'affiche de cette façon : (voir test.jpg)

    Donc là, j'ai l'utilisateur de la base de donnée qui peut modifier ses informations. Je les modifie etc... Et quand je valide le formulaire j'ai l'erreur du dessus.
    Je me demande si la fonction $this->em->updateUser($user); est bien celle a appeler, mais je n'en trouve pas d'autre. Et vu que c'est un updateUser du FOSUserBundle, est ce qu'elle met a jour mes données personnalisées (firstname, phone, ...) ?

    De plus, mon objet user n'est pas modifier :

    protected 'id' => int 34
    private 'firstname' => string 'faivre' (length=6)
    private 'lastname' => string 'sylvain' (length=7)
    private 'birthday' => null
    private 'phone' => null
    private 'civility' => null
    private 'nationality' => null
    private 'school' => null
    Images attachées Images attachées  

  18. #18
    Membre confirmé
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Avril 2012
    Messages
    73
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 34
    Localisation : France, Yvelines (Île de France)

    Informations professionnelles :
    Activité : Développeur informatique
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Avril 2012
    Messages : 73
    Par défaut
    Plusieurs choses a modifier : dans ton controlleur, lorsque tu récupère ton user, Verifie que tu envoie bien le nom et pas l'objet user.

    Ensuite pour mettre ton user a jour tu peut utiliser persist au lieu de updateUser.

    Pourquoi tes champs reste null, je ne connais pas assez bien symfony2 pour te donner une réponse sure.

  19. #19
    Membre confirmé
    Profil pro
    Étudiant
    Inscrit en
    Avril 2009
    Messages
    96
    Détails du profil
    Informations personnelles :
    Localisation : France, Charente Maritime (Poitou Charente)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Avril 2009
    Messages : 96
    Par défaut
    Citation Envoyé par Teudjy Voir le message
    Plusieurs choses a modifier : dans ton controlleur, lorsque tu récupère ton user, Verifie que tu envoie bien le nom et pas l'objet user.

    Ensuite pour mettre ton user a jour tu peut utiliser persist au lieu de updateUser.

    Pourquoi tes champs reste null, je ne connais pas assez bien symfony2 pour te donner une réponse sure.
    Alors je ne sais pas se que j'ai changer mais ça à l'aire d'allez mieux !

    J'ai ça maintenant : Catchable Fatal Error: Argument 1 passed to monsite\UserBundle\Entity\User::setBirthday() must be an instance of DateTime, null given, called in C:\wamp\www\monsite\vendor\symfony\src\Symfony\Component\Form\Util\PropertyPath.php on line 347 and defined in C:\wamp\www\monsite\src\monsite\UserBundle\Entity\User.php line 189

    Dans mon utilisateur :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
     
        public function getBirthday()
        {
            return $this->birthday;
        }
     
        public function setBirthday(\DateTime $birthday)
        {
            $this->birthday = $birthday;
        }
    Et dans mon formulaire :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
     
                    ->add('birthday', 'date', array(
                                              'input'  => 'datetime',
                                              'widget' => 'choice'))
    Tu penses que ça peut venir de là ?

  20. #20
    Membre confirmé
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Avril 2012
    Messages
    73
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 34
    Localisation : France, Yvelines (Île de France)

    Informations professionnelles :
    Activité : Développeur informatique
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Avril 2012
    Messages : 73
    Par défaut
    Cela viens de deux endroit différent :
    - le champ birthday n'est pas rempli dans ton formulaire
    - le fait de préciser quelle classe la méthode setBirthday empêche de pouvoir lui envoyer une valeur null.

    J'ai vu dans ton code que ce champ peut être null.
    Je te propose donc deux solution :
    - soit tu enleve le \DateTime (ce n'est pas ce que je choisirai)
    - tu rajoute ' = null' derrière $birthday dans la déclaration de la méthode.

    Il existe peut-etre une autre solution mais je n'y ai pas encore pensé, sache en tout cas que tu peux faire la vérification de l'objet dans la méthode grâce à instanceof

Discussions similaires

  1. Réponses: 1
    Dernier message: 20/05/2015, 02h38
  2. Réponses: 0
    Dernier message: 14/08/2013, 16h29
  3. Chargement des données pour un utilisateur précis
    Par Lipolipo dans le forum W4 Express
    Réponses: 4
    Dernier message: 08/05/2012, 16h54
  4. interdire acces base donnée pour un utilisateur reseau
    Par jalalnet dans le forum MS SQL Server
    Réponses: 4
    Dernier message: 15/03/2012, 17h17
  5. [PHPMyAdmin] Accès base de donnée pour utilisateur
    Par nicodeme dans le forum Outils
    Réponses: 2
    Dernier message: 04/03/2006, 02h10

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