Problem/Motivation

I was having trouble changing a value while hook_node_validate() so it repopulates the form with the new value I set through form_set_value().

to explain: I validated a form with my module using mymodule_node_validate(). when the submitted form failed a custom check, it should raise an error with form_set_error() and also use different values in some of the fields in the form. now using $form_set_value() (as suggested in the docs) does indeed change the value of the field when it passes the validation, but it does not change the repopulated field of the form.

Proposed resolution

after a lot of debugging, I have found out that drupal uses the values inside $form_state['complete form'], instead of $form_state['values'] to repopulate the form. this actually contradicts the docs and - in my humblest opinion - is not as straight forward as an API should be.

best regards,
alex.

see here for a more use case problem of this.

Comments

lmeurs’s picture

Ran into the same problem with validation on form and field level. I wanted to check a field's value and clean it up a bit. Eventually I ended up with setting the new value in 3 places like this:

function myform_validate_myfield($element , &$form_state) {
  // get $element's value
  $old_value = $new_value = $form_state['input']['myfield'];

  /* some checking and cleaning of $new_value */

  // if value has changed, set the new value
  if ($old_value != $new_value) {
    // $form_state['input'] is used for repopulating field value's in case of NO validation errors
    $form_state['input']['myfield'] = $new_value;

    // $form_state['complete form'] is used for repopulating field value's in case of validation errors
    $form_state['complete form']['myfield']['#value'] = $new_value;

    // values set by form_set_value() are used as field value's on form submition
    form_set_value($element , $new_value , $form_state);
  }
}

I know this is a workaround and not a fix, but so far it seems to be working for me.

Cheers, Laurens

Version: 7.10 » 7.x-dev

Core issues are now filed against the dev versions where changes will be made. Document the specific release you are using in your issue comment. More information about choosing a version.

Status: Active » Closed (outdated)

Automatically closed because Drupal 7 security and bugfix support has ended as of 5 January 2025. If the issue verifiably applies to later versions, please reopen with details and update the version.