Return an array of entities

Public

This function spits back an array in the form of id => title based on the id and title fields you want. This is useful when building form options that select a grouping of entities based on simple requirements (like give me all page nodes or all users). I've used this to pull all nodes of a certain type and rendering the options array as field_machine_name => title or uid => name .

Get raw version
php
  1. /**
  2.  * Helper function to generate options list of entities based on type
  3.  */
  4. function _assemble_entity_list($entity_type, $bundle, $id_field, $title_field) {
  5. // pull items based on bundle
  6. $options = array();
  7. // assemble all entities requested
  8. $query = new EntityFieldQuery;
  9. $result = $query
  10. ->entityCondition('entity_type', $entity_type)
  11. ->entityCondition('bundle', $bundle)
  12. ->propertyOrderBy($title_field)
  13. ->execute();
  14. // convert to load only keys of items found
  15. $etids = array_keys($result[$entity_type]);
  16. // load all the entities in the array
  17. $elist = entity_load($entity_type, $etids);
  18. // load entities and build array of id -> title
  19. foreach ($elist as $entity) {
  20. // allow for field value as key
  21. if (strpos($id_field, 'field_') !== FALSE) {
  22. $key = $entity->{$id_field}[LANGUAGE_NONE][0]['value'];
  23. }
  24. else {
  25. $key = $entity->{$id_field};
  26. }
  27. $options[$key] = $entity->{$title_field};
  28. }
  29. return $options;
  30. }

Comments