Support for Drupal 7 is ending on 5 January 2025—it’s time to migrate to Drupal 10! Learn about the many benefits of Drupal 10 and find migration tools in our resource center.
We have tons of "EntityMetadataWrapperExceptions" as of "data structure is not set".
Mainly field_collection suffers from this like in #1033202: [Meta] Generic entity processor.
To reproduce:
$just_created_node_wrapper->field_collection->field_foo->set($foo);
Result:
* EntityMetadataWrapperException
EntityMetadataWrapperException: Unable to set the data property field_contract_participant as the parent data structure is not set. in EntityStructureWrapper->setProperty() (line 477 of sites/all/modules/entity/includes/entity.wrapper.inc).
Expected:
* field collection wrapper autocreates when needed
For now i use this workaround:
if($just_created_node_wrapper->field_my_collection->value() === NULL) { // Workaround Issue 1911158
$empty_field_collection_properties = array('field_name' => 'field_my_collection', 'host_entity' => $just_created_node_wrapper);
$empty_field_collection = entity_property_values_create_entity('field_collection_item', $empty_field_collection_properties);
$empty_field_collection->field_my_collection->set($empty_field_collection);
}
$just_created_node_wrapper->field_my_collection->field_foo->set($foo);
which might better live where the exception was raised.
Objections?
Comments
Comment #0.0
geek-merlinimproved workaround
Comment #1
geek-merlinIt seems we can even do this several levels:
EDIT: but we get an error if we try to set a field of that second level fieldcollection.
Comment #1.0
geek-merlinfixed code
Comment #2
geek-merlinYep, this belongs to fieldcollection and seems related to #1227800: Ease programmatic manipulation of values within collections.
Comment #2.0
geek-merlinerror msg
Comment #2.1
geek-merlintypo