diff --git a/entity.test b/entity.test index 6f8987e..62f4d80 100644 --- a/entity.test +++ b/entity.test @@ -863,6 +863,32 @@ class EntityMetadataIntegrationTestCase extends DrupalWebTestCase { // Test setting tags by using ids. $wrapper->field_tags->set(array(2)); $this->assertEqual($wrapper->field_tags[0]->tid->value(), 2, 'Specified tags by a list of term ids.'); + + // Test setting entity references to NULL. + // Create a taxonomy term field for that purpose. + $field_name = drupal_strtolower($this->randomName() . '_field_name'); + $field = array('field_name' => $field_name, 'type' => 'taxonomy_term_reference', 'cardinality' => 1); + $field = field_create_field($field); + $field_id = $field['id']; + $field_instance = array( + 'field_name' => $field_name, + 'entity_type' => 'node', + 'bundle' => 'article', + 'label' => $this->randomName() . '_label', + 'description' => $this->randomName() . '_description', + 'weight' => mt_rand(0, 127), + 'widget' => array( + 'type' => 'options_select', + 'label' => 'Test term field', + ) + ); + field_create_instance($field_instance); + $term_field[LANGUAGE_NONE][0]['tid'] = $term->tid; + $node = $this->drupalCreateNode(array('title' => 'foo', 'type' => 'article', $field_name => $term_field)); + $wrapper = entity_metadata_wrapper('node', $node); + $wrapper->$field_name->set(NULL); + $termref = $wrapper->$field_name->value(); + $this->assertNull($termref, 'Unset of a term reference successful.'); } /** diff --git a/includes/entity.wrapper.inc b/includes/entity.wrapper.inc index 25f75cd..2d1df6d 100644 --- a/includes/entity.wrapper.inc +++ b/includes/entity.wrapper.inc @@ -604,6 +604,10 @@ class EntityDrupalWrapper extends EntityStructureWrapper { $id = entity_id($this->type, $data); $this->id = isset($id) ? $id : FALSE; } + elseif (!isset($data)){ + $this->id = FALSE; + $this->data = NULL; + } } /** @@ -704,6 +708,12 @@ class EntityDrupalWrapper extends EntityStructureWrapper { if ($this->info['type'] == 'entity' && ($previous_id != $this->id || $previous_type != $this->type)) { $this->updateParent($this); } + // In case the entity has been unset, we cannot properly detect changes as + // the previous id defaults to FALSE for unloaded entities too. So in that + // case we just always update the parent. + elseif ($this->id === FALSE) { + $this->updateParent(NULL); + } elseif ($previous_id != $this->id) { $this->updateParent($this->id); }