Skip to content

Instantly share code, notes, and snippets.

@jez500
Created January 8, 2018 01:06
Show Gist options
  • Save jez500/711099573e02ef4b89016490bbe44fa5 to your computer and use it in GitHub Desktop.
Save jez500/711099573e02ef4b89016490bbe44fa5 to your computer and use it in GitHub Desktop.
Drupal 8 Basic form example
<?php
namespace Drupal\my_module\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
/**
* Class TestAjaxFormSelect.
*/
class MyForm extends FormBase {
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'my_unique_form_id';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
// Get the form values.
$values = $form_state->getValues();
// Element(s).
$form['my_select'] = [
'#type' => 'select',
'#empty_value' => '',
'#empty_option' => '- Select a value -',
'#default_value' => (isset($values['my_select']) ? $values['my_select'] : ''),
'#options' => [
1 => 'One',
2 => 'Two',
3 => 'Three'
],
];
$form['submit'] = [
'#type' => 'submit',
'#value' => 'Submit my form',
];
return $form;
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
// Do something with $form_state->getValues();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment