0

In a custom module I am defining a defaults Configuration entity that references a role. I would like to define a dependency on the role. This is my first attempt.

public function calculateDependencies() {
  $this->dependencies = parent::calculateDependencies();
  $this->addDependency('module', 'user');
  if (isset($this->role_id)) {
    $this->addDependency('config', "user.role.{$this->role_id}");
  }
  return $this; // Also tried return $this->dependencies;
}

The Drupal documentation on dependencies references the Block configuration class that looks very similar:

  public function calculateDependencies() {
    parent::calculateDependencies();
    $this->addDependency('theme', $this->theme);
    return $this;
  }

However I am seeing an error shown below when trying to save the entity.The backtrace indicates it is coming from the attempt to add a dependency on the user module. I chose to add that dependency by taking an example from system.action.user_add_role_action.administrator.

PHP Error: Cannot use object of type Drupal/my_module/Entity/MyAccessDefaults as array in /app/web/core/lib/Drupal/Core/Entity/DependencyTrait.php on line 32

For example I am trying to test with this code:

$values = [
  'id' => 'administrator', 'label' => 'Administrator role grants', 
  'grant_type' => 'role', 'role_id' => "administrator", 
  'grants' => ['grant_view' => 1]
];
$default_admin_config = \Drupal::entityTypeManager()->getStorage('my_entity')->create($values);
$default_admin_config->save();
1

ConfigEntityInterface::calculateDependencies returns $this, so this line:

$this->dependencies = parent::calculateDependencies();

Is causing problems (replacing the dependencies array with the instance of the current class, which is presumably a MyAccessDefaults).

Looking at the code, and other core classes which implement ConfigEntityInterface, your code should be:

public function calculateDependencies() {
  parent::calculateDependencies();
  $this->addDependency('module', 'user');
  if (isset($this->role_id)) {
    $this->addDependency('config', "user.role.{$this->role_id}");
  }
  return $this;
}
1
  • Yes, that was the issue. I had just got it working when you answered with the same change. I think I copied that part from a sample somewhere. – lolcode Sep 8 '20 at 19:21

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.