0

How do I pass additional values to #element_validate so they can be used for validation?

I'm using hook_form_alter() and Drupal 7.

//Example 1
function my_validation_function($form, &$form_state) {
    //Validation Code
}

I would like to use:

//Example 2
function my_validation_function($form, &$form_state, $additional_values) {
    //Validation Code with access to $additional_values
}

This works for example 1:

$form['field']['#element_validate'] = array('my_validation_function');

How do I pass $additional_values to example 2 using $form['field']['#element_validate']

3
  • If you provide a little more context of what you are looking to accomplish (any why), you will likely get some better answers.
    – mpdonadio
    Commented Sep 22, 2011 at 1:52
  • All the values available to hook_form_alter will be available to validate function if i am not wrong. So I do not understand what kind of values you need to pass from hook_form_alter to validation function. Commented Sep 22, 2011 at 2:03
  • Modified the original question. It's a syntax question more than a validation question really. I'm just not sure how to pass additional variables to a callback using #element_validate
    – Citricguy
    Commented Sep 22, 2011 at 2:36

3 Answers 3

4
function where_ever_extra_data_originates_from() {
  $extra_data_to_pass_on_stored_here = &drupal_static(__FUNCTION__);
  $extra_data_to_pass_on_stored_here = $actual_extra_data
}

function my_validation_function($form, &$form_state) {
  //Here's our extra stuff now
  $extra_data = &drupal_static(where_ever_extra_data_originates_from);
}
2
  • 2
    This is a MUCH better answer :-)
    – Chapabu
    Commented Feb 17, 2012 at 11:46
  • Agreed, I too have learned a better way - thank you.
    – DeeZone
    Commented Jun 5, 2012 at 18:30
0

You can add whatever extra elements to the $form_state array in your alter function and read them out in the validate function, like so:

function my_form_alter(&$form, &$form_state, $form_id) { 
  $form_state['additional_value'] = 'the extra value';
  $form['#validate'][] = 'my_validation_function';
}

function my_validation_function($form, &$form_state) {
  //Validation Code
  $extra = $form_state['additional_value']
}
-1

You can't alter(add to) the number of parameters that are passed to a hook function. You could declare the variable that you want passed into the function as "global" -> Variable scope when you define it and again in the function which would give you access to the value.

1
  • 2
    Sorry, but I simply must downvote an answer that advocates a global.
    – Letharion
    Commented Feb 17, 2012 at 10:46

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.