I'm putting together a fairly complex form with Drupal 8 (currently building on beta 7). In my validation function, I need to be able to detect whether a field, which was populated with default values, has changed.

In Drupal 7, this would have been pretty straightforward. I could dig into the form_state array and find the appropriate default_value entry and compare it to the submitted value.

But now that form_state is an encapsulated object, I don't see an obvious way to get the default value.

I know I can kluge this if I need to, by including hidden fields in the form itself with the default values. But I know that the information is in the form_state object: if I print_r form_state I can see both the old and new values--but not in any way I can figure out how to access using the methods listed in FormStateInterface.

Bottom line: in Drupal 8, how do I test whether the submitted value of a form element is the same as its default value?


3 Answers 3

public function validateForm(array $form, FormSateInterface $form_state) {
  $element = $form['elementname'];
  $default_value = isset($element['#default_value']) ? $element['#default_value'] : NULL;
  $value = $form_state->getValue($element['#parents']);
  $changed = $default_value == $value;
    if ($changed) {
    // This is stupid, it's just an example.
    $form_state->setError($element, $this->t("The value has changed."));

Okay, think I figured it out, although it seems like a bit of a kluge still.

I used the getCompleteForm() method on FormStateInterface. This gives you, as far as I can tell, the array version of FormStateInterface, so you can handle it just like you did in 7. It seems like there should be a more elegant solution, but this way seems to be working for now.


Here's how I did it, pretty similar to Ivan's solution

public function validateForm(array $form, FormStateInterface $form_state) {
  if ($form[$elementName]['#value'] == $form[$elementName]['#default_value']) {
    // It changed
  } else {
    // it didn't

Depending on what you are trying to do you can also do this on save()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.