Drupal - Accessing values of unknown field types when using entity_metadata_wrapper
Here are a few suggestions to make this process a little easier.
$wrapper->field_something->type();
will return the type of the field, ie node
, taxonomy_term
, integer
, text
etc. You could then handle the value returned from $wrapper->field_something->value()
correctly.
Also
$wrapper->field_something->raw()
will return the raw value of the field. Which will either be an array
in the case of multi valued fields of just the value. For instance an entity_reference
will be the nid
(or entity id) of the referenced entity, or an array
of referenced entity id's.
So as no one has come up with another solution, I will answer my own question:
There isn't a simpler way to access values of unknown field types when using entity metadata wrappers.
There are alternative methods to the one I initially described (for instance those pointed out by @thepearson). In particular this method is useful:
entity_property_list_extract_type($type)
It will return the listed type if your type is a list (eg. 'integer' if your type is 'list<integer>'), or false if your type is not a list. Internally it does a strpos just like the code I initially posted, but I guess it's more future proof.
The conclusion is that:
Entity metadata wrappers work well if you have no idea of your field types, and want to carefully address each possible case ;
Entity metadata wrappers work well if you know exactly what types your fields are, and you want to use them ;
If you have only some ideas of what your field types are like (for instance all text, but you don't know if they are formatted or not, and you don't know if they are single or multi valued) then Entity metadata wrappers do not provide any short-cuts and you need to write your own as I did in the initial question.