1

The element's name property is declared in the $form array, at the very end of the array tree. For example, if an element in the form tree was structured like this: $form['account_settings']['username'] ?>

...then that element's name property is 'username'--this is the key it will be available under in $form_state['values'], in your validation and submission functions, as the form code flattens the array in this fashion before it passes the key/value pairs. NOTE: if you wish to have the full tree structure passed to $form_state['values'], this is possible, and will be discussed later.

-Source

So, for example, if you have this:

$form['details']['admin'] = array(
    '#type' => 'checkbox',
    '#title' => t('Only admin can view'),
    '#default_value' => variable_get('admin', 0),
  );

You see that you'd be using variable_get('admin', 0);

So what's to prevent naming collisions? Say you have another setting:

$form['more_details']['admin'] = array(
        '#type' => 'checkbox',
        '#title' => t('Only admin can view'),
        '#default_value' => variable_get('admin', 0),
      );

If anyone has a clear explanation as to how this "flattening" works, that'd be great.

1

While it's good practice to use unique field names in your form, you can use the #tree property to preserve the group nesting of parent -> same child name there.

$form['#tree'] = TRUE;

That will preserve the nesting of group -> field values in the form $form_state['values'] so instead of being flattened it will be

$form_state['values']['details']['admin'] = 'foo';

and

$form_state['values']['more_details']['admin'] = 'bar';
  • True, but when it comes to using variable_get after you save the form, what will the difference in variable names be? – AlxVallejo Oct 15 '13 at 13:49
  • @AlxVallejo, the variable will be an array with nested values. – David Thomas Aug 22 '16 at 22:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.