【问题标题】:Drupal 8 module getting "$entity" argument error with hook_entity_presaveDrupal 8 模块使用 hook_entity_presave 获取“$entity”参数错误
【发布时间】:2021-06-01 17:10:10
【问题描述】:

我正在尝试在 Drupal 8 (8.9.11) 中创建一个模块,该模块使用函数 hook_entity_presave 以编程方式更新节点/实体。我已经尝试了https://drupal.stackexchange.com/questions/223346/hook-entity-presave-doesnt-work 的答案,我能够在我的代码中添加这些答案。 这是我的 routing.yml (sno.routing.yml):

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

这是我的控制器(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.
    
    }   
}
}

当我开始添加内容类型发布 (/node/add/issues) 的内容时,我收到以下错误:

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).

非常感谢!

【问题讨论】:

    标签: module hook drupal-8


    【解决方案1】:

    如果您尝试使用 hook_entity_presave() 挂钩,则应按照他们的设计将其移动到 sno.module

    $entity 对象将自动解析为 Drupal\Core\Entity\EntityInterface 的实例,而通过 Controller 方法执行此操作时不会发生这种情况。

    <?php
    
    /**
     * @file
     * Contains sno.module.
     */
    
    use Drupal\Core\Entity\EntityInterface;
    
    /**
     * Implements hook_entity_presave().
     */
    function sno_entity_presave(EntityInterface $entity) {
      // Do stuff.
    }
    
    

    【讨论】:

    • 感谢您清理这个 baikho!事实上,我的代码的第一次迭代只有 sno.info.yml 和 sno.module 但我没有得到我想要的。但是现在,仅使用像您这样的裸代码再次尝试,我现在可以将该文本插入/更新到我的一个字段中。以前我的代码中有一个命名空间,这可能是原因吗?我也有一些使用语句,例如 use Drupal\Core\Entity\EntityChangedInterface;但我认为这无关紧要。但无论如何,代码已经在工作了,我对此很满意。谢谢!
    【解决方案2】:

    您可能需要查看Drupal hooks 以了解其工作原理。

    要使用hook,您不应该创建路由,而只需在.module 文件上实现它。 您的钩子函数将在 Drupal 核心流程中自动调用(在您的情况下,它是实体保存流程)。

    现在你应该将sno_entity_presave() 函数移动到sno.module 然后它会工作。

    【讨论】:

      猜你喜欢
      • 2017-05-22
      • 1970-01-01
      • 1970-01-01
      • 2019-07-28
      • 1970-01-01
      • 1970-01-01
      • 2021-08-31
      • 1970-01-01
      • 2020-01-09
      相关资源
      最近更新 更多