How to place multiple form elements from a loop I have a table that will have multiple table rows that are generated dynamically using a foreach loop. In these rows will be textfields using the Drupal forms API.

Example:

$f = '&lt;table&gt;';
$f .= '&lt;tr&gt;&lt;td&gt;Something...&lt;/td&gt;&lt;/tr&gt;';

foreach($somethingAwesome as $val){
    $f .= '&lt;tr&gt;&lt;td&gt;';

    $form['blah'][$val] = array(
        '#type' =&gt; 'textfield',
    );

    $f .= '&lt;/td&gt;&lt;/tr&gt;';
}

$f .= '&lt;tr&gt;&lt;td&gt;Something else...&lt;/td&gt;&lt;/tr&gt;';
$f .= '&lt;/table&gt;';

$form['woot'] = array(
    '#type' =&gt; 'whatever',
    '#prefix' =&gt; $f
);


This winds up outputting the form elements after the table in the page. This is not what I am expecting.

The output looks something like:

Something...
Something else...

Textfield
Textfield
(etc...)


It should look like this:

Something...

Textfield
Textfield
(etc...)

Something else...


I have tried using the #prefix in the textfield form elements but that produces some odd unexpected (at least for me) behavior.

I am using Drupal 7, if that makes any difference.

Edit: Added that I am in fact adding the $val to the $form element in the foreach loop
You could try this if I understand correctly:

$header = '&lt;table&gt;';
$header .= '&lt;tr&gt;&lt;td&gt;Something...&lt;/td&gt;&lt;/tr&gt;';

$form['header'] = array(
  '#markup' =&gt; $header;
)

$i = 1;

foreach($somethingAwesome as $val){

    $form['blah_' . $i] = array(
        '#type' =&gt; 'textfield';
        '#prefix' =&gt; '&lt;tr&gt;&lt;td&gt;'
        '#suffix' =&gt; '&lt;/td&gt;&lt;/tr&gt;'
    );

$i++;
}

$footer = '&lt;tr&gt;&lt;td&gt;Something else...&lt;/td&gt;&lt;/tr&gt;';
$footer .= '&lt;/table&gt;';

$form['footer'] = array(
    '#markup' =&gt; $footer,
);


This should give you the output:

Something...

TEXTFIELD
TEXTFIELD
TEXTFIELD

Something else...

You'll need to do something to differentiate each $form['blah'] part too, otherwise you'll be running a foreach loop that overwrites that specific part of your form on every iteration.

You're running your foreach loop in the place where you want it, but all of the data you want surrounding the form is being put into one variable, and then added in one go as a prefix.  Suffix will add data to the end.

General Reference (in case you didn't know):

FormAPI Reference

Specific References:

#prefix

#suffix