I need to pass an additional var into my custom validation function, I came up with something like this:

$form['title'] = array(
  '#type' => 'textfield',
  '#title' => t('Subject'),
  '#default_value' => $node->title,
  '#size' => 60,
  '#maxlength' => 128,
  '#required' => TRUE,
  '#element_validate' => array('my_validation_function'),
  '#my_var' => 'var_i_want_passed',
);

It works but it feels DIRTY...

Is this safe or is there a better way?

(I'd like to avoid passing vars through $form_state['my_arrrrgh_and_whatnot'].)

Comments

jaypan’s picture

Passing a variable through with the $form like that is fine.

Contact me to contract me for D7 -> D10/11 migrations.

Web Assistant’s picture

Although that would work, I agree that's a dirty way of doing it.

I believe it's the Drupal way to pass variables through $form_state. All elements of $form_state are persisted, and people usually like to use $form_state['storage']. So in your case it would be:

<?php
$form_state['storage']['my_var'] = 'var_i_want_passed';
?>

The docs say:

storage: $form_state['storage'] is not a special key, and no specific support is provided for it in the Form API. By tradition it was the location where application-specific data was stored for communication between the submit, validation, and form builder functions, especially in a multi-step-style form. Form implementations may use any key(s) within $form_state (other than the keys listed here and other reserved ones used by Form API internals) for this kind of storage. The recommended way to ensure that the chosen key doesn't conflict with ones used by the Form API or other modules is to use the module name as the key name or a prefix for the key name. For example, the Node module uses $form_state['node'] in node editing forms to store information about the node being edited, and this information stays available across successive clicks of the "Preview" button as well as when the "Save" button is finally clicked.

Can I ask why you want to avoid this way of doing it?

saysilence’s picture

Thank you all for your answers.

as why i would want to avoid using $form_state is simplicty. I can define my vars in the same place where i define the function (no scroling back and forth needed between the form element and $form_state['def..'] )
plus in the validation function i can quickly access my var by doing $element['#my_var'] without the need of going through $form_state['something_something']['nested']['nested']['nested'][...]

call it the rule of lazyness.