Created
June 1, 2020 14:51
-
-
Save lcube45/e8ea125a4de86809d681d43d66520f0c to your computer and use it in GitHub Desktop.
Drupal 8 - ajax callback & alter form
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class SimpleForm extends FormBase { | |
/** | |
* {@inheritdoc} | |
*/ | |
public function getFormId() { | |
return 'simple_form'; | |
} | |
/** | |
* {@inheritdoc} | |
*/ | |
public function buildForm(array $form, FormStateInterface $form_state) { | |
$form['referentiel'] = [ | |
'#type' => 'select', | |
'#title' => $this->t('Référentiel'), | |
'#options' => ['foot' => $this->t('foot'), 'rugby' => $this->t('rugby'), 'basket' => $this->t('basket')], | |
'#size' => 1, | |
]; | |
$form['titre'] = [ | |
'#type' => 'textfield', | |
'#title' => $this->t('titre'), | |
'#maxlength' => 64, | |
'#size' => 64, | |
'#default_value' => 'my title' | |
]; | |
$form['objet'] = [ | |
'#type' => 'textfield', | |
'#title' => $this->t('objet'), | |
'#maxlength' => 64, | |
'#size' => 64, | |
]; | |
$form['submit'] = [ | |
'#type' => 'submit', | |
'#value' => $this->t('Submit'), | |
]; | |
return $form; | |
} | |
/** | |
* {@inheritdoc} | |
*/ | |
public function validateForm(array &$form, FormStateInterface $form_state) { | |
parent::validateForm($form, $form_state); | |
} | |
/** | |
* {@inheritdoc} | |
*/ | |
public function submitForm(array &$form, FormStateInterface $form_state) { | |
// Display result. | |
foreach ($form_state->getValues() as $key => $value) { | |
drupal_set_message($key . ': ' . $value); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// example.module | |
/** | |
* Implements hook_form_FORM_ID_alter(). | |
*/ | |
function mymodule_simple_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) { | |
$form['#prefix'] = '<div id="my">'; | |
$form['#suffix'] = '</div>'; | |
$form['referentiel']['#ajax'] = array( | |
'callback' => 'myCallback', | |
'event' => 'change', | |
'wrapper' => 'my', | |
); | |
} | |
function myCallback(array &$form, FormStateInterface $form_state) { | |
$method = $form_state->getValue('referentiel'); | |
$form['titre']['#value'] = $method; | |
$form['objet']['#value'] = $method; | |
return $form; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment