0

I need to pass an array to twig along with the form.

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

where $job_locations is

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

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

And my twig file looks like

 {% 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 coming correctly but it is throwing an error in the error log like

User error: "count" is an invalid render array key in Drupal\Core\Render\Element::children() (line 97 of C:\xampp\htdocs\aws\dev\careers\core\lib\Drupal\Core\Render\Element.php) 

User error: "city" is an invalid render array key in Drupal\Core\Render\Element::children() (line 97 of C:\xampp\htdocs\aws\dev\careers\core\lib\Drupal\Core\Render\Element.php) 

Please help me to solve this.

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 acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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