I'm having trouble figuring out how to unset a field's value that references another entity. In Drupal Commerce, we have a product reference field that may be single or multiple value. When I delete a product, I want to delete any reference to that product as well to prevent nasty bugs. For multiple value reference fields, it's easy enough to unsetOffset() on the list wrapper and then save the entity. The reference gets deleted.
However, for single value fields, $wrapper->{$field_name} is actually the referenced entity itself. I can't unset($wrapper->{$field_name}), I can't set it to NULL, and ->clear() doesn't appear to be what I want. The closest I could get was setting it to 0, but technically there's then a reference to entity 0 (which of course doesn't exist) instead of just deleting the data altogether.
Am I missing something?
| Comment | File | Size | Author |
|---|---|---|---|
| #7 | entity_set_null.patch | 2.14 KB | fago |
| #5 | entity_set_null.patch | 959 bytes | fago |
| #3 | entity_set_null.patch | 967 bytes | fago |
Comments
Comment #1
fagohm, I'd say "$wrapper->{$field_name} = NULL;" should work. If not, it's a bug! Ideally unset() should do the same.
Comment #2
rszrama commentedOk, pretty sure NULL failed because of EntityMetadataWrapper::validate() checking the $value via entity_property_verify_data_type(). Since the field's type should be commerce_product, I'm guessing it's failing here:
Comment #3
fagoyep. Patch attached. Does that help?
Comment #5
fagoSilly me.
Comment #6
rszrama commentedOk, so this patch does work as I expected it to, but it doesn't actually let you unset a field value like I was thinking it should. : D
Basically, setting the field to NULL will simply save the NULL value. However, if I didn't choose an option (i.e. chose NULL) via a field widget on the edit form, no value would be saved at all. The problem then is that when I try to wrap the entity later, it's choking on this NULL value. What we really need is a way to remove a field's value from the database altogether as though we had "unselected" the option from the edit form.
The reason this is a problem is b/c when I come back and try to wrap the node after its product reference field value has been set to NULL, I get an array flip error resulting from the wrapper trying to do a commerce_product_load(NULL).
Summary: the patch does what it needs to do, but Entity ought to do more to actually resolve this issue.
Comment #7
fagoMakes sense. So let's improve the field setters to filter out the NULL values, so they aren't saved.
Does the attached patch fix it for you?
Comment #8
rszrama commentedw00t! That did the trick. : )
Comment #9
fagoGreat, committed.