I have noticed that setting the value for $form_state['storage'] variable in the form builder function causes the form elements to be rendered with an incremental id

eg.

If I set a variable $form_state['storage']['somevariable']='xxx' in the form builder the in the output I have noticed that forms elements are rendered with ids incremented to value 1 like:

<input type="text" maxlength="10" name="date" id="edit-date-1" size="10" >
<input type="hidden" name="form_id" id="edit-alogbook-mainform-1" value="alogbook_mainform"  />
<input type="submit" name="op" id="edit-submit-1" value="Submit"  class="form-submit" />

This makes it difficult to access these elements with javascript/ jqeury.

This does not happen if the same formstate variable was set in submit function.

I was under the impression that the variable $form_state['storage'] is a convenient place to store variable in forms which otherwise we have to store as hidden elements.

From the form.ince file http://api.drupal.org/api/file/includes/form.inc/6/source I can see that this happens to ensure form_ids are unique.

// Ensure IDs are unique. The first occurrence is held but left alone.
// Subsequent occurrences get a number appended to them. This incrementing
// will almost certainly break code that relies on explicit HTML IDs in
// forms that appear more than once on the page, but the alternative is
// outputting duplicate IDs, which would break JS code and XHTML
// validity anyways. For now, it's an acceptable stopgap solution.

But I can't understand why this should happen in my case. Please let me know if there is a way to set formstate variables without this happening ?

Comments

gpk’s picture

I would just try using $form['storage'] and set the element type to value.

gpk
----
www.alexoria.co.uk

ponkarthik’s picture

Thats what I tried and used the id with the incremental number in jquery(edit-fieldname-1), but on the second step in a multistep form the form element id reverts to one without the incremental number (edit-fieldname) - I think this is because in the second step the $form['storage'] variable is set in the submit function.

Thus the form element ids change from one step to the subsequent step.

gpk’s picture

$form or $form_state ... ??? In your original post you said you'd used the latter.

By the time you get to the submit routine it is maybe safe to use $form_state

gpk
----
www.alexoria.co.uk

ponkarthik’s picture

Sorry in the previous post I meant $form_state['storage']