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

EDI, CMS, Outils, Scripts et API PHP Discussion :

faire appel à du javascript dans un formulaire : Drupal 8


Sujet :

EDI, CMS, Outils, Scripts et API PHP

  1. #1
    Membre habitué Avatar de legrandse
    Homme Profil pro
    Responsable de service informatique
    Inscrit en
    Décembre 2010
    Messages
    350
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Belgique

    Informations professionnelles :
    Activité : Responsable de service informatique

    Informations forums :
    Inscription : Décembre 2010
    Messages : 350
    Points : 149
    Points
    149
    Par défaut faire appel à du javascript dans un formulaire : Drupal 8
    Bonjour à tous,

    Je parcours le web pour trouver des info pour intégrer du javascript dans la création d'un formulaire.

    A la base j'ai crée un module avec différents champs de formulaire dont 2 qui font appel à un datepicker.

    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
    <?php
     
    namespace Drupal\MyForm\Form;
     
    use \Drupal\Core\Form\FormStateInterface;
    use \Drupal\Core\Form\FormBase;
     
    class FormSubscribev2 extends FormBase{
     
    	public function getFormId(){
    		return'subscribe_form';
     
    	}
     
    	/**
       * Form constructor.
       *
       * @param array $form
       *   An associative array containing the structure of the form.
       * @param \Drupal\Core\Form\FormStateInterface $form_state
       *   The current state of the form.
       *
       * @return array
       *   The form structure.
       */
     
    	public function buildForm(array $form, FormStateInterface $form_state){
     
     
    		$form['arrival']=array(
    		'#type'=>'date',
    		'#title'=>$this
    			->t('Arrival'),
     
    		);
    		$form['departure']=array(
    		'#type'=>'date',
    		'#title'=>$this
    			->t('Departure'),
     
    		);
    		$form['email']=array(
    		'#type'=>'email',
    		'#title'=>$this->t('email'),
     
    		);
     
     
    		$form['name']=array(
    		'#type'=>'textfield',
    		'#title'=>$this->t('Nom'),
     
    		);
     
    		$form['firstname']=array(
    		'#type'=>'textfield',
    		'#title'=>$this->t('Prenom'),
     
    		);
     
    		$form['street']=array(
    		'#type'=>'textfield',
    		'#title'=>$this->t('Street'),
     
    		);
    		$form['no']=array(
    		'#type'=>'textfield',
    		'#title'=>$this->t('Nr'),
     
    		);
    		$form['postcode']=array(
    		'#type'=>'textfield',
    		'#title'=>$this->t('Post code'),
     
    		);
     
    		$form['place']=array(
    		'#type'=>'textfield',
    		'#title'=>$this->t('Place'),
     
    		);
     
     
    		$form['country'] = [
    		  '#type' => 'select',
    		  '#title' => $this
    		    ->t('Country'),
    		  '#options' => [
    		    'BE' => $this
    		      ->t('BE'),
    		    'NL' => $this
    		      ->t('NL'),
    		    'LU' => $this
    		      ->t('LU'),
    		    'FR' => $this
    		      ->t('FR'),
    		    'DE' => $this
    		      ->t('DE'),
    		    'GB' => $this
    		      ->t('GB'),
    		  ],
    		];
     
     
     
     
    		$form['lang'] = [
    		  '#type' => 'select',
    		  '#title' => $this
    		    ->t('Language'),
    		  '#options' => [
    		    'FR' => $this
    		      ->t('FR'),
    		    'NL' => $this
    		      ->t('NL'),
    		    'DE' => $this
    		      ->t('DE'),
    		    'EN' => $this
    		      ->t('EN'),
     
    		  ],
    		];
     
     
    		$form['phone']=array(
    		'#type'=>'textfield',
    		'#title'=>$this->t('Phone'),
    		);
     
    		 $form['save'] = array(
          '#type' => 'submit',
          '#value' => $this
            ->t('Save'),
        );
     
     
    		 return $form;
     
    		} 
     
     
    		public function validateForm(array &$form, FormStateInterface $form_state) {
     
     
    		if(empty($form_state->getValue('name'))) {
          $form_state->setErrorByName('name',$this->t('Veuillez entrer votre nom !')); 
       }
       else if(empty($form_state->getValue('arrival'))) {
          $form_state->setErrorByName('arrival',$this->t('Veuillez entrer une date d\'arrivée !')); 
       }
       else if(empty($form_state->getValue('departure'))) {
           $form_state->setErrorByName('departure',$this->t('Veuillez entrer une date de retour !')); 
       }
       else if(empty($form_state->getValue('firstname'))) {
          $form_state->setErrorByName('firstname',$this->t('Veuillez entrer votre prénom !')); 
       }
       else if(empty($form_state->getValue('arrival'))) {
           $form_state->setErrorByName('arrival',$this->t('Veuillez entrer une date d\'arrivée !')); 
       }
       else if(empty($form_state->getValue('departure'))) {
          $form_state->setErrorByName('departure',$this->t('Veuillez entrer une date de départ !')); 
       }
       else if(empty($form_state->getValue('street'))) {
          $form_state->setErrorByName('street',$this->t('Veuillez entrer votre rue !')); 
       }
       else if(empty($form_state->getValue('no'))) {
           $form_state->setErrorByName('no',$this->t('Veuillez entrer votre n° de rue !')); 
       }
       else if(empty($form_state->getValue('postcode'))) {
          $form_state->setErrorByName('postcode',$this->t('Veuillez entrer votre code postal !')); 
       }
       else if(empty($form_state->getValue('place'))) {
          $form_state->setErrorByName('place',$this->t('Veuillez entrer votre localité !')); 
       }
     
       else if(empty($form_state->getValue('phone'))) {
          $form_state->setErrorByName('phone',$this->t('Veuillez entrer un n° de contact !')); 
       }
     
       else if(empty($form_state->getValue('email'))) {
          $form_state->setErrorByName('email',$this->t('Veuillez entrer votre email !')); 
       }
     
     
       else
       {
     
    		}
     
     
     
        // Validate submitted form data.
      }
      public function submitForm(array &$form, FormStateInterface $form_state) {
    	drupal_set_message($this->t('Nous avons bien reçu votre demande. Celle-ci sera traitée dans les plus brèfs délais'));
        // Handle submitted form data.
     
    	$fields = array(
      'email' => $form_state->getValue('email'),
      'firstname' => $form_state->getValue('firstname'),
      'name' => $form_state->getValue('name'),
      'street' => $form_state->getValue('street'),
      'no' => $form_state->getValue('no'),
      'country' => $form_state->getValue('country'),
      'postcode' => $form_state->getValue('postcode'),
      'place' => $form_state->getValue('place'),
      'lang' => $form_state->getValue('lang'),
      'phone' => $form_state->getValue('phone'),
    );
    \Drupal::database()
      ->insert('booking_customer')
      ->fields($fields)
      ->execute(); 
     
     
     
     
      } 
     
     
     
     
    }
     
    ?>
    Jusque là rien de compliqué.

    Mais là où je coince c'est que le datepicker doit être customisé car il doit appeler beforeShowDay qui pour sa part contient des info issu d'une BDD.

    Je ne connais pas Drupal et la POO je ne m'y fait pas mais je suis obligé de passer par là.


    Ma question est de savoir où je dois placer le php qui liste les données de la BDD pour la préparation du datepicker en l'occurence :
    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
    //affichage reservation pour datepicker
       $req = $connexion->prepare("SELECT id,arrival,departure,customer FROM booking WHERE id_house = :id_house ");
       $req ->BindParam(":id_house",$id_house);     
       $req->execute();	
    		$activeDays = array();
    		$arrayArrival = array();
    		$arrayDeparture = array();
     
            while($d = $req->fetch(PDO::FETCH_ASSOC)){
                $debut = strtotime($d['arrival']);
    			$fin = strtotime($d['departure']);
    			$cursor = $debut; // On cree un curseur qui passera pas tous les jours de l'evenement
            	while ($cursor <= $fin) { // On parcourt tous les jours de la plage de l'evenement
     
    			$activeDays[] = date('Y-n-j',$cursor);
                $cursor += 86400; // On ajoute un journee pour passer au jour suivant
     
    		  }
    			$arrayArrival[] = date('Y-n-j',$debut);
    			$arrayDeparture[] = date('Y-n-j',$fin);
     
     
     
            }


    et mon javascript qui affiche le datepicker customisé.
    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
    <script>
      var activeDays = <?php echo json_encode($activeDays); ?>;
      //var activeDays = ["7-6-2018", "7-7-2018", "7-8-2018", "7-12-2018", "7-13-2018", "7-14-2018"]; 
      var arrival = <?php echo json_encode($arrayArrival); ?>;
      //var arrival = ["7-6-2018", "7-12-2018"];
      var departure = <?php echo json_encode($arrayDeparture); ?>;
     //var departure = ["2018-10-18", "2018-10-11"];
     
     
     
      $( function() {
        var dateFormat = "dd/mm/yy",
          from = $( "#from" )
            .datepicker({
    		  firstDay: 1,	
              dayNamesMin: [ "Di", "Lu", "Ma", "Me", "Je", "Ve", "Sa" ],
    		  monthNames: [ "Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Aout", "Septembre", "Octobre", "Novembre", "Decembre" ],
    		  monthNamesShort: [ "Jan", "Fév", "Mar", "Avr", "Mai", "Juin", "Juil", "Aout", "Sep", "Oct", "Nov", "Déc" ],
    		  dateFormat : "dd/mm/yy",
              changeMonth: true,
              numberOfMonths: 3,
    		  beforeShowDay: function(date) {
                var events = [true,''];
                var m = date.getMonth();
    			var d = date.getDate();
    			var y = date.getFullYear();
    			var currentdate = y + '-' + (m+1) + '-' + d ;
                var n = [];
                departure.forEach(function(item){
      		    n.push((new Date(item)).getDay());
    	        });
     
     
    			if ( activeDays.indexOf(currentdate)  > -1)  
                {
                    events = [true,'isActived'];
    			}
     
    			if ( arrival.indexOf(currentdate)  > -1) 
    			{
                    events = [true,'isActivedArrival'];
    			}
    			if ( departure.indexOf(currentdate)  > -1) 
    			{
                    events = [true,'isActivedDeparture'];
    			}
                if (departure.indexOf(currentdate)  > -1 && n.indexOf(0) > -1)
    			{
    				events = [true, 'isActivedDepartureSun'];
    			}
     
    			if ( arrival.indexOf(currentdate) > -1 && departure.indexOf(currentdate) >-1) 
    			{
                    events = [true,'isActivedEqual'];
    			}
     
     
     
                return events;
            }
     
     
     
            })
            .on( "change", function() {
              to.datepicker( "option", "minDate", getDate( this ) );
            }),
          to = $( "#to" ).datepicker({
    		firstDay: 1,  
            dayNamesMin: [ "Di", "Lu", "Ma", "Me", "Je", "Ve", "Sa" ],
    		  monthNames: [ "Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Aout", "Septembre", "Octobre", "Novembre", "Decembre" ],
    		  monthNamesShort: [ "Jan", "Fév", "Mar", "Avr", "Mai", "Juin", "Juil", "Aout", "Sep", "Oct", "Nov", "Déc" ],
    		dateFormat : "dd/mm/yy",
            changeMonth: true,
            numberOfMonths: 3,
    		beforeShowDay: function(date) {
                var events = [true,''];
                var m = date.getMonth();
    			var d = date.getDate();
    			var y = date.getFullYear();
    			var currentdate = y + '-' + (m+1) + '-' + d ;
                var n = [];
                departure.forEach(function(item){
      		    n.push((new Date(item)).getDay());
    	        });
     
    			//var sun = getDay(currentdate);		
     
    			if ( activeDays.indexOf(currentdate)  > -1)  
                {
                    events = [true,'isActived'];
    			}
     
    			if ( arrival.indexOf(currentdate)  > -1) 
    			{
                    events = [true,'isActivedArrival'];
    			}
    			if ( departure.indexOf(currentdate)  > -1) 
    			{
                    events = [true,'isActivedDeparture'];
    			}
                if (departure.indexOf(currentdate)  > -1 && n.indexOf(0) > -1)
    			{
    				events = [true, 'isActivedDepartureSun'];
    			}
     
    			if ( arrival.indexOf(currentdate) > -1 && departure.indexOf(currentdate) >-1) 
    			{
                    events = [true,'isActivedEqual'];
    			}
     
                return events;
            }
     
     
          })
          .on( "change", function() {
            from.datepicker( "option", "maxDate", getDate( this ) );
          });
     
        function getDate( element ) {
          var date;
          try {
            date = $.datepicker.parseDate( dateFormat, element.value );
          } catch( error ) {
            date = null;
          }
     
          return date;
        }
      } );
      </script>



    Merci pour l'aide

  2. #2
    Modérateur

    Avatar de MaitrePylos
    Homme Profil pro
    DBA
    Inscrit en
    Juin 2005
    Messages
    5 496
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 51
    Localisation : Belgique

    Informations professionnelles :
    Activité : DBA
    Secteur : Service public

    Informations forums :
    Inscription : Juin 2005
    Messages : 5 496
    Points : 12 596
    Points
    12 596
    Par défaut
    Bonjour,

    Je n'ai pas encore eu l'occasion de travailler sur D8.

    Mais bon, j'imagine qu'a à un moment vous devez instancier ce formulaire dans une vue, via un controller ?

    un truc du genre


    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
     
     
    $form = new FormSubscribev2();
     
    echo $form->build(param);
    dans ce cas pourquoi ne pas créer des attribut et faire un getter un peu comme ceci :

    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
     
     
    class FormSubscribev2 extends FormBase{
     
    public $activeDays = [];
    public $arrayArrival = [];
    public $arrayDeparture [];
     
     
    public function getDatePicker(){
     
       $req = $connexion->prepare("SELECT id,arrival,departure,customer FROM booking WHERE id_house = :id_house ");
       $req ->BindParam(":id_house",$id_house);     
       $req->execute();	
     
            while($d = $req->fetch(PDO::FETCH_ASSOC)){
                $debut = strtotime($d['arrival']);
    			$fin = strtotime($d['departure']);
    			$cursor = $debut; // On cree un curseur qui passera pas tous les jours de l'evenement
            	while ($cursor <= $fin) { // On parcourt tous les jours de la plage de l'evenement
     
    			$this->activeDays[] = date('Y-n-j',$cursor);
                $cursor += 86400; // On ajoute un journee pour passer au jour suivant
     
    		  }
    			$this->arrayArrival[] = date('Y-n-j',$debut);
    			$this->arrayDeparture[] = date('Y-n-j',$fin);
     
     
     
            }
    }
     
     
    ..... reste du code
     
    }

    ensuite dans la vue

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
     
     
    $form->getDatePicker();
     
     
     var activeDays = <?php echo json_encode($form->activeDays); ?>;
      //var activeDays = ["7-6-2018", "7-7-2018", "7-8-2018", "7-12-2018", "7-13-2018", "7-14-2018"]; 
      var arrival = <?php echo json_encode($form->arrayArrival); ?>;
      //var arrival = ["7-6-2018", "7-12-2018"];
      var departure = <?php echo json_encode($form->arrayDeparture); ?>;
     //var departure = ["2018-10-18", "2018-10-11"];

    Après je maîtrise pas D8 et j'ai peut-être tout faux....mais cela me semble une piste

  3. #3
    Membre habitué Avatar de legrandse
    Homme Profil pro
    Responsable de service informatique
    Inscrit en
    Décembre 2010
    Messages
    350
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Belgique

    Informations professionnelles :
    Activité : Responsable de service informatique

    Informations forums :
    Inscription : Décembre 2010
    Messages : 350
    Points : 149
    Points
    149
    Par défaut
    merci pour tes conseils.

    Je ferais qques tests.

    Pour le moment je lis la doc. J'ai mal au crâne

Discussions similaires

  1. du javascript dans un formulaire appelé par ajax
    Par kaking dans le forum Général JavaScript
    Réponses: 6
    Dernier message: 17/07/2009, 11h49
  2. [PHP-JS] lien PHP/javascript dans un formulaire
    Par Hayabusa dans le forum Langage
    Réponses: 1
    Dernier message: 10/07/2006, 00h37
  3. Réponses: 6
    Dernier message: 28/06/2006, 15h01
  4. Javascript dans un formulaire type echo"<form action
    Par coyoteuch dans le forum Général JavaScript
    Réponses: 2
    Dernier message: 12/06/2006, 11h20
  5. Javascript dans un formulaire
    Par MagicManu dans le forum Général JavaScript
    Réponses: 9
    Dernier message: 26/10/2004, 11h25

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