Hello. I don't know if this the right place to create this issue, but I solved it by modifying this specific file (EntityViewBuilder.php).
Problem
When using EntityViewBuilder to display an entity reference field, the output does not respect the current language.
How to reproduce
- Create a new Drupal 8 installation
- Add a user entity reference field to content type basic page
- Add a second language. Enable translation for User and Basic Page
- Enable tranlation for the entity reference field created in step 2
- In Basic Page manage display, select rendered entity for the entity reference field
- Add a text field to User, e.g. field_surname
- Translate user 1
- Create a basic page with a reference to user 1 and translate this page
- Visit the basic page. The rendered user will be in the correct language.
- Now install Fieldblock. You will also need to install this patch. I choose this example because Fieldblock uses EntityViewBuilder.
- Fieldblock.php line 342 calls FieldItemList::view()
- FieldItemList.php line 255 calls EntityViewBuilder::viewField()
- Go to Manage Blocks and add a Fieldblock for the field of step 2. Once again, choose rendered entity display mode.
- Again, visit the translated basic page. The rendered user in the block will be in the original language, untranslated.
Suggested resolution
I don't know if this is a general correct solution. In my case, I solved the issue by modifying EntityViewBuilder::viewField() (line 397 of EntityViewBuilder.php) from this:
public function viewField(FieldItemListInterface $items, $display_options = []) {
$entity = $items->getEntity();
$field_name = $items->getFieldDefinition()->getName();
$display = $this->getSingleFieldDisplay($entity, $field_name, $display_options);
$output = [];
$build = $display->build($entity);
if (isset($build[$field_name])) {
$output = $build[$field_name];
}
return $output;
}
to this:
public function viewField(FieldItemListInterface $items, $display_options = []) {
$entity = $items->getEntity();
if ($entity instanceof TranslatableInterface && $entity->isTranslatable()) {
$entity = \Drupal::service('entity.repository')->getTranslationFromContext($entity);
}
$field_name = $items->getFieldDefinition()->getName();
$display = $this->getSingleFieldDisplay($entity, $field_name, $display_options);
$output = [];
$build = $display->build($entity);
if (isset($build[$field_name])) {
$output = $build[$field_name];
}
return $output;
}
I will also create a patch and post it here.
Any comments welcome, thanks in advance.
| Comment | File | Size | Author |
|---|---|---|---|
| #98 | 2955392-98.patch | 6.24 KB | alexpott |
| #98 | 95-98-interdiff.txt | 1.53 KB | alexpott |
| #95 | 2955392-95.patch | 6.24 KB | alexpott |
| #95 | 91-95-interdiff.txt | 1.29 KB | alexpott |
| #91 | 2955392-91-interdiff.txt | 1.09 KB | berdir |
Comments
Comment #2
babis.p commentedComment #3
berdirThe challenge with viewField() is that view() actually allows to pass in an explicit language and that is also used for references, but viewField() does not.
For example if you have a list in views, then you can select in which language the entity should be displayed, you can for example list all translations on a single page and each entity should be rendered in its language. This would not be able to render the referenced user in the appropriate language for each.
This doesn't make it worse, but it's also not a complete fix.
Don't forget to set the issue to needs review so that the patch can get tested.
Comment #4
steven buteneers commentedThis service should be injected instead of statically calling it. The class already contains a create and construct.
Tested the patch, my scenario was that (in layout builder) I displayed a paragraph (entity reference revision) with a translatable text field. In both languages the source languages was displayed, after applying this patch the correct language is used! ++
Comment #5
dhirendra.mishra commentedApplying Correct patch with injecting the entity.repository service. Please review and test my patch.
Comment #6
steven buteneers commentedSome nits:
Typehint against interface:
Drupal\Core\Entity\EntityRepositoryInterface
Also in the constructor.
Unnecessary variable declaration. Just call $this->entityRepository->getTranslationFromContext($entity) directly.
Comment #7
dhirendra.mishra commentedThanks Steven Buteneers,
Here below is the corrected and updated patch.Please review and test it.
Comment #8
dhirendra.mishra commentedKindly ignore the #7 patch as Interface is still missing in typehint in constructor. Please find correct patch in #9.
Comment #9
dhirendra.mishra commentedHere is the Patch.
Comment #10
steven buteneers commentedSorry I missed some things in the previous patch, here are my last comments:
This should be declared after the $entityManager property (based on naming convention)
Docblock needs to be updated as well
I don't think we should make the entity repository nullable. I see this happens with the theme registry (don't ask me why, as they actually try to assign the same service twice anyway).
Therefore I suggest we inject the entity repository before the theme registry and make it required.
Also $entityRepository (in the constructor) should be written snake_case to match up with the other parameters in the constructor.
At last: you also need to inject the service in the create function, as is done with the other services as well.
Comment #11
steven buteneers commentedComment #12
dhirendra.mishra commentedThanks for the update. I have updated my patch.Please check if anything missing.Also please test and review it.
Comment #13
dhirendra.mishra commentedKindly review and test my code
Comment #14
steven buteneers commentedSome nits:
Add docblock for the entity repository here (before the theme registry)
Inject the entity repository before the theme registry. (note: Also in the create function).
Comment #15
dhirendra.mishra commentedThanks for the update. I have completed both correction and updated the patch.Please check
Comment #16
berdirI disagree with that.
That would break subclasses that already inject the registry.
Instead, just like the $theme_registry, the argument needs to be last an optional, with a fallback to \Drupal::service().
While touching and injecting this, which is great, should we also update the non-injected calls at the same time?
Also, the problem is that we have no way to render it in a specific language.
I think the title should probably say "when used with a non-translatable field", because that's the problem/difference.. for translatable field, $entity is the correct translation if $items is.
The problem is that this makes it impossible for translatable fields to be rendered in not-the-current-language as we have no $langcode argument and trying to add it would be an API change.
Comment #17
berdirAnd we need tests :)
Comment #18
dhirendra.mishra commentedPrevious Patch got failed as it was generated from 8.4.x branch. Now it has been taken from 8.7.x branch.
Comment #19
dhirendra.mishra commentedComment #22
msankhala commentedEmpty space should be removed.
As @Berdir mentioned in comment #16 point 1
EntityRepositoryInterface $entity_repository = NULLshould be the last argument so it does not break the subclass.Also, this needs tests because this is a significant change.
Comment #23
dagmarThis patch adds the changes requested in #22.
Agree. So, why no add this only to fields that are not translatable? This patch does that.
Tests are tricky here... Should we create a new KernelTest to combine Translations and References right? I couldn't find an example to use as base. @Berdir any hint?
Comment #24
pavelculacov commentedThanks for patch. solve problem with sub-paragraphs translation
Comment #25
keynone commentedThe Patch works perfectly. Thanks!
Comment #26
surbz commentedThanks for the review @Regnoy and @keynone can we also change the status to RTBC now.
Comment #27
dagmarThis cannot be RTBC until has some tests.
Comment #28
RAFA3L commentedThanks! the patch works!
Comment #29
steven buteneers commentedReviewed en tested, works!
Comment #30
alexpottIn order to commit a bug fix we need an automated to test to prove that we've fixed the bug and ensure that we don't break it again in the future. For more information about writing tests in Drupal 8 see the following links:
Comment #31
scotwith1tThis didn't apply cleanly for me with the latest 8.7.x-dev. I think it's because of #3023981: Add @trigger_error() to deprecated EntityManager->EntityRepository methods and it's gonna need a re-roll? I wish I was good at rolling patches or I'd take a stab at this... :-/
Comment #32
scotwith1tPretty sure the fix applied above in the latest 8.7.x-dev gives us similar changes to this one, it seems maybe the only piece that might still be needed is this bit? Line #s prob changed and such since #23 was created though.
With this bit applied, I am now seeing the translated Paragraph field. I guess it still needs the test to pass and get committed though. Thanks everyone!
Comment #33
scotwith1tGotta try sometime...I think this re-roll is all that's left of what's needed after the latest 8.7.x-dev core updates
Comment #34
scotwith1tTake 2?
Comment #35
scotwith1tYay! Just needs a test now. Sorry, this is definitely outside my skillset. But now I can incorporate the patch again. :)
Comment #36
pavelculacov commentedOld Patch no problem, Your patch have problem, i use Layout Builder
EntityRepositoryInterface; << is missing
Call to a member function getTranslationFromContext() on null in Drupal\Core\Entity\EntityViewBuilder->viewField()
After this work like a charm
Comment #38
pavelculacov commentedBut, this problem is only use LayoutBuilder module if use.
Update patch for Drupal 8.7
Comment #39
pavelculacov commentedComment #40
shaalAfter seeing a comment about this issue in #3051188: Translated content displays its taxonomy terms in the wrong language when layout builder is enabled for that content type
I tested this on Drupal 8.7.x
I reverted Umami's settings to use the same taxonomy terms for all languages #3051465: Revert "Taxonomies are only displayed in English"
Here you can see the bug marked with red arrows (English taxonomy terms displayed inside a Spanish recipe page):

Then I applied patch #39

and here's the page showing Spanish taxonomy terms in the Spanish recipe page:
Patch #39 resolves #3051188: Translated content displays its taxonomy terms in the wrong language when layout builder is enabled for that content type
Comment #41
tim.plunkettThis cannot be RTBC yet because it needs tests.
Also it should likely be reviewed by an entity maintainer.
Should this instead use the new EntityRepository methods? See https://www.drupal.org/node/3036722.
Nit: The indentation here is very wonky. Hard to know when the condition has ended and the actual line has begun.
Comment #42
dagmarThis is the test for the issue. Let see what the testbot says.
Comment #43
dagmarThe patch works because the tags field provided by the standard profile is set to translatable. Making this field untranslatable replicates the same scenario than described in #4.
Comment #44
dagmarThis patch includes the fix from #39 with the indentation issues fixed.
Comment #46
dagmar#45 Includes tests coverage.
#43 shows exposes the failure (that patch doesn't include the fix).
Regarding question from #41
I'm not sure. It seems that code is useful when you want to load an entity giving an ID. But at this level of code, the entity is already available with
$items->getEntity();We only need to load an existent translation for an already loaded entity.
Comment #47
bnjmnmUsing the methods mentioned in #41, all these lines can be replaced with
$entity = $this->entityRepository->getActive($items->getEntity()->getEntityTypeId(), $items->getEntity()->id());EntityViewBuilderTest.Not used
Not used
Nit: s/content/translation/ s/right/correct
Capitalize "English" and all other language names in this test.
Nit: Remove "now" and make this one sentence.
Nit: Remove "A now" and comma. Change "no translatable" to "non-translatable"
Nit: Remove "A now" and the comma.
For this and the other enable/disable translation methods in this class, the function args aren't necessary since it is always article/tags. The methods themselves could be considered by some to be unnecessary since they are only used once, but they do make the test easier to read so I'm inclined to keep them but it's possible another will feel differently.
Nit: Remove comma and change "not translatable" to "non-translatable"
This isn't really random - maybe rephrase as
Create a taxonomy term with a Spanish translation.Nit: Remove comma
Nit: Single quotes
Comment #48
dagmarThanks! @bnjmnm.
Items 1, 3 to 9 and 11 to 14 addressed in this patch.
I invested around four hours to write a proper patch for this issue. Unfortunately I don't have time to work in a different test right now.
I tried to prioritize readability here.
Comment #50
bnjmnmThanks for the quick turnaround on that @dagmar!
Here's a patch Addressing two items from my review (needs a subsystem maintainer anyway so I'm not in a position to RTBC)
enableTranslationsForContentType($type)is nowenableTranslationsForArticle()So the additional tests needed (no expectations for @dagmar to do it, btw 🙂) are tests that would have identified this issue without us having to discover it via Layout Builder (it's good the Layout Builder test is there, though)
Comment #51
bnjmnmComment #52
bnjmnmFirst I should point out that the functional test added to Layout Builder should be refactored to not use the standard profile - this will need to be changed before this can be RTBC.
Added a kernel test to cover
EntityViewBuilderdirectly.A few things to mention
EntityTestTranslatableNoUISkip, an entity type I borrowed from the language module. The permission was necessary for the entity to be rendered in an entity reference field. Full disclosure I'm not 100% sure why - it happens in a call tocheckAccess()inDrupal\Core\Field\Plugin\Field\FieldFormatterEntityReferenceFormatterBase::getEntitiesToViewDrupal\Core\Entity\EntityViewBuilder::viewField- this solution works just fine but it seems odd that the entity returned by the FieldItemList in$items->getEntity()is the default language, even if the field is retrieved from a translated version. I think the solution as-is is just fine, but since a maintainer will be reviewing this anyway, I'd like their thoughts on this.Comment #54
bnjmnmChanged the deprecated call to getViewBuilder to use the service where the method is not deprecated, and updated LayoutBuilderTranslationWithReferencedContentTest to not use the standard profile.
Comment #56
dagmar@bnjmnm thanks for continue working on this. I have a few updated from my side regarding the use of Drupal 8.7 and Layout Builder.
I'm not entirely sure why, but when I try to edit the Layout of a content type using Layout Builder. This code
$entity = !$field_is_translatable && $entity_is_translatable ? $this->entityRepository->getActive($items->getEntity()->getEntityTypeId(), $items->getEntity()->id()) : $items->getEntity();ends making $entity NULL.
Which later shows a fatal error in the page because.
Also, the another problem related to the use of
entityRepository->getActivetrigger this warning:We upgraded a site from D8.6 to D8.7 and reverting #54 allowed us to keep using the Layout Builder user interface.
I'm almost sure this has to be related with the use of
entityRepository->getActive. My patch of #44 doesn't produce the fatal error.Comment #57
bnjmnm@dagmar if this is not working for you when editing Layout Builder, the test coverage needs to be expanded to cover that use case. Would you be able to review LayoutBuilderTranslationWithReferencedContentTest.php and point out what this test does not cover that would have otherwise surfaced the issue you reported? (field and block types in your layout, etc..)
Comment #58
berdirWhat's missing is that $items->getEntity() can be null, typically when creating a "faked" field items object without an actual entity, which is I guess what layout builder is doing. The code needs to first check that $items->getEntity()( isn't NULL, in which case we can't detect the correct language and should do some kind of fallback, likely the current language.
Comment #59
pavelculacov commented#58 Agree with you, have same problem in Commerce Product Variation
Comment #60
bnjmnmThe error in #56 should get test coverage, I tried to piece together how to reproduce this based on the other comments but was not able to do so. If someone can provide steps on how to reproduce the error, with just core modules, I can write a test that proves a different approach is necessary. Someone else who has experienced the error is also welcome to write the test 🙂
The patch in #44 that was reported to work also uses
$items->getEntity(), which #58 points out can return null, so it seems particularly important to surface these use cases in tests.Comment #61
dagmar@bnjmnm I tried to replicate this as well using a fresh 8.8.x site install. Unfortunately I haven't been able to replicate this either. Maybe is related to something with the upgrade from 8.6.x.
Comment #62
bnjmnmBased on the following I'm setting back to needs review
The tests in this patch prove that this patch fixes the reported issue, an I don't see any evidence that it introduces new problems, so I'd like to move this forward so multilingual sites no longer have this bug. If someone is running into problems related to this patch please provide steps to reproduce and/or tests that prove the existence of the problem. While I don't want to introduce new problems with this patch, I also don't want to deprive users of a fix based on something less-than-conclusive.
Comment #63
shaalRTBC.
I can confirm that in recipe nodes (which use Layout Builder) tags are displaying the correct string in English and in Spanish.
Comment #64
dagmarThanks @bnjmnm
Sorry meant to say I cannot reproduce this as part of a fresh install. I faced this issue in production in a really large site, so I can tell this is not ready yet as is. #58 and #59 are mentioning this as well.
@shaal thanks for your feedback. But I'm moving this back to Needs review because we already know that this will break existent installation if this lands as is.
Let's see if @Regnoy or @Berdir can provide some extra indications to provide a full working patch.
Comment #65
pavelculacov commented@dagmar have error Commerce Product Layout Manager(field Variations) after applay last patch from Support for Layout Builder module
Drupal\Core\Entity\EntityStorageException: No entity bundle was specified in Drupal\Core\Entity\ContentEntityStorageBase->createWithSampleValues()
Here only have error.
Fresh Site Install.
For working site i use patch entity-view-builder-entity-reference-language-2955392-36.patch
Comment #66
yahyaalhamadI applied @shaal #62 and @bnjmnm #54, but both introduces this error when using default layout builder in a taxonomy with a paragraph.
Call to a member function getEntityTypeId() on null in /var/www/html/ridwan/public_html/core/lib/Drupal/Core/Entity/EntityViewBuilder.php on line 525Comment #67
anybodyThank you for your hard work on this issue, I can confirm that this is also causing #3072745: Symmetric translation broken? in entity_reference_layout module which is fixed by #62 for me.
We'll test #62 on 8.7.x for the next days and report if it breaks other things. So far it applies cleanly and works without any problems. You are my heros for today after searching for hours... :)
Comment #68
thomas.frobieterThank you all, this is truely a major issue and broke translations in entitiy_reference_revisions for us. With the patch in #62 it's fixed for us, we didn't run into any of the problems above yet in the last two weeks.
Comment #69
anybody-.- I should not have written my comment in #67 ... :D Now that I wrote it, we're in trouble. Translation of entity_reference_revision elements is working but therefor layout administration is broken:
which doesn't appear if the patch is removed.
On a different node view mode ("teaser") we get:
even after the patch was removed so that might be unrelated.
As I've just seen, our error is the same as #56. We're using 8.7.x, NO commerce and NO fieldblock module.
UPDATE:
I was able to solve the second bug by removing
context_mapping:
entity: layout_builder.entity
view_mode: view_mode
from the core.entity_view_display.node.XX.teaser.yml configuration and re-importing it. The error was gone and I couldn't find any negative impact yet. After re-saving that value was not set again.
The first error definitely only appears with this patch. Perhaps we're missing another patch which has been committed to 8.8.x but not 8.7.x?
Comment #70
dagmarThis is the third confirmation the patch #62 breaks layout builder (#69, #65, #64).
@Anybody thanks for your feedback, I think could be useful to provide some extra context of your site configuration, like fields your are trying to render in your site, or which modules, are interacting there. In the meantime I guess this still needs work.
Comment #71
anybodyI guess this issue #3063839: PHP message: Error: Call to a member function getEntityTypeId() on null in /var/www/html/drupal/web/core/lib/Drupal/Core/Entity/EntityViewBuilder.php on line 525 might be reported by other users of this patch. So we should have a closer look at these lines, which cause the error for me for the default view mode of a translatable node entity type.
that cause:
Comment #72
anybodyOk I had a closer look and the problem seems to exist in preview mode in the layout builder, when using this patch because in this line
the
returns NULL instead of the entity ID in some cases in the default view mode (only). The returned example entity simply seems to be "new" and doesn't have an ID. That causes getActive() to fail and also return NULL which means $entity is also passed as NULL.
As a quickfix I added "!$items->getEntity()->id() === NULL" condition to check if the entity is empty, which brings the page back to life:
(core/lib/Drupal/Core/Entity/EntityViewBuilder.php, Line 458)
But my experience in this context isn't enough to tell WHY the returned entity is "new" here and what should be the appropriate fix.
Comment #73
sic commentedthe patch seems to be working, thanks guys. hope this gets into core quickly :)
Comment #74
thomas.frobieter#62 + hack from #72 did the trick for me, thank you!
Could you perhaps check if a new patch with #72 included makes sense to you?
Comment #75
shaalPatch #62 fixed the issue I experienced in Umami.
Comments #64-74 did not provide steps to replicate the issue you are seeing after applying patch #62.
Can you please provide these steps?
Comment #76
anybodyHi @shaal, thank you!
The steps are quite simple:
This happens in every combination for every content type we tried.
The content type has translation enabled for most of the fields. Some simply don't make sense. And I guess the error appears because of the preview functionality.
As background information: We're using the following patched (via composer-patches) against core in the environments where we've encountered these problems:
If you and others are not able to reproduce this problem (we did in several Drupal projects), we should try to find out which configuration leads to these problems.
Comment #77
bnjmnmThe specific steps (1-5) listed in #76are already part of of test coverage and those tests pass. We need to know what use cases are present on sites experiencing the problem so it can be added to test coverage. As soon as there are steps that allow us to recreate the problem on a fresh Drupal install (including modules enabled, field type, field config, how it is used in layout, etc), it will be possible to write the tests that will allow this issue to get committed.
Comment #78
shaal@Anybody thank you for providing these clear steps.
@bnjmnm thank you for your continuous support.
I was able to replicate it, on a fresh Umami install:
drush si demo_umami -yComment #79
bnjmnm#78 is the info we need to get this moving again! (Thanks to everyone pre-#78 for the feedback that helped us get there too!)
If anyone happens to have bandwidth, it would be incredibly helpful to know what specific variables in Umami are causing the error so the bug can be reproduced on a bare Drupal install. Once that info is available I can take care of writing the tests that will be necessary to get this committed.
Comment #80
johnwebdev commented#79
1. Create a new content type 'Foo' enable it to be translatable
2. Add a entity reference field (i.e. Taxonomy), it should not be translatable.
3. Enable Layout builder
4. Manage layout
5. *WSOD*
#72 was on the right track!
On manage layout the entity would not have a Id, and this line would attempt to get the entity from the repository which fails.
Comment #81
johnwebdev commentedComment #82
bnjmnmThe steps in #80 had the info needed to create a test that reproduces the error reported in #56, #76, etc.
Attached is a test-only patch that should fail without the solution in #80, along with a patch that combines that test with the solution, which should patch. Lets see if the testbot agrees.
Comment #83
bnjmnmOn a local site, I managed to get this test to fail without the patch from #81, this is the test in the TEST-ONLY patch from #82 that is supposed to fail as reproduces the steps described in #80.
I'll try to revisit this some time this week and attempt to make a test that actually fails -- but if anyone else is excited to get this committed you are quite welcome to hop in and get the test from 2955392-82-TEST-ONLY to fail like it should have.
For this to be committed, we need a failing test to prove that the bugs reported in #56, #76etc are in core and not a specific site config (something I have no doubt about, btw, but we need that test to get it through the gate)
Comment #85
berdirNow I finally did run into a case where I could use this as well, so I decided to spend some time with it.
getActive() is IMHO the wrong API here. We might be calling this for an arbitrary specific revision and want to render *that* revision. getActive() loads the revision it thinks is best for this case. So we might end up with $items and $entity from different revisions, which doesn't sound like fun at all :) (That entity might not even have the same translations as the one we currently have).
What we really need is getTranslationFromContext(), which is the same as EntityViewBuilder::view() uses. That removes the need for an extra isNew() check because we don't need the id anymore. I wasn't quite sure what to do with that layout builder test, didn't touch it yet. IMHO it would be fine to remove that now.
Then I also improved the kernel test a bit. Some notes on that:
* The changed logic means the mocking approach that this used didn't really work anyore. What I did instead is change the default language and reset the language manager. That's much easier then.
* That did result in a weird problem where it thought that the site wasn't multilingual anymore. The reason for that is that EN didn't really exist as a configurable language, only the fixed default, and changing the default resulted in having only one language. I've also installed en.
* entity_test_translatable_UI_skip is a really weird entity type that we only use to test some edge case in the content_translation UI. The default multilingual test type is entity_test_mul, so I switched to that. We just need to grant the view test entity translations permission then.
Please test this :)
Comment #86
shaalI tested #85, together with #3051465: Revert "Taxonomies are only displayed in English" and it works as expected, taxonomies are being displayed correctly in Spanish.
Comment #87
dhirendra.mishra commentedComment #88
yahyaalhamadApplied patch #85, all our problems were solved. Nice job.
Comment #89
anybodyGreat, thank you so much @Berdir, I can also confirm #85 works perfectly. Thanks for your time and investigation!
I'll set this RTBC. Is it possible to get this into 8.8 or too late?
Comment #90
bnjmnmFor this to be committed, we still need a failing test that reproduces the bug reported in #56, #76 in order to prove that #85 addresses the specific issue reported.
Comment #91
berdirMy implementation is very different from the previous patch and does not have the have the issue that previous patches had, so no, I don't think explicit layout builder test coverage is needed. In fact, I think we should remove the existing layout builder test here as well, it wasn't actually failing before and if there is something there that isn't covered by tests yet for the layout builder module then I think that should be done in a separate issue.
That said, we can actually kind of test the scenario that failed, by not saving the relevant entities that we're testing with and it still works fine. A test-only patch of this specific scenario is however not possible because as mentioned, the code that failed on new entities simply doesn't exist anymore.
Comment #92
anybodyThank you @Berdir, #91 fixed #3063839: PHP message: Error: Call to a member function getEntityTypeId() on null in /var/www/html/drupal/web/core/lib/Drupal/Core/Entity/EntityViewBuilder.php on line 525 for us, which appeared with patch #62!
Comment #93
diego_mow commentedPatch #91 worked for me with Paragraphs.
RTBC
Comment #94
mdupontI confirm this patch fixed the problem I was having with translated Paragraph entities on Layout Builder pages. Before the patch, the entities were displayed in the default language only. After the patch, they are displayed in the correct translation depending on the context.
Comment #95
alexpottI think we can improve this by doing
Less else and less getEntity().
Here's the patch. Leaving at rtbc because this is not really changing the patch at all - just doing less to do the same.
Comment #96
berdirRepeating what I said on slack: The improvement makes sense to me.
Comment #97
johnwebdev commentedLooks good to me, haven't had the time to verify manually that the WSOD bug has been solved though, but by looking at it, it should.
Some minor doc thingies, but leaving at RTBC:
Should "points always" be flipped to "always points"?
Tests the viewField method
Comment #98
alexpott@johndevman good points. Fixed.
Comment #99
anybodyJust tested #98 manually in some environments again. Confirming RTBC!
Comment #100
diego_mow commentedRe-testing my scenario with new patch, and it also worked.
Comment #101
alexpottCrediting everyone who provided evidence of local testing and/or patch reviews.
Comment #102
alexpott@Berdir in #3 you discounted the solution in #2 which feels very similar to the solution in #91 and on. Does the old you still disagree with the new you?
Comment #103
berdirThe one important difference compared to #2 is that we now check whether or not the field is translatable, so at least we don't break anything that worked before. The view use case would have always shown the original language for untranslatable fields, now it would always show it in the current language.
I think this is an improvent for the 90% use case, and if someone really has a use case where they want to control the language and show something different, then they can figure out a solution for how to pass that language into the field, I'm not sure what the best approach for that would be, but this doesn't make easier or harder to do so IMHO.
But yes, we took a lot of interesting detours until we got back to a working solution...
Comment #104
alexpottGiven the number of followers and commenters we're probably above the 90% use-case. Going to commit the fix to 9.0.x and 8.9.x and ask other committers about backport to 8.8.x
Committed and pushed 1e04ea32c6 to 9.0.x and 94493f36dc to 8.9.x. Thanks!
Comment #107
yahyaalhamadComment #108
alexpott@catch and @webchick +1'd the backport to 8.8.x
Comment #111
tomsch commentedhi,
thanks a lot for the effort you guys put in solving this problem.
I use drupal 8.7.10 and without core patches both twig examples below render the default language. With patch #98 from this issue only Example 1 renders fine in all languages. With patch #20 from the duplicate FieldItemList::view() issue both examples render correctly across languages.
Am I using bad practice code? Is there a way to make this work (except for going via rendered entities directly -- with custom display modes if needed -- as in example 1)?
node.field_documentationcontains an entity reference to the content typedocumentation.Example 1
Example 2
Comment #112
makeaweli commented@tomsch I'm running 8.9.3 and am able to duplicate your issue with Example 2 not working. I would prefer to directly access the data rather than the rendered entity.
Comment #113
berdirExample 2 isn't meant to work with this, because title then is a translatable field and doesn't trigger the content language fallback. It's not possible to make that work magically without breaking other use cases like actually rendering it in a different language, with is not uncommon with views.
To make that work, you need to add a bit of php code in preprocess, as you can see in the patch, it is basically doing this:
So you want to build something like this:
That gives you a list of nodes with the best-available translation for the current content language, and you can loop over those in twig.
That said, I would recommend to use view modes. One thing that you're still missing with this is necessary cache tags for example, so if you change those documentation nodes, it won't invalidate that. you can support that too with another php line, but it just works with view modes. Alternatively, try https://www.drupal.org/project/field_formatter to render just a single field from a referenced entity.