Skip to content

Instantly share code, notes, and snippets.

@anxp
Created May 1, 2019 08:41
Show Gist options
  • Save anxp/cf232e89575cfc06d898b81ce151320a to your computer and use it in GitHub Desktop.
Save anxp/cf232e89575cfc06d898b81ce151320a to your computer and use it in GitHub Desktop.
Drupal 8 features: Get a form element value VS set form error by element name
<?php
$form['#tree'] = TRUE;
$form['part_of_the_form'] = [
'#type' => 'container',
];
$form['part_of_the_form']['field_1'] = [
'#type' => 'textfield',
'#title' => 'Field-1',
];
$form['part_of_the_form']['field_2'] = [
'#type' => 'textfield',
'#title' => 'Field-2',
];
$form['part_of_the_form']['btn_submit'] = [
'#type' => 'submit',
'#value' => 'Submit this form',
];
//Get a value of form nested element (for example, text field):
$field1_value = $form_state->getValue(['part_of_the_form', 'field_1']);
//Show from error and highlight element with error we do this strange way:
$form_state->setErrorByName('part_of_the_form][field_1', 'Please, re-check Field 1.');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment