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?
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();
}
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']);
}
}
}
}