Quicktips with Charlie: Entity Metadata Wrapper and Null Values
Last year I had the privilege of meeting Charlie Schliesser, a fellow developer here in St. Louis. Little did I know, a few months later we'd actually be working together quite a bit as I took a new position with my church which utilized the services of the company he worked for. Since that time, we've had several co-working sessions where we swap tips, talk about new technologies, get help with problems and leave inspired to do cool work. Each time we depart, I feel like I have a few more tools in my toolbox and I'm eager to share them. With that in mind, I'd like to start a series of posts that share what we learn. Feel free to leave comments, ask questions, or give feedback!
Entity_metadata_wrapper and Null Values
Are you a fan of entity_metadata_wrapper from the entity module? If you aren't, it's a great alternative to node_load()/entity_load() that gives you chain-able, localized, and sanitized (if requested) access to fields and properties of any entity. If you are hip to EMW, you've likely run into an issue where you try to access the value() of a field that isn't set on the object and EMW throws a nasty exception killing the page.
This often happens when looping through nodes where a non-required field is blank (i.e. $wrapper->field_middle_name->value()) and is quite frustrating. Before today, I'd try to avoid this issue by using field_get_items() or dumping the entity (using $wrapper->value()) and checking the value there. Thankfully, today I found a stackoverflow post that provided a pretty elegant alternative.
The Solution
Who knew that the good folks who created EMW implemented the magic method __isset() on the EntityMetadataWrapper class? Now, we can do something like this to check for set values:
- $wrapper = entity_metadata_wrapper('node', 123);
- if($wrapper->__isset('field_middle_name')) {
- // Do something awesome with the middle name.
- } else {
- // Don't do anything awesome, they don't have a middle name.
- }
Pretty neat huh?
Tags