I want to pass a variable created with Javascript to $form_state so that I can use this variable in the form_submit function.

In an ajaxified form I can use:

Drupal.ajax[ajax_el].options.data._my_vars = JSON.stringify(js_object);

But how can I accomplish it in a non ajax form? Is there another possibility than using a hidden field? It might be possible to pass it to a field with #access => FALSE?

I would welcome every advice. Many thanks!


  • You can #attach JS settings. This is how the #states data get passed during Ajax calls.
    – AKS
    Dec 14, 2014 at 15:54
  • Thanks for your answer. In which way I have to attach the settings? I just know the the way to pass a variable to the client and not vice versa: $form['#attached']['js']['my_key'] = array( 'data' => array('my_key' => $settings), 'type' => 'setting' );. How can I pass a variable generated with JS to the server with the settings?
    – Daniel
    Dec 14, 2014 at 16:28
  • Oops sorry I though about this the other way.
    – AKS
    Dec 14, 2014 at 16:30
  • No problem! But you probably don't have another idea for my problem? :)
    – Daniel
    Dec 14, 2014 at 16:47
  • 1
    You could use a hidden field, which is JS and css independent. You can use javascript place a cookie, which will be submitted with every http request thereafter until cleared. Hidden fields seems to be the way to go.
    – AKS
    Dec 14, 2014 at 16:50

1 Answer 1


Create a field for that variable, like this:

$form['_my_vars'] = array('#type' => 'hidden', '#default_value' => $_my_vars);

Whenever you are changing variable, update field's value.

Do not use

'#access' => FALSE

The Form API Reference clarifies it:

when FALSE, the element is not rendered and the user submitted value is not taken into consideration.

  • Hi thanks for your answer! I already worked it out with the help of AyeshK. See the comments of my question. But nevertheless, thanks!
    – Daniel
    Dec 18, 2014 at 11:30
  • @user3083978 Comments may get purged without notice. If AyeshK wrote this first, I can delete my answer. But only after his answer is posted as actual answer.
    – Mołot
    Dec 18, 2014 at 11:32

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.