0

How to allow a specific Drupal role to modify its own content in the CiviCRM Contact form (civicrm-contact/%user)? I don't see any permissions like "edit own content" for type nodes in admin/people/permissions for the CiviCRM contact entity. Do you have a solution? Thanks

1 Answer 1

1

You can use standard Drupal access hooks and place whatever custom logic you like. https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21entity.api.php/function/hook_ENTITY_TYPE_access/9

Here is a possible way. Add this hook implementation in a custom module. You can have any custom logic there.

In this example, I look up the contact id via uf_match record for the user, and see if the contact id being viewed matches the user's contact id. If so, it should grant access.

This is off the cuff, but should point in the right direction

You'll need the proper 'use' statements at the top of the file for EntityInterface, AccountInterface, and AccessResult.

function YOUR_MODULE_civicrm_contact_access(EntityInterface $entity, $operation, AccountInterface $account) {
  if ($operation == 'update' && $account->id()) {
    \Drupal::service('civicrm')->initialize();
    try {
      $uf_match_result = civicrm_api3('UfMatch', 'get', [
        'sequential' => TRUE,
        'uf_id' => $account->id(),
      ]);
      if (!empty($uf_match_result['values'][0]['contact_id'])) {
        return AccessResult::allowedIf($entity->id() == $uf_match_result['values'][0]['contact_id']);
      }
    }
    catch (Exception $e) {

    }
  }
  return AccessResult::neutral();
}

It would also be possible to check if the $account has a permission, like 'edit my contact' in the allowedIf() conditional

$account->hasPermission('edit my contact');

2
  • This is good but CRM_Core_Session::singleton()->getLoggedInContactID(); may be more forward-compatible than API3? Though either way is valid IMO. Jan 3 at 18:48
  • Yes could be a better way to find a user's linked contact id, time to stop using APIv3 :) APIv4 maybe fine too. Jan 4 at 19:09

Your Answer

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

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