2

Normally you can't have different paragraph items per language so I simply want to hide selected paragraphs depending on a field value in the paragraph. I added an untranslatable list field listing all active languages and editors can select one or multiple languages for which the paragraph should be rendered. On other languages it should be hidden.

So I implemented hook_ENTITY_TYPE_access(), got that field value, calculated an $allowed value and returned an AccessResult::forbiddenIf($allowed === FALSE).

This works fine for the default language, BUT it doesn't work when viewing the translated node. On translations the field always comes out empty. Even if I get the getUntranslated() paragraph.

How can I make my logic work for the translations as well? Why does the visibility field always come out empty on translations? How can I get the selected values?

use Drupal\Core\Access\AccessResult;
use Drupal\Core\Session\AccountInterface;
use Drupal\paragraphs\ParagraphInterface;

/**
 * Implements hook_ENTITY_TYPE_access().
 */
function MYMODULE_paragraph_access(ParagraphInterface $paragraph, $operation, AccountInterface $account) {

  if ($operation === 'view' && $paragraph->hasField('field_visibility') && !$paragraph->get('field_visibility')->isEmpty()) {

    $current_language_id = \Drupal::languageManager()->getCurrentLanguage()->getId();

    $visibility = $paragraph->get('field_visibility')->getValue();

    $allowed =  array_search($current_language_id, array_column($visibility, 'value'));

    return AccessResult::forbiddenIf($allowed === FALSE);
  }

  // No opinion.
  return AccessResult::neutral();
}
2
  • Not sure, but you might be a victim of the behavior described in issue 2887353 : Translations of paragraphs only exist after explicitly re-saving the host entity in that language.
    – Hudri
    Sep 11, 2023 at 13:00
  • @Hudri – Wow yeah, there's something going on in that direction. Just noticed it works for newly added paragraphs, just not for existing ones. Will check deeper. Thank you!
    – leymannx
    Sep 11, 2023 at 13:29

1 Answer 1

1

Okay, so the code in the question should have just worked. But it didn't because the paragraph translatability was misconfigured. The actual issue was this: #2864682: Sub-paragraph fields cannot be translated.

As soon as I correctly configured the "workaround" from the issue, the code from the question fired just fine.

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.