0

I want to pass an array and a form to a template file, using this code.

public function buildForm(array $form, FormStateInterface $form_state) {
  $form['job_locations'] = $job_locations;
  $form['#theme'] = 'search_form';
  $form['#method'] = 'get';
  // Omissis
  return  $form;
}

The value of $job_locations is the following.

Array(
  [0] => Array(
    [city] => Singapore
    [count] => 5
  )
  [1] => Array(
    [city] => Toronto
    [count] => 3
  )
)

The content of the template file is the following.

{% for location in form.job_locations %}
  {% if location.city  %}
    <li data-original-index="0">
      <a tabindex="0" class="location-list-item" data-tokens="null" role="option" aria-disabled="false" aria-selected="false">
        <span class="text">{{ location.city }}</span>
      </a>
    </li>
  {% endif %}
{% endfor %}

Everything is shown correctly, but the code I am using causes these errors.

User error: "count" is an invalid render array key in Drupal\Core\Render\Element::children()
User error: "city" is an invalid render array key in Drupal\Core\Render\Element::children()

How can I avoid to get these errors?

1 Answer 1

1

Three possible solutions:

  1. Valid render array

    You get a valid render array by putting the content of city and count in #markup elements:

      'city' => [
        '#markup' => 'Singapore',
    
  2. Form variable with a #

    Or start the variable name with a hash, so that it is no longer considered to be a form element which needs to be rendered:

    $form['#job_locations'] = ...
    

    Twig:

    {% for location in form['#job_locations'] %}
      ...
    {% endfor %}
    
  3. Separate template

    Or create a custom template with a variable for the locations array to theme the list separately from the form:

    $form['job_locations'] = [
      '#theme' => 'job_location_list',
      '#locations' => $job_locations,
    ];
    

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.