Drupal - How to validate a field value programatically in Drupal 8?

The $form_state now become a classed object as documented here

You can use getValue() to get field value instead of converting it into an array

$form_state->getValue('name');

instead of:

$form_state = get_object_vars($form_state);
$name = $form_state['values']['name']);

Same thing for form_set_value.

And form_set_error() became $form_state->setErrorByName().


The form_set_error() has been dropped in favor of the following $form_state class methods:

$form_state->setError($element, $message);
$form_state->setErrorByName($element, $message);

So the code would look like:

use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_form_alter().
 */
function mymodule_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  // Use this to find out about the current form id.
  drupal_set_message('Form ID: ' . $form_id);
}

/**
 * Implements hook_form_FORM_ID_alter() for the FORM_ID() form.
 */
function mymodule_form_FORM_ID_alter(&$form, FormStateInterface $form_state, $form_id) {
  $form['#validate'][] = '_mymodule_form_validate';
}

/**
 * Validates submission values in the FORM_ID() form.
 */
function _mymodule_form_validate(array &$form, FormStateInterface $form_state) {
  $values = $form_state->getValue('field_myfield');
  foreach ($values as $value) {
    $plain_value = is_array($value) ? current($value) : NULL;
    if (empty($plain_value)) {
      $form_state->setErrorByName('field_myfield', t('Please enter a value!'));
    }
  }
}

Tags:

Forms

Users

8