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 :

Formulaire dynamique


Sujet :

Symfony PHP

  1. #1
    Membre à l'essai
    Homme Profil pro
    Étudiant
    Inscrit en
    Septembre 2013
    Messages
    16
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Maroc

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Septembre 2013
    Messages : 16
    Points : 15
    Points
    15
    Par défaut Formulaire dynamique
    Bonsoir ,

    Je suis debutant en symfony , et j aimerais faire deux champs de type select (ville et province ) en tel sorte que si un utilisateur choisi une province les villes correspondantes s'affichent automatique. j'ai reussi a faire ca grace un tuto https://gist.github.com/jaytaph/9640...le-account-php mais j'ai un probléme c'est que quand je choisi une province les villes correspandantes ne s'afficheront pas voici mon code :

    Le 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
    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
    <?php
     
    namespace NoxLogic\DemoBundle\Controller;
     
    use NoxLogic\DemoBundle\Entity\Account;
    use NoxLogic\DemoBundle\Form\AccountType;
    use Symfony\Bundle\FrameworkBundle\Controller\Controller;
    use Symfony\Component\HttpFoundation\JsonResponse;
    use Symfony\Component\HttpFoundation\Request;
    use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
     
    class DefaultController extends Controller
    {
     
        public function ajaxAction(Request $request) {
            if (! $request->isXmlHttpRequest()) {
                throw new NotFoundHttpException();
            }
     
            // Get the province ID
            $id = $request->query->get('province_id');
     
            $result = array();
     
            // Return a list of cities, based on the selected province
            $repo = $this->getDoctrine()->getManager()->getRepository('NoxLogicDemoBundle:City');
            $cities = $repo->findByP($id, array('name' => 'asc'));
            foreach ($cities as $city) {
                $result[$city->getName()] = $city->getId();
            }
     
            return new JsonResponse($result);
        }
     
     
        public function createAction(Request $request)
        {
            $account = new Account();
     
            // You probably want to use a service and inject it automatically. For simplicity,
            // I'm just adding it to the constructor.
            $form = $this->createForm(new AccountType($this->getDoctrine()->getManager()), $account);
     
            $form->handleRequest($request);
     
            if ($form->isValid()) {
                /* Do your stuff here */
     
                $this->getDoctrine()->getManager()->persist($account);
                $this->getDoctrine()->getManager()->flush();
            }
     
            return $this->render('NoxLogicDemoBundle:Default:index.html.twig', array('form' => $form->createView()));
        }
     
    }
    AccountType.php :

    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
    <?php
     
    namespace NoxLogic\DemoBundle\Form;
     
    use Doctrine\ORM\EntityManager;
    use NoxLogic\DemoBundle\Entity\province;
    use Symfony\Component\Form\AbstractType;
    use Symfony\Component\Form\FormBuilderInterface;
    use Symfony\Component\Form\FormEvent;
    use Symfony\Component\Form\FormEvents;
    use Symfony\Component\Form\FormInterface;
    use Symfony\Component\OptionsResolver\OptionsResolverInterface;
     
    class AccountType extends AbstractType {
     
        protected $em;
     
        function __construct(EntityManager $em)
        {
            $this->em = $em;
        }
     
     
        public function buildForm(FormBuilderInterface $builder, array $options)
        {
            // Name of the user
            $builder->add('name', 'text');
     
            /* Add additional fields... */
     
            $builder->add('save', 'submit');
     
            // Add listeners
            $builder->addEventListener(FormEvents::PRE_SET_DATA, array($this, 'onPreSetData'));
            $builder->addEventListener(FormEvents::PRE_SUBMIT, array($this, 'onPreSubmit'));
        }
     
     
        protected function addElements(FormInterface $form, Province $province = null) {
            // Remove the submit button, we will place this at the end of the form later
            $submit = $form->get('save');
            $form->remove('save');
     
     
            // Add the province element
            $form->add('province', 'entity', array(
                'data' => $province,
                'empty_value' => '-- Choose --',
                'class' => 'NoxLogicDemoBundle:Province',
                'mapped' => false)
            );
     
            // Cities are empty, unless we actually supplied a province
            $cities = array();
            if ($province) {
                // Fetch the cities from specified province
                $repo = $this->em->getRepository('NoxLogicDemoBundle:city');
                $cities = $repo->findByPovince($province, array('name' => 'asc'));
            }
     
            // Add the city element
            $form->add('city', 'entity', array(
                'empty_value' => '-- Select a province first --',
                'class' => 'NoxLogicDemoBundle:City',
                'choices' => $cities,
            ));
     
            // Add submit button again, this time, it's back at the end of the form
            $form->add($submit);
        }
     
     
        function onPreSubmit(FormEvent $event) {
            $form = $event->getForm();
            $data = $event->getData();
     
            // Note that the data is not yet hydrated into the entity.
            $province = $this->em->getRepository('NoxLogicDemoBundle:province')->find($data['province']);
            $this->addElements($form, $province);
        }
     
     
        function onPreSetData(FormEvent $event) {
            $account = $event->getData();
            $form = $event->getForm();
     
            // We might have an empty account (when we insert a new account, for instance)
            $province = $account->getCity() ? $account->getCity()->getProvince() : null;
            $this->addElements($form, $province);
        }
     
     
        public function setDefaultOptions(OptionsResolverInterface $resolver)
        {
              $resolver->setDefaults(array(
                  'data_class' => 'NoxLogic\DemoBundle\Entity\account'
              ));
        }
     
     
     
     
        public function getName()
        {
            return "account_type";
        }
     
    }
    province.php

    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
    <?php
     
    namespace NoxLogic\DemoBundle\Entity;
     
    use Doctrine\ORM\Mapping as ORM;
     
    /**
     * Province
     *
     * @ORM\Table()
     * @ORM\Entity()
     */
    class Province
    {
        /**
         * @var integer
         *
         * @ORM\Column(name="id", type="integer")
         * @ORM\Id
         * @ORM\GeneratedValue(strategy="AUTO")
         */
        private $id;
     
        /**
         * @var string
         *
         * @ORM\Column(name="name", type="string", length=255)
         */
        private $name;
     
        /**
         * @ORM\OneToMany(targetEntity="City", mappedBy="province")
         */
        protected $cities;
     
        /**
         * Constructor
         */
        public function __construct()
        {
            $this->cities = new \Doctrine\Common\Collections\ArrayCollection();
        }
     
        /**
         * Get id
         *
         * @return integer 
         */
        public function getId()
        {
            return $this->id;
        }
     
        /**
         * Set name
         *
         * @param string $name
         * @return Province
         */
        public function setName($name)
        {
            $this->name = $name;
     
            return $this;
        }
     
        /**
         * Get name
         *
         * @return string 
         */
        public function getName()
        {
            return $this->name;
        }
     
        /**
         * Add cities
         *
         * @param \NoxLogic\DemoBundle\Entity\City $cities
         * @return Province
         */
        public function addCity(\NoxLogic\DemoBundle\Entity\City $cities)
        {
            $this->cities[] = $cities;
     
            return $this;
        }
     
        /**
         * Remove cities
         *
         * @param \NoxLogic\DemoBundle\Entity\City $cities
         */
        public function removeCity(\NoxLogic\DemoBundle\Entity\City $cities)
        {
            $this->cities->removeElement($cities);
        }
     
        /**
         * Get cities
         *
         * @return \Doctrine\Common\Collections\Collection 
         */
        public function getCities()
        {
            return $this->cities;
        }
     
        function __toString() {
            return $this->getName();
        }
    }
    city.php

    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
    <?php
     
    namespace NoxLogic\DemoBundle\Entity;
     
    use Doctrine\ORM\Mapping as ORM;
     
    /**
     * City
     *
     * @ORM\Table()
     * @ORM\Entity()
     */
    class City
    {
        /**
         * @var integer
         *
         * @ORM\Column(name="id", type="integer")
         * @ORM\Id
         * @ORM\GeneratedValue(strategy="AUTO")
         */
        private $id;
     
        /**
         * @var string
         *
         * @ORM\Column(name="name", type="string", length=255)
         */
        private $name;
     
        /**
         * @ORM\ManyToOne(targetEntity="Province", inversedBy="cities")
         */
        protected $province;
     
     
     
        /**
         * Get id
         *
         * @return integer 
         */
        public function getId()
        {
            return $this->id;
        }
     
        /**
         * Set name
         *
         * @param string $name
         * @return City
         */
        public function setName($name)
        {
            $this->name = $name;
     
            return $this;
        }
     
        /**
         * Get name
         *
         * @return string 
         */
        public function getName()
        {
            return $this->name;
        }
     
        /**
         * Set province
         *
         * @param \NoxLogic\DemoBundle\Entity\Province $province
         * @return City
         */
        public function setProvince(\NoxLogic\DemoBundle\Entity\Province $province = null)
        {
            $this->province = $province;
     
            return $this;
        }
     
        /**
         * Get province
         *
         * @return \NoxLogic\DemoBundle\Entity\Province 
         */
        public function getProvince()
        {
            return $this->province;
        }
     
        function __toString() {
            return $this->getName();
        }
     
    }
    index.html.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
    <html>
    <body>
    {# Display the form #}
    {{ form(form) }}
     
     
    {# Add ajax thingie that will update the city select box #}
    <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
    <script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
     
    <script type="text/javascript">
        $(document).ready(function () {
            $('#account_type_province').change(function(){
     
               var val = $(this).val();
               $.ajax({
                    type: "POST",
                    url: "{{ url('province_ajax_call') }}?province_id=" + val,
                    success: function(data) {
     
                        // Remove current options
                        $('#account_type_city').html('');
     
                        $.each(data, function(k, v) {
     
                            $('#account_type_city').append('<option value="' + v + '">' + k + '</option>');
                        });
                    }
                });
     
                return false;
            });
        });
     
    </script>
    </body>
    </html>
    routing.yml

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    nox_logic_demo_homepage:
        path:     /hello
        defaults: { _controller: NoxLogicDemoBundle:Default:create}
    province_ajax_call:
         path:     /hello
         defaults: { _controller: NoxLogicDemoBundle:Default:ajax}

  2. #2
    Membre éprouvé
    Homme Profil pro
    Développeur Web
    Inscrit en
    Novembre 2013
    Messages
    739
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Tunisie

    Informations professionnelles :
    Activité : Développeur Web

    Informations forums :
    Inscription : Novembre 2013
    Messages : 739
    Points : 1 022
    Points
    1 022
    Par défaut
    as tu essayé de voir l'onglet 'network' en bas de navigateur ?
    Si c'est bon tu dois avoir Status 200 .

  3. #3
    Membre à l'essai
    Homme Profil pro
    Étudiant
    Inscrit en
    Septembre 2013
    Messages
    16
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Maroc

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Septembre 2013
    Messages : 16
    Points : 15
    Points
    15
    Par défaut
    Oui ca me donne en status 200

  4. #4
    Membre à l'essai
    Homme Profil pro
    Étudiant
    Inscrit en
    Septembre 2013
    Messages
    16
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Maroc

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Septembre 2013
    Messages : 16
    Points : 15
    Points
    15
    Par défaut
    ca fait 3 jours que je suis bloqué dans ce point , si quelqu'un peut m'aider svp

  5. #5
    Membre éclairé
    Homme Profil pro
    Technicien maintenance
    Inscrit en
    Août 2011
    Messages
    477
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 54
    Localisation : France

    Informations professionnelles :
    Activité : Technicien maintenance
    Secteur : Administration - Collectivité locale

    Informations forums :
    Inscription : Août 2011
    Messages : 477
    Points : 677
    Points
    677
    Par défaut
    Bonjour,

    Tu as bien un 200. C'est bien. Mais quel est le contenu de la réponse ?

Discussions similaires

  1. Validation formulaire dynamique
    Par odelayen dans le forum Général JavaScript
    Réponses: 2
    Dernier message: 31/08/2005, 17h47
  2. [JSF] Implémentation d'un formulaire dynamique
    Par Fleep dans le forum Général JavaScript
    Réponses: 2
    Dernier message: 01/03/2005, 19h00
  3. pb access formulaire dynamique
    Par jibouze dans le forum IHM
    Réponses: 3
    Dernier message: 12/01/2005, 09h39
  4. formulaire dynamique
    Par shirya dans le forum Général JavaScript
    Réponses: 4
    Dernier message: 19/10/2004, 16h13
  5. [struts]Formulaire dynamique
    Par GreenJay dans le forum Struts 1
    Réponses: 8
    Dernier message: 28/05/2004, 16h35

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