"cannot use a scalar value as an array" warning for adding #prefix and #suffix in template.php via hook-form-alter – Drupal 7 I have the following code in my Drupal’s template.php file. What it does is to embed every element of my site's contact form (created with the Webform module) in a li element (the form itself is already embedded in a ul element).

function MYTHEME_form_alter(&amp;$form, &amp;$form_state, $form_id) {

  if ($form_id == 'webform_client_form_MYFORMID') {
    foreach($form['submitted'] as &amp;$field) {
      $field['#prefix'] = '&lt;li&gt;';
      $field['#suffix'] = '&lt;/li&gt;';
    }
  }


This works, but I get 'Warning: Cannot use a scalar value as an array in MYTHEME_form_alter()' when accessing a page that contains such a form. The warning shows twice, once for each of the two lines where I add the prefix and suffix, respectively.

I have searched far and wide, but I do not know what to do. To the best of my knowledge, this is how Drupal wants me to handle this. And like I said, it does work, but it would be nice to get rid of the warnings and do everything 100 % correct.

(I'm using Drupal 7 and PHP 5.6.24.)

Does anybody know a better / the correct way to do this? Thank you.
Warning: Cannot use a scalar value as an array in MYTHEME_form_alter()


It is a common PHP error which means you are treating a scalar value (eg: int, string) as an array.

You can fix it by checking if it is an array before using it.

function MYTHEME_form_alter(&amp;$form, &amp;$form_state, $form_id) {

  if ($form_id == 'webform_client_form_MYFORMID') {
    foreach($form['submitted'] as &amp;$field) {
      if (is_array($field)) {
        $field['#prefix'] = '&lt;li&gt;';
        $field['#suffix'] = '&lt;/li&gt;';
      }
    }
  }


As mentioned by @Clive

Since you are adding #prefix and #suffix, you are obviously trying to change for the render element. So it would be better to limit the change occurred on render element only.

element_children is the API provided by Drupal for that purpose.

function MYTHEME_form_alter(&amp;$form, &amp;$form_state, $form_id) {

  if ($form_id == 'webform_client_form_MYFORMID') {
    foreach($element_children($form['submitted']) as $key) {
      $field = &amp;$form['submitted'][$key];
      $field['#prefix'] = '&lt;li&gt;';
      $field['#suffix'] = '&lt;/li&gt;';
    }
  }