Hello,

I need help with this interesting formAPI problem:
I need something like this:
1. generate a random number, and display the value in the form.
2. let the user submit the form.
3. retrieve that value in the submit function.

So what I tried is to store the value in a form element:

form['random_number'] = array (
  '#type' => 'value',
  '#value' => generateRandom(),
); 

Then, in the submit function I try to do $form_state['random_number'].
But this does not seems to work. And instead of getting the original value that was displayed in the form, I get a new generated random.
This is I think because the form is being built before the validation, and overrides the value with a new random.

How can I solve this, retreiving the original random number that was used in the first building of the form?
Thanks.

Comments

nevets’s picture

You can also look at $form_state in the build function and set #value to either $generateRandom() or the value in $form_state.

ofridagan’s picture

I thought about it, and tried it.
But $form_state['values'] is empty in the build function!
Am I missing anything??

Thanks again!

nevets’s picture

You need to use a type of 'hidden' instead of 'value'.

ofridagan’s picture

Thank you so much!
I'll give that a try...
So you are saying the values of the form should generally be availble at the building phase right before the validation?

nevets’s picture

Yes, for most form element types (for example it does not apply when #type is 'value').