Currently entity_autocomplete field type is not supported.
Form example:
$form['multivalue'] = [
'#type' => 'multivalue',
'#title' => 'Title',
'#cardinality' => -1,
'#default_value' => $default_value,
'entity' => [
'#type' => 'entity_autocomplete',
'#target_type' => 'node',
'#selection_settings' => [
'target_bundles' => ['article'],
],
'#validate_reference' => TRUE,
'#title' => 'Entity',
];
];
After form submission default value is saved in the form. But entity_autocomplete expects an object there instead of an integer.
The following exception is triggered:
The #default_value property has to be an entity object or an array of entity objects.
See \Drupal\Core\Entity\Element\EntityAutocomplete::valueCallback()
Suggestion: add an additional #process method to the field and load related entities.
Comments
Comment #2
a.milkovskyProposed solution.
Comment #3
a.milkovskyComment #4
a.milkovskyComment #5
a.milkovskyMoved logic to the MultiValue class.
Comment #6
sinn commentedWhat is a problem to load entities and then pass them into default value?
Comment #7
a.milkovsky@sinn see my patch #5.
Also in case of multivalued field, there might be muptiple entity_reference sub-fields and the field should recognize all of them.
The `processEntityAutocompleteDefaultValue` method already supports the entityTypeManager entity load by any target entity type (not only "node" as in your example. In addition the method processes a non-integer value, in the entity_autocomplete format.
Comment #8
a.milkovskySomehow the loaded entity gets lost after clicking on the "Add more" button. Trying to find a fix.Nevermind. The issue was with the patch from #3229995: Items are removed incorrectly with Ajax.
This patch works and is ready to review as before.
Comment #9
a.milkovskyAdded on additional case to check for EntityInterface.
Comment #10
a.milkovskyAdded an additional check `isset($element['#default_value'])`
Comment #13
darvanenCreated an MR to run CI and see if there are any issues. As there is a test suite I'm pretty sure this will need tests to proceed.