Given that in PHP5 objects are said to be passed by reference automatically, are there reasons why one must not pass an object through forms ('programmatically')? I hope to create acceptable persistence through using $form_state
for use with AJAX or form submit handlers. I've tried the following and it works (but I don't want to be doing something in poor practice/ that might get blocked).
$foo = new stdClass();
$foo->bar = 'foobar';
$form['foo-bar'] = array(
'#type' => 'value',
'#value' => $foo,
);
Which then appears in $form_state when the following element triggers an AJAX request
$form['numbers_required'] = array(
'#type' => 'textfield',
'#title' => t('Numbers needed'),
'#ajax' => array(
'callback' => 'numbers_required_callback',
'wrapper' => 'numbers_remaining',
),
);
Furthermore, the following passage from the drupal_build_form() documentation suggests I might have to set the form 'cache' property to TRUE. Perhaps for others this is the case if they aren't using an AJAX callback. Given that I am, I assume I can ignore this, but thought others might find it useful to know.
cache: If set to TRUE the original, unprocessed form structure will be cached, which allows the entire form to be rebuilt from cache. A typical form workflow involves two page requests; first, a form is built and rendered for the user to fill in. Then, the user fills the form in and submits it, triggering a second page request in which the form must be built and processed. By default, $form and $form_state are built from scratch during each of these page requests. Often, it is necessary or desired to persist the $form and $form_state variables from the initial page request to the one that processes the submission. 'cache' can be set to TRUE to do this. A prominent example is an Ajax-enabled form, in which ajax_process_form() enables form caching for all forms that include an element with the #ajax property. (The Ajax handler has no way to build the form itself, so must rely on the cached version.) Note that the persistence of $form and $form_state happens automatically for (multi-step) forms having the 'rebuild' flag set, regardless of the value for 'cache'.