8

I am working on an admin interface for a module that uses a custom entity type. Is there a function or some way that I can use to find all entities of a given type, so that I can show users a list of them?

8

You're looking for the EntityFieldQuery class:

$query = new EntityFieldQuery;

$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'article')
  ->fieldCondition('field_my_field', 'value', 'a_value')
  ->propertyCondition('status', 1)
  ->fieldOrderBy('field_my_field', 'value', 'DESC');

$results = $query->execute();
if (isset($results['node'])) {
  $nodes = node_load_multiple(array_keys($results['node']));

  foreach ($nodes as $nid => $node) {
    // Do something with the node object
  }
}

The above code loads all node entities with a content type of article. It filters on a custom field called field_my_field and the status property of the node. I only put that in for reference you wouldn't need it to load all nodes without any filters. Same goes for the order by statement.

Hope that helps.

| improve this answer | |
1

You may also try the following simple two-liner:

$res = (new EntityFieldQuery)->entityCondition('entity_type', 'node')->execute(); 
$entities = entity_load('node', array_keys(reset($res)));

Or the following one-liner (PHP >= 5.5), ready to use with drush eval:

print_r((new EntityFieldQuery)->entityCondition("entity_type", "node")->entityCondition("bundle", "page")->execute());

To remove them, please check: Can I delete nodes of a given content type with Drush?

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.