0

A comment field type in a node(rendered as a form in the node view) has a user entity reference field where multiple user entities can be input and has default values set with:

foreach ($user_ids_array as $key => $value){
    $drupal_user_object = \Drupal\user\Entity\User::load($value);
    if($drupal_user_object){
      $form['field_in_question']['widget'][$key]['target_id']['#default_value'] = $drupal_user_object;
    }
  }

using form alter. In the individual comment's edit form(linked through the edit button of saved comments) the default values are rendered correctly and are visible. However the comment's edit form in the corresponding node's view does not display the user entities properly:

enter image description here

Only the first user entity is loaded and the rest are blank. The render array(of 'widget' index) of the field looks like:

0 => array:3 [▼
      "target_id" => array:16 [▼
        "#title" => Drupal\Core\StringTranslation\TranslatableMarkup {#8704 ▶}
        "#title_display" => "invisible"
        "#description" => ""
        "#field_parents" => []
        "#required" => false
        "#delta" => 0
        "#weight" => 0
        "#type" => "entity_autocomplete"
        "#target_type" => "user"
        "#selection_handler" => "default:user"
        "#selection_settings" => array:7 [▶]
        "#validate_reference" => false
        "#maxlength" => 1024
        "#default_value" => Drupal\user\Entity\User {#4481 ▶}
        "#size" => 60
        "#placeholder" => ""
      ]
      "_weight" => array:6 [▶]
      "_actions" => array:2 [▶]
    ]
    1 => array:3 [▼
      "target_id" => array:16 [▼
        "#default_value" => Drupal\user\Entity\User {#1383 ▶}
      ]
      "_weight" => array:6 [▶]
      "_actions" => array:2 [▶]
    ]
    2 => array:3 [▼
      "target_id" => array:16 [▼
        "#default_value" => Drupal\user\Entity\User {#1383 ▶}
      ]
      "_weight" => array:6 [▶]
      "_actions" => array:2 [▶]
    ]

Besides the first default value, rest of them have no indexes set besides '#default_value'. Is there a way I can ensure that the render array is properly loaded for the rest of the values?

1
  • 1
    Welcome to Drupal Answers :) You're using $key, or User ID, for the widget delta ($form['field_in_question']['widget'][...]), but that number needs to be zero-based and sequential, i.e. the first item is 0, second is 1, all the way up to count($user_ids_array) - 1. Try making that change and see if it fixes it, if not just update the question with the new details and I'm sure it'll be an easy one to work out
    – Clive
    Commented Jan 14 at 20:23

0

Your Answer

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

Browse other questions tagged or ask your own question.