3

In Drupal 6, I have a custom form validation function, where:

  • I copy the value from field A to field B, if field B is empty.
  • I call form_set_error() when the field B contains more than X characters.

Validation works fine, and the error is set. The problem is that the value in field B is not retained when the form is rebuilt: field B remains empty. I want to keep the value in field B after validation (when the error is set) to make it easy for users to edit it down to the right length.

My validation function looks like this:

function myform_validate($form, &$form_state) {
  if (empty($form_state['values']['field_b']['0']['value'])) {
        $form_state['values']['field_b']['0']['value'] = $form_state['values']['field_a']['0']['value']; 
      }
      if (strlen($form_state['values']['field_b']['0']['value']) > 260) {
        form_set_error('field_b', 'Text in field b is too long');
      }
    }
  }
}

Any suggestions on how to retain the value in field B when the form is rebuilt?

1 Answer 1

4

If you want to set a form value from within your validation callback you'll need to use something like form_set_value. Values that are assigned directly in the manner shown above will not be retained, but that function should do the trick! It's specifically intended for this purpose - setting a form value during the validation phase.

For example:

function myform_validate($form, &$form_state) {
  if (empty($form_state['values']['field_b'])) {
        // Note that the $form array - not $form_state - is used in the first parameter.
        // The second parameter is the value you are setting.
        // Third just pass the $form_state array itself, which will be altered by form_set_vaue().
        form_set_value($form['field_b'], $form_state['values']['field_a'], $form_state); 
      }
      if (strlen($form_state['values']['field_b']) > 260) {
        form_set_error('field_b', 'Text in field b is too long');
      }
    }
  }
}
2
  • Thanks! form_set_value() is what I was looking for. I'm struggling to find the right value to replace, as it's part of a (CCK fieldset) array. I understand I have to pass in an '#parents' array, but can't seem to find the correct key/array path. The field itself is a textfield that's part of a fieldset, so I've tried mulitple variations of array('#parents' => array('fieldset', 'field', '0', 'value'). Anything obvious I'm doing wrong here?
    – brunodbo
    Commented Sep 9, 2011 at 17:45
  • Answering my own question: form_set_value(array('#parents' => array('field_a', '0', 'value')), $form_state['values']['field_b'][0]['value'], $form_state); seems the right way to get to the field's value.
    – brunodbo
    Commented Sep 9, 2011 at 18:24

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.