18

I have created a custom resource which extends the EntityResource class. This way I can use all build in functionality that Drupal core provides on the default entity resource, but I can still add some extra checks. This works perfectly fine.

I defined my canonical route in my resource as /api/my-endpoint/{node}. In this way, I can fetch and patch nodes by the node ID. After careful consideration, I want to implement /api/my-endpoint/{node_uuid} or even /api/my-endpoint/{node_custom_field} to fetch (and patch) a node by UUID.

Of course, Drupal doesn't know this param and cannot load the corresponding node object, which results in fatal errors.

How can make I this work?
I tried to implement a custom RoutingParamConverter class, but I didn't got it to work.

2 Answers 2

18

As long as you have the uuid of an entity you can use Drupal's entity storage interface to load it given that property. It should be as simple as using the loadByProperties method.

$node_loaded_by_uuid = \Drupal::entityTypeManager()->getStorage('node')->loadByProperties(['uuid' => $your_uuid]);
$node_loaded_by_uuid = reset($node_loaded_by_uuid);

UPDATE: milkovsky is correct. loadByProperties returns an array. If you want the actual node object at the top of it you will have to use the reset function.

3
  • 2
    You will get an array back. A reset(...) operation should be done in addiiton: $node_loaded_by_uuid = reset($node_loaded_by_uuid).
    – milkovsky
    Commented Jan 16, 2020 at 16:40
  • @milkovsky thank you. I updated the answer to reflect this.
    – Amy
    Commented Jan 17, 2020 at 16:25
  • See my answer for something simpler.
    – colan
    Commented Dec 16, 2021 at 17:02
18

You can use EntityRepositoryInterface::loadEntityByUuid():

$entity = \Drupal::service('entity.repository')->loadEntityByUuid('node', $uuid);
2
  • The internals of the loadEntityByUuid function does exactly what the other answer is doing, but with a couple extra calls. See loadEntityByUuid in EntityRepository.php
    – mbomb007
    Commented Feb 28, 2023 at 22:05
  • This is a brilliant answer. I have a hook_node_presave() and I need the Node ID but only have the UUID. Working on Drupal 9.5 and will test for Drupal 10.x after the migration. $entity = \Drupal::service('entity.repository')->loadEntityByUuid('node', 'b6bca440-f4d9-41d0-86c6-d913c00b9e78')->id(); Everything I need is there!
    – cbovard
    Commented Aug 10, 2023 at 21:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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