0

I have a Webform field on my node, which links to an application form. The form is set to allow one submission per user (per node). I want the link to disappear after the user has submitted the form.

Any good ways to do this?

2 Answers 2

1

You can try to implement hook_entity_field_access

function hook_entity_field_access($operation, \Drupal\Core\Field\FieldDefinitionInterface $field_definition, \Drupal\Core\Session\AccountInterface $account, \Drupal\Core\Field\FieldItemListInterface $items = NULL) {
  if ($field_definition->getName() === 'field_registration_form' && $operation === 'view') {
  $webform = Webform::load('WEBFORM_ID');
  // Using webform config entity to check submission create.
  $access_result = $webform->access('submission_create', $account, TRUE);
  // Adding the current account as a cacheable dependency and the 'webform_submission_list' cache tag
  // to keep track of any new submission per user.
  $access_result->addCacheableDependency($account)
  ->addCacheTags('webform_submission_list');
  return $access_result;
  }
  return AccessResult::neutral();
}
0

This works (below, added to MY_THEME.theme), but I haven't stress-tested it:

function TEMPLATE_preprocess_node(&$variables) {
  // Hide field_registration_form if already submitted to it.
  if($variables['node']->bundle() == 'CONTENT_TYPE') {
    $current_user = \Drupal::currentUser();
    $uid = $current_user->id();
    $webform = Webform::load('WEBFORM_ID');
    if ($webform->hasSubmissions()) {
      $query = \Drupal::entityQuery('webform_submission')
        ->condition('webform_id', 'WEBFORM_ID');
      $result = $query->execute();
      $submission_data = [];
      foreach ($result as $item) {
        $submission = \Drupal\webform\Entity\WebformSubmission::load($item);
        $submission_data[] = $submission->getData()['user'];
      }
      if (in_array($uid, $submission_data)) {
        unset($variables['content']['field_registration_form']);
      }
    }
  }
}
1
  • 2
    You might run into caching issue when trying to alter the node. You might need to add cache context / tags to $variables['content'] to make sure the visible/hidden is not cached.
    – jrockowitz
    Commented Nov 21, 2019 at 14:56

Your Answer

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

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