0
votes

I am trying to create a module in Drupal 8 (8.9.11) and this module uses the function hook_entity_presave in order to update a node / entity programmatically. I've tried the answers from https://drupal.stackexchange.com/questions/223346/hook-entity-presave-doesnt-work, I was able to add those in my code. Here is my routing.yml (sno.routing.yml):

sno.content:
  path: /node/add/issuances
  defaults:
    _controller: Drupal\sno\Controller\SnoController::sno_entity_presave
  requirements:
    _permission: 'access content'

Here is my Controller (src/Controller/SnoController.php):

namespace Drupal\sno\Controller;

use Drupal\Core\Entity\EntityInterface;
use Drupal\node\NodeInterface;

class SnoController {
    public function sno_entity_presave(\Drupal\Core\Entity\EntityInterface $entity) {
      if ($entity->getEntityType()->id() == 'issuances') {
     $entity->set('field_s', ', s. ');
    //CAUTION : Do not save here, because it's automatic.
    
    }   
}
}

When I got into adding a content of content type issuance (/node/add/issuances), I am getting the error below:

The website encountered an unexpected error. Please try again later.

RuntimeException: Controller "Drupal\sno\Controller\SnoController::sno_entity_presave()" requires that you provide a value for the "$entity" argument. Either the argument is nullable and no null value has been provided, no default value has been provided or because there is a non optional argument after this one. in Symfony\Component\HttpKernel\Controller\ArgumentResolver->getArguments() (line 78 of /var/www/senate-library/vendor/symfony/http-kernel/Controller/ArgumentResolver.php).

Thank you very much!

2

2 Answers

2
votes

You may need to take a look to Drupal hooks to know how it works.

To use a hook, you shouldn't create a route but just implement it on .module file. Your hook function will be automatically invoked in the Drupal core process (in your case, it is entity saving flow).

Now you should move sno_entity_presave() function to sno.module then it will work.

1
votes

If you are attempting to utilise the hook_entity_presave() hook, then you should move it to a sno.module as per their design.

The $entity object will then automatically resolve to an instance of Drupal\Core\Entity\EntityInterface, which wouldn't occur when doing it via a Controller method.

<?php

/**
 * @file
 * Contains sno.module.
 */

use Drupal\Core\Entity\EntityInterface;

/**
 * Implements hook_entity_presave().
 */
function sno_entity_presave(EntityInterface $entity) {
  // Do stuff.
}