View source
<?php
namespace Drupal\form_test\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
class FormTestMachineNameValidationForm extends FormBase {
public function getFormId() {
return 'form_test_machine_name_validation_form';
}
public function buildForm(array $form, FormStateInterface $form_state) {
$form['#attributes']['novalidate'] = 'novalidate';
$form['name'] = [
'#type' => 'textfield',
'#default_value' => $form_state
->getValue('name'),
'#maxlength' => 50,
'#required' => TRUE,
'#title' => 'Name',
];
$form['id'] = [
'#type' => 'machine_name',
'#default_value' => $form_state
->get('id'),
'#maxlength' => 50,
'#required' => TRUE,
'#machine_name' => [
'exists' => [
$this,
'load',
],
'source' => [
'name',
],
],
];
$form['id2'] = [
'#type' => 'machine_name',
'#default_value' => 'duplicate',
'#maxlength' => 50,
'#required' => TRUE,
'#machine_name' => [
'exists' => [
$this,
'load',
],
'source' => [
'name',
],
],
];
$form['snack'] = [
'#type' => 'select',
'#title' => $this
->t('Select a snack'),
'#options' => [
'apple' => 'apple',
'pear' => 'pear',
'potato' => 'potato',
],
'#required' => TRUE,
'#ajax' => [
'callback' => '::buildAjaxSnackConfigureForm',
'wrapper' => 'snack-config-form',
'method' => 'replace',
'effect' => 'fade',
],
];
$form['snack_configs'] = [
'#type' => 'container',
'#attributes' => [
'id' => 'snack-config-form',
],
'#tree' => TRUE,
];
$form['submit'] = [
'#type' => 'submit',
'#value' => 'Save',
];
return $form;
}
public function buildAjaxSnackConfigureFormValidate(array $form, FormStateInterface $form_state) {
$form_state
->set('id', $form_state
->getValue('id'));
}
public function buildAjaxSnackConfigureFormSubmit(array $form, FormStateInterface $form_state) {
$form_state
->setRebuild();
}
public function buildAjaxSnackConfigureForm(array $form, FormStateInterface $form_state) {
return $form['snack_configs'];
}
public function load($machine_name) {
if (strpos($machine_name, 'duplicate') !== FALSE) {
return TRUE;
}
return FALSE;
}
public function submitForm(array &$form, FormStateInterface $form_state) {
$this
->messenger()
->addStatus('The form_test_machine_name_validation_form form has been submitted successfully.');
}
}