9

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.

9

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.

| improve this answer | |
  • 1
    You will get an array back. A reset(...) operation should be done in addiiton: $node_loaded_by_uuid = reset($node_loaded_by_uuid). – milkovsky Jan 16 at 16:40
  • @milkovsky thank you. I updated the answer to reflect this. – Matt Jan 17 at 16:25
1

You can use EntityRepositoryInterface::loadEntityByUuid():

$entity = \Drupal::service('entity.repository')->loadEntityByUuid('node', $uuid);
| 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.