Problem/Motivation

Drupal 8.7 marked Layout Builder as a stable module. We need to ensure there is a proper integration with products which allows embedding variation fields and that field injection still properly works.

Remaining tasks

  1. Add a context to ensure a product's default variation is present with a product
  2. Price field items need to generate sample data
  3. Test placement of variation fields
  4. Placeholder for the add to cart form when a product ID is unavailable (default layout edit)
  5. Test add to cart and field replacement
  6. Test variation field injection with LB installed but not enabled
  7. Test customizing a non-default view display mode (ie: teaser, catalog, etc custom)

Original summary

I have tried the layout builder in a fresh installation with core8.5.0 and latest dev version of commerce. I can see its a great step forward to layout the page but with problem for now.

1: With the layout builder enable, I am keep getting the error log message when I adjusting the commerce product :

Drupal\Component\Plugin\Exception\ContextException: Required contexts without a value: entity. in Drupal\Core\Plugin\Context\ContextHandler->applyContextMapping() (line 96 of /home/dpapercom/public_html/core/lib/Drupal/Core/Plugin/Context/ContextHandler.php).

and eventually the commerce product page is completely dead, whenever click on the product link to its page, its shows a ""The website encountered an unexpected error. Please try again later."" message, until I disable the layout builder, it live again.

2: with the layout builder it doesn't display the product variation image on the product page. after I disable the layout builder, the image will come back ( I have a image_field in the product variation type )

Thanks

CommentFileSizeAuthor
#107 LayOut.pdf539.43 KBlondova
#105 layoutbuilder products.png76.13 KBneograph734
#100 2952529-100.patch29.27 KBmglaman
#99 2952529-99.patch29.26 KBmglaman
#99 interdiff-2952529-98-99.txt3.01 KBmglaman
#98 2952529-97.patch28.89 KBmglaman
#98 interdiff-2952529-92-97.txt3.96 KBmglaman
#93 interdiff-88-92.txt5.99 KBvalic
#92 interdiff-88-92.patch5.99 KBvalic
#92 support_for_layout_b-2952529-92.patch29.05 KBvalic
#88 support_for_layout_b-2952529-88.patch23.3 KBmglaman
#88 interdiff-2952529-85-88.txt4.75 KBmglaman
#86 interdiff-2952529-83-86.txt6.13 KBmglaman
#86 support_for_layout_b-2952529-86.patch20.95 KBmglaman
#84 support_for_layout_b-2952529-84.patch20.8 KBmglaman
#84 interdiff-2952529-81-84.txt2.48 KBmglaman
#82 interdiff-2952529-80-82.txt1.12 KBmglaman
#82 support_for_layout_b-2952529-82.patch21.43 KBmglaman
#81 support_for_layout_b-2952529-81.patch22.55 KBmglaman
#77 interdiff_70_77.txt896 byteswaspper
#77 commerce-layout-builder-fixes-2952529-77.patch45.43 KBwaspper
#70 commerce-layout-builder-fixes-2952529-70.patch45.23 KBfreelock
#68 interdiff_59-68.txt3.88 KBmorbus iff
#68 2952529-68.patch25.42 KBmorbus iff
#63 layout-builder-sku-good.png104.37 KBmorbus iff
#63 layout-builder-sku-bad.png90.52 KBmorbus iff
#59 interdiff-42-59.txt1.15 KBctrladel
#59 2952529-59.patch25.46 KBctrladel
#42 2952529-42.patch25.46 KBmglaman
#39 2952529-39.patch22.91 KBmglaman
#37 2952529-37.patch21.18 KBmglaman
#36 2952529-36.patch16.52 KBmglaman
#31 interdiff-2952529-30-31.txt3.45 KBmglaman
#31 2952529-31.patch13.06 KBmglaman
#30 interdiff-2952529-29-30.txt1.32 KBmglaman
#30 2952529-30.patch13.17 KBmglaman
#28 Screen Shot 2019-05-15 at 10.35.39 PM.png166.14 KBmglaman
#28 interdiff-2952529-27-28.txt1.59 KBmglaman
#28 2952529-28.patch81.55 KBmglaman
#24 interdiff-2952529-23-24.txt6.25 KBmglaman
#24 2952529-24.patch12.46 KBmglaman
#22 2952529-22.patch10.03 KBmglaman
#22 interdiff-2952529-21-22.txt2.27 KBmglaman
#22 Screen Shot 2019-05-13 at 2.25.02 PM.png132.24 KBmglaman
#22 Screen Shot 2019-05-13 at 2.22.57 PM.png958.54 KBmglaman
#20 interdiff-2952529-19-20.txt9.06 KBmglaman
#20 support_for_layout_b-2952529-20.patch8.66 KBmglaman
#6 2952529-6.patch5.35 KBdravenk
#6 interdiff.txt1.06 KBdravenk
#5 node.png706.65 KBdravenk
#3 2952529-3.patch971 bytesdravenk

Comments

freelylw created an issue. See original summary.

mglaman’s picture

Project: Drupal core » Commerce Core
Version: 8.5.x-dev » 8.x-2.x-dev
Component: layout_builder.module » Product
Status: Active » Postponed

Layout Builder is experimental. Core doesn't provide an easy way to support embedded field injection, like ours. I have ideas, and we'll be syncing on this at DrupalCon Nashville.

dravenk’s picture

Status: Postponed » Needs review
StatusFileSize
new971 bytes

I don't understand why the layout build page calls the addToCartForm method, resulting in the empty product_id passed in. If the product_id is empty, it means that you don't need to add it to shopping cart.

mglaman’s picture

Title: layout builder error for commerce product » Support for Layout Builder (experimental) module
Category: Bug report » Feature request
Priority: Major » Normal
Status: Needs review » Needs work

I forgot about this issue! I have it working w/ LB in https://github.com/drupalcommerce/commerce/pull/854. This patch fixes main error, but my patch gives full support.

Changing the issue around. If an experimental module causes an error, I won't consider it a bug -- because it's experimental. Instead it is a feature request to support it.

#3 provides crash fix. My PR adds full support (adding variation fields.)

See https://twitter.com/nmdmatt/status/986002696401436675 for screenshots

dravenk’s picture

StatusFileSize
new706.65 KB

I think since product_id is empty, it should be returned. Because using an empty product_id as a conditional query is not logical and wasteful. there's still misinformation..Do you agree?
t

dravenk’s picture

Status: Needs work » Needs review
StatusFileSize
new1.06 KB
new5.35 KB

Contains the pull request mentioned in #4 and fix #5 error messages.

mglaman’s picture

Assigned: Unassigned » mglaman
Status: Needs review » Needs work
Issue tags: +Needs tests

Thanks for rolling in my patch.

+++ b/modules/product/src/ProductLazyBuilders.php
@@ -65,6 +65,10 @@ class ProductLazyBuilders {
+    // @todo Quickfix for Layout Builder
+    if (!$product_id) {
+      return [];
+    }

We should better handle this, as it causes LB to prevent the add to cart field block from being removed.

There's an LB issue to fix that (blocks with no content) but we should consider what to do here as well.

I'll be working on the final touches for this patch.

steinmb’s picture

@mglaman are you still working on this patch?

mglaman’s picture

I can pick it back up, time got away from me. The patch works "as is" but just is not ready for being committed. Also, per #7 we need to see if core handling blocks with no content.

mglaman’s picture

  1. +++ b/modules/price/src/Plugin/Field/FieldType/PriceItem.php
    @@ -146,4 +147,17 @@ class PriceItem extends FieldItemBase {
    +  /**
    +   * {@inheritdoc}
    +   */
    +  public static function generateSampleValue(FieldDefinitionInterface $field_definition) {
    +    $currencies = \Drupal::entityTypeManager()->getStorage('commerce_currency')->loadMultiple();
    +    $currency_codes = array_keys($currencies);
    +    $values = [
    +      'number' => '9.99',
    +      'currency_code' => reset($currency_codes),
    +    ];
    +    return $values;
    +  }
    +
    

    I want to see if we can improve this with the latest NumberFormatter fixes. It is overkill to load ALL the currencies (okay, it may only be one or two). But if we could just pass `USD` by default, that would look simpler.

  2. +++ b/modules/product/src/ContextProvider/LayoutBuilderProductVariationContext.php
    @@ -0,0 +1,71 @@
    +    /** @var \Drupal\commerce_product\Entity\ProductInterface $product */
    +    if ($product = $this->routeMatch->getParameter('commerce_product')) {
    +      $value = $product->getDefaultVariation();
    +    }
    

    We should be loading the default variation from variation storage. That is what filters out inactive or otherwise removed variations from the context.

  3. +++ b/modules/product/src/ContextProvider/LayoutBuilderProductVariationContext.php
    @@ -0,0 +1,71 @@
    +      $value = $sample_entity_generator->get('commerce_product_variation', $sample_product->bundle());
    

    In no way can we assume the variation has the same bundle as the product.

  4. +++ b/modules/product/src/ProductLazyBuilders.php
    @@ -65,6 +65,10 @@ class ProductLazyBuilders {
    +    // @todo Quickfix for Layout Builder
    +    if (!$product_id) {
    +      return [];
    +    }
    

    This needs to be tested.

lawxen’s picture

The drupal8.6's layout builder field_layout dosn't take effect on commerce_product's form display

lawxen’s picture

pavelculacov’s picture

This patch help me, but after clear cache i have error

Drupal\Core\Entity\EntityStorageException: Missing entity bundle. The "cakes" bundle does not exist in Drupal\Core\Entity\ContentEntityStorageBase->createWithSampleValues()
After debug "createWithSampleValues"

var_dump($bundle);
var_dump($this->entityTypeId);
var_dump($this->entityManager->getBundleInfo($this->entityTypeId));

string(5) "cakes"
string(26) "commerce_product_variation"
array(4) {
  ["cakes_variation"]=>
  array(3) {
    ["label"]=>
    string(15) "Cakes Variation"
    ["translatable"]=>
    bool(true)
    ["untranslatable_fields.default_translation_affected"]=>
    bool(false)
  }
  ["custom_cake"]=>
  array(2) {
    ["label"]=>
    string(11) "Custom Cake"
    ["translatable"]=>
    bool(false)
  }
  ["default"]=>
  array(2) {
    ["label"]=>
    string(7) "Default"
    ["translatable"]=>
    bool(false)
  }
  ["serial_cake"]=>
  array(3) {
    ["label"]=>
    string(11) "Serial Cake"
    ["translatable"]=>
    bool(true)
    ["untranslatable_fields.default_translation_affected"]=>
    bool(false)
  }
}

My product type bundle is not equal with product variant type bundle

andyg5000’s picture

This patch also appears to have caused the follow error on existing layouts

"PHP message: Uncaught PHP Exception Drupal\Component\Plugin\Exception\ContextException: "The 'entity:commerce_product_variation' context is required and not present." at /var/www/html/public/core/lib/Drupal/Core/Plugin/Context/Context.php line 73" while reading response header from upstream
pavelculacov’s picture

Own fix is

      $sample_entity_generator = \Drupal::getContainer()->get('layout_builder.sample_entity_generator');
//We must check if is ProductInterface because if we use layoutbuilder on Node page, it will broken
      if($sample_product instanceof ProductInterface)
        $value = $sample_entity_generator->get('commerce_product_variation', $sample_product->getDefaultVariation()->bundle());
mglaman’s picture

Assigned: mglaman » Unassigned
mindaugasd’s picture

Title: Support for Layout Builder (experimental) module » Support for Layout Builder module
mglaman’s picture

Assigned: Unassigned » mglaman

Picking this up on Monday.

mglaman’s picture

Per #15 the problem was mentioned in #10:

In no way can we assume the variation has the same bundle as the product.

The problem with Layout Builder is that we have two ways to edit a layout:

* Customizing a product's individual layout, where we have context of data
* Managing the default layout (admin/commerce/config/product-types/simple/edit/display/default/layout) where we have no data

We should be loading the variation type from the product type's config.

mglaman’s picture

Status: Needs work » Needs review
StatusFileSize
new8.66 KB
new9.06 KB

Okay, here is an updated patch which fixes our context delivery so that variation fields show up. This can be manually tested.

Next steps:

* test coverage
* fallback display for add to cart formatter

mglaman’s picture

Status: Needs review » Needs work

EDIT: I broke the form somehow. This comment is completely null and void.

----

When manually testing, an error occurs when trying to save a variation field into section

Drupal\Component\Plugin\Exception\MissingValueContextException: Required contexts without a value: entity in Drupal\Core\Plugin\Context\ContextHandler->applyContextMapping() (line 155 of /var/www/html/web/core/lib/Drupal/Core/Plugin/Context/ContextHandler.php).

The problem occurs in \Drupal\layout_builder\SectionComponent::getPlugin.

  public function getPlugin(array $contexts = []) {
    $plugin = $this->pluginManager()->createInstance($this->getPluginId(), $this->getConfiguration());
    if ($contexts && $plugin instanceof ContextAwarePluginInterface) {
      $this->contextHandler()->applyContextMapping($plugin, $contexts);
    }
    return $plugin;
  }

There is no context mapping passed applyContextMapping(ContextAwarePluginInterface $plugin, $contexts, $mappings = [])

---

We need to get the mapping defined. \Drupal\layout_builder\Form\ConfigureBlockFormBase::submitForm has the following

    // If this block is context-aware, set the context mapping.
    if ($this->block instanceof ContextAwarePluginInterface) {
      $this->block->setContextMapping($subform_state->getValue('context_mapping', []));
    }

In \Drupal\layout_builder\Entity\LayoutBuilderEntityViewDisplay the context mapping is always passed. EDIT this seems to only run when LB is first turned on.

      $configuration = [
        'label_display' => '0',
        'context_mapping' => ['entity' => 'layout_builder.entity'],
      ];

For variation fields we need to try and alter the context mapping to pull from the proper context definition.

--

Digging more. In \Drupal\Core\Plugin\ContextAwarePluginAssignmentTrait::addContextAssignmentElementthe context mapping gets set to a value element. if there were multiple satisfifying contexts, then one could be chosen. For some reason this isn't working for our embedded entities.

mglaman’s picture

Status: Needs work » Needs review
StatusFileSize
new958.54 KB
new132.24 KB
new2.27 KB
new10.03 KB

It is working! Now it is ready for the tests and fallback identified in #20

Pink boxes are the added variation fields.

Status: Needs review » Needs work

The last submitted patch, 22: 2952529-22.patch, failed testing. View results
- codesniffer_fixes.patch Interdiff of automated coding standards fixes only.

mglaman’s picture

This is blocked on a problem when there is no existing product data. See #3054492: Allow content entity storages to define forbidden keys when generating sample entity values

Here is a new patch to fix failures on the translation routes. Also the beginnings of tests, which highlight the blocker failure.

Status: Needs review » Needs work

The last submitted patch, 24: 2952529-24.patch, failed testing. View results
- codesniffer_fixes.patch Interdiff of automated coding standards fixes only.

mglaman’s picture

Crediting tim.plunkett for the Slack support and guidance for core issues

mglaman’s picture

Status: Needs work » Needs review
StatusFileSize
new81.55 KB
new1.59 KB
new166.14 KB

This attempts to fix some problems. But I found more. Generating variations is missing the bundle for the variations.

The variations entity reference is invoked for \Drupal\Core\Field\FieldItemList::generateSampleItems.

But \Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem::generateSampleValue is dying. It fails when there are no bundles specified

    $entity_storage = \Drupal::entityTypeManager()->getStorage($options['target_type']);
    if ($entity_storage instanceof ContentEntityStorageInterface) {
      $bundle = static::getRandomBundle($entity_type, $options['handler_settings']);

      // Track the generated entity by reference type, target type, and bundle.
      $key = $field_definition->getTargetEntityTypeId() . ':' . $options['target_type'] . ':' . $bundle;

      // If entity generation was attempted but did not finish, do not continue.
      if (isset($recursion_tracker[$key])) {
        return [];
      }

The bundle is just "0" when passed.

But we define the bundle in commerce_product_add_variations_field for the FieldConfig.

    ->setSetting('handler_settings', [
      'target_bundles' => [
        $product_type->getVariationTypeId(),
      ],
    ])

Our default config is correct field.field.commerce_product.default.variations.yml

settings:
  handler: 'default:commerce_product_variation'
  handler_settings:
    target_bundles:
      - default
mglaman’s picture

🤔I looks like this core function is always returning the key and not the values.

\Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem::getRandomBundle

  protected static function getRandomBundle(EntityTypeInterface $entity_type, array $selection_settings) {
    if ($bundle_key = $entity_type->getKey('bundle')) {
      if (!empty($selection_settings['target_bundles'])) {
        $bundle_ids = $selection_settings['target_bundles'];
      }
      else {
        $bundle_ids = \Drupal::service('entity_type.bundle.info')->getBundleInfo($entity_type->id());
      }
      return array_rand($bundle_ids);
    }

That's because of our field definition being incorrect

We have

 - default

when it should be

default: default
mglaman’s picture

StatusFileSize
new13.17 KB
new1.32 KB

This changes the field information. Also prevents the product context from generating variations. We'll see where this goes.

  1. +++ b/modules/product/commerce_product.services.yml
    --- a/modules/product/config/install/field.field.commerce_product.default.variations.yml
    +++ b/modules/product/config/install/field.field.commerce_product.default.variations.yml
    
    +++ b/modules/product/config/install/field.field.commerce_product.default.variations.yml
    @@ -19,5 +19,5 @@ settings:
    -      - default
    +      default: default
    

    TBD: Should this spin out into its own issue? It's a general bug.

  2. +++ b/modules/product/src/ContextProvider/ProductRouteContext.php
    @@ -45,9 +52,10 @@ class ProductRouteContext implements ContextProviderInterface {
    +      $value = $this->productStorage->createWithSampleValues($product_type->id(), [
    +        'variations' => NULL,
    +      ]);
    
    +++ b/modules/product/src/ContextProvider/ProductVariationContext.php
    @@ -0,0 +1,95 @@
    +        $value = $this->productVariationStorage->createWithSampleValues($product_type->getVariationTypeId(), [
    +          'product_id' => NULL,
    +        ]);
    ...
    +          $value = $this->productVariationStorage->createWithSampleValues($product_type->getVariationTypeId(), [
    +            'product_id' => NULL,
    +          ]);
    

    With tests passing and the field config identified as the main issue, do we need these?

  3. +++ b/modules/product/src/ProductLazyBuilders.php
    @@ -65,6 +65,13 @@ class ProductLazyBuilders {
    +    if (!$product_id) {
    +      // `\Drupal\layout_builder\Plugin\Block\FieldBlock::getPreviewFallbackString()`
    +      // Override for the add to cart field formatter so we never get an empty
    +      // product ID.
    +      // @see https://www.drupal.org/project/drupal/issues/3027653
    +      return [];
    +    }
    

    Still to be worked.

mglaman’s picture

StatusFileSize
new13.06 KB
new3.45 KB

Okay, the tests pass. Here is a patch which removes the create sample method calls with null values to see if the original reasoning behind #3054492: Allow content entity storages to define forbidden keys when generating sample entity values is moot.

I also had random failures locally. This change ensures the Add Block link is in the viewport.

-    $this->getSession()->getPage()->clickLink('Add Block');
+    $add_block = $this->getSession()->getPage()->findLink('Add Block');
+    $add_block->focus();
+    $add_block->click();
mglaman’s picture

Issue summary: View changes
mglaman’s picture

Issue summary: View changes
mglaman’s picture

mglaman’s picture

+++ b/modules/product/src/ProductViewBuilder.php
@@ -72,7 +73,7 @@ class ProductViewBuilder extends EntityViewBuilder {
-    if ($product_type->shouldInjectVariationFields() && $entity->getDefaultVariation()) {
+    if (!($display instanceof LayoutEntityDisplayInterface) && $product_type->shouldInjectVariationFields() && $entity->getDefaultVariation()) {
       $variation = $variation_storage->loadFromContext($entity);

This was breaking variation field injection for product types without layout builder enabled.

We're missing test coverage to ensure field injection works with LB installed but not enabled.

The new check should probably involved

$is_layout_builder = $display instanceof LayoutEntityDisplayInterface && $display->isLayoutBuilderEnabled();
mglaman’s picture

Issue summary: View changes
Status: Needs work » Needs review
StatusFileSize
new16.52 KB

This patch

* Adds a preview fallback for the formatter if the product has been flagged as "in_preview".
* Fixes variation field injection when LB installed but not used

All that remains is now testing field injection over AJAX with the add to cart form.

mglaman’s picture

StatusFileSize
new21.18 KB

I've added a test for overriding the default layout on a product. Locally it is erroring but I need to hit the pause button. Seeing if DrupalCI has different results.

Status: Needs review » Needs work

The last submitted patch, 37: 2952529-37.patch, failed testing. View results
- codesniffer_fixes.patch Interdiff of automated coding standards fixes only.

mglaman’s picture

Status: Needs work » Needs review
StatusFileSize
new22.91 KB

New tests. New problems.

* Overrides for the layout won't save in the tests
* Field replacement is broken due to missing CSS classes from variation fields added via field blocks.

---

Field replacement. We will need a custom block to extend \Drupal\layout_builder\Plugin\Block\FieldBlock and ensure all variation fields use our custom block class.

We'll need to override \Drupal\layout_builder\Plugin\Block\FieldBlock::build. We'll basically have to replace its logic a call to \Drupal\commerce_product\ProductVariationFieldRenderer::renderField.

andypost’s picture

Thanks for pointing different processing for empty fields, looks it needs core issue to document at least... It helps in #3055574: Empty field for Drupal core Layout builder (layout_builder)

Status: Needs review » Needs work

The last submitted patch, 39: 2952529-39.patch, failed testing. View results
- codesniffer_fixes.patch Interdiff of automated coding standards fixes only.

mglaman’s picture

Status: Needs work » Needs review
StatusFileSize
new25.46 KB

Checkpoint. This adds VariationFieldBlock for variations to use our renderer.

Status: Needs review » Needs work

The last submitted patch, 42: 2952529-42.patch, failed testing. View results
- codesniffer_fixes.patch Interdiff of automated coding standards fixes only.

pavelculacov’s picture

D 8.7

\web\core\lib\Drupal\Core\Plugin\Context\ContextHandler.php:146:
array (size=1)
  'entity' => string '@commerce_product.layout_builder_product_variation_context:commerce_product_variation' (length=85)
The website encountered an unexpected error. Please try again later.

Drupal\Component\Plugin\Exception\ContextException: Assigned contexts were not satisfied: entity in Drupal\Core\Plugin\Context\ContextHandler->applyContextMapping() (line 151 of core\lib\Drupal\Core\Plugin\Context\ContextHandler.php).
mglaman’s picture

@Regnoy in which builder context did this happen? When managing the default layout or an override for a project? When adding a block? When viewing the layout editor?

pavelculacov’s picture

Before your patch i use from comment #6

Now i have error, Can help me to remove programmaticaly
"layout_builder_product_variation_context:commerce_product_variation" from already saved Commerce Product Type

mglaman’s picture

@Regnoy I cannot assist you without more details as I requested in #45, the context is required for product variation fields and I don't know how to replicate your error without those details.

pavelculacov’s picture

@mglaman Thanks for response.

If somebody use patch #6 before and then #42

Just add in commerce > commerce_product.services.yml with your class ProductVariationContext

commerce_product.layout_builder_product_variation_context:
    class: Drupal\commerce_product\ContextProvider\ProductVariationContext
    arguments: ['@current_route_match', '@entity_type.manager']
    tags:
      - { name: 'context_provider' }

And remove block from layout builder, and after thant remove this services from yml. This help me

steinmb’s picture

I have time to put the patch through some manual testing. But before I test it, #42 failed. Do we need tests to pass first?

mglaman’s picture

@steinmb it can be tested to find bugs. The noticeable failure from #42 is that fields are not replaced.

christian.wiedemann’s picture

I tested it manually with some product types.

Got following error when:

  1. Use layout builder for teaser view mode
  2. Add price field to the layout. (Or any other variation fields)
  3. List them in a view
The website encountered an unexpected error. Please try again later.</br></br><em class="placeholder">Drupal\Component\Plugin\Exception\MissingValueContextException</em>: Required contexts without a value: entity in <em class="placeholder">Drupal\Core\Plugin\Context\ContextHandler-&gt;applyContextMapping()</em> (line <em class="placeholder">155</em> of <em class="placeholder">core/lib/Drupal/Core/Plugin/Context/ContextHandler.php</em>). <pre class="backtrace">Drupal\layout_builder\SectionComponent-&gt;getPlugin(Array) (Line: 69)
Drupal\layout_builder\Event\SectionComponentBuildRenderArrayEvent-&gt;__construct(Object, Array, ) (Line: 111)
Drupal\layout_builder\SectionComponent-&gt;toRenderArray(Array, ) (Line: 86)
Drupal\layout_builder\Section-&gt;toRenderArray(Array) (Line: 308)
mglaman’s picture

@Christian.wiedemann thanks for the report! This was in the default layout builder config mode on the admin side, then, for teasers?

christian.wiedemann’s picture

Yes in config mode (admin/commerce/config/product-types/suit/edit/display/teaser/layout). I just want to render a product list with "view mode" teaser. And I manage the teaser with layout builder.

mglaman’s picture

Issue summary: View changes

Thanks! I have not yet tried to manage anything but the default display; I didn't expect this problem :/ good findings!

christian.wiedemann’s picture

Got following error:

AssertionError: assert($context instanceof ProductInterface) in assert() (line 80 of modules/contrib/commerce/modules/product/src/ContextProvider/ProductVariationContext.php).

assert(, 'assert($context instanceof ProductInterface)') (Line: 80)
Drupal\commerce_product\ContextProvider\ProductVariationContext->getRuntimeContexts(Array) (Line: 102)
Drupal\commerce_product\ContextProvider\ProductVariationContext->getAvailableContexts() (Line: 97)
Drupal\Core\Plugin\Context\LazyContextRepository->getAvailableContexts() (Line: 44)
Drupal\layout_builder\Element\LayoutBuilder->getAvailableContexts(Object) (Line: 265)

Steps to reproduce:

  • Nodetype Landingpage
  • Check option: "Allow each content item to have its layout customized." under "admin/structure/types/manage/landing_page/display/full"
  • Create a node of type landing_page
  • Click on "Layout". "en/node/NID/layout"

A quick fix is:

         if ($context instanceof ProductInterface) {
            $value = $context->getDefaultVariation();
            if ($value === NULL) {
              $product_type = ProductType::load($context->bundle());
              $value = $this->productVariationStorage->createWithSampleValues($product_type->getVariationTypeId());
            }  
          }

But not sure if this works.

mglaman’s picture

So you're getting the error on a node layout form? This hasn't been tested against nodes. Can you provide more details on your node setup? This has only been tested on configuring the product entity view display.

ctrladel’s picture

Note that core versions previous to 8.7.2 will need this patch https://www.drupal.org/project/drupal/issues/3053529 to enable the "Allow each product to have its layout customized." option on products.

christian.wiedemann’s picture

yes the error occurs when I use the layout builder for a "singel customaized node". Layoutbuilder still works when I use Layout Builder for the node type.

ctrladel’s picture

StatusFileSize
new25.46 KB
new1.15 KB

Ran into the assertion exception on node edit as well, here's a patch that changes it to an if statement like in #55. This does allow the value to be null when the context is returned but that seems okay based on what other getRuntimeContexts() implementations are doing.

ajits’s picture

Status: Needs work » Needs review

To trigger the test bot. I see a couple of tabs instead of spaces in the code though (interdiff file line 85 and 86).

Status: Needs review » Needs work

The last submitted patch, 59: 2952529-59.patch, failed testing. View results
- codesniffer_fixes.patch Interdiff of automated coding standards fixes only.

pavelculacov’s picture

Last Patch Not working with this issue last patch

EntityViewBuilder::viewField() does not respect entity current language when used with an entity reference field

Is working only with this compatibility
1) "Support for Layout Builder module" : "https://www.drupal.org/files/issues/2019-05-20/2952529-42.patch"
2) "EntityViewBuilder::viewField() does not respect entity current language when used with an entity reference field" : "https://www.drupal.org/files/issues/2019-05-03/entity-view-builder-entit..."

morbus iff’s picture

StatusFileSize
new90.52 KB
new104.37 KB

#59 (without the patch from #2955392: EntityViewBuilder::viewField() does not respect entity current language when used with an entity reference field) is working pretty good for me so far, with some slight concerns:

  1. The SKU default content appears, at times, to generate some incredibly long strings without spaces. This causes my particular Bootstrap theme to break, distorting the Layout Builder preview. Screenshots attached: layout-builder-sku-good.png shows the generated SKU being short and the layout displaying as I'd expect; layout-builder-sku-bad.png shows a long SKU being generated and breaking the display. This particular "long SKU" is only about medium-sized: I've seen some that generate enough to roll off the page.
  2. The "List price" field (layout-builder-sku-good.png) generates some preview content, but the "Price" field doesn't. I would assume both fields should do the same thing.
morbus iff’s picture

Assuming:

* a product's default entity_view_display is customized with Layout Builder
* and that layout contains product variant fields

Then:

* Viewing a product without any product variations
** For example, creating a product and hitting "Save" instead of "Save and add variations"

Causes the following error:

The website encountered an unexpected error. Please try again later.</br></br><em class="placeholder">Drupal\Component\Plugin\Exception\MissingValueContextException</em>: Required contexts without a value: entity in <em class="placeholder">Drupal\Core\Plugin\Context\ContextHandler-&gt;applyContextMapping()</em> (line <em class="placeholder">155</em> of <em class="placeholder">core/lib/Drupal/Core/Plugin/Context/ContextHandler.php</em>). <pre class="backtrace">Drupal\layout_builder\SectionComponent-&gt;getPlugin(Array) (Line: 69)

morbus iff’s picture

Another small hiccup, and this requires some setup.

* Create product type A and product type B.
* On product type A, create a Reference field to product type B. Call it "Similar Products".
* Create three product type B products.
* Create one product type A product that references all three product type Bs.

* For product type B, Manage Display and choose Layout Builder.
* Add the product title field.
* Add the variation price field.

* For product type A, Manage Display, and choose Layout Builder.
* Add the "Similar Products" Reference field you created above, with Formatter "Rendered entity".

* View your product type A product.
* For the "Similar Items" Reference render:
** You should see the correct product B entity titles.
** But you'll see the product A price instead of the product B price.
** Any other variation field from B will be replaced with A's version instead.

Now:

* Head back to product type B, Manage Display, unchoose Layout Builder.
* Add the product title field.
* Add the variation price field.
* View your product type A product.
* The product type B References should be correct now.

morbus iff’s picture

And another:

# Create a product type with "Inject product variation fields into the rendered product."
# Create a Color product attribute with Black, Blue, and Red. Assign it to your product type.
# Create a product of that type with three variations:
## Each product variation should have a different price.
## Each product variation should have a different attribute.
# For your product type's "Manage display", use Layout Builder and display SKU, Price, and Variations.
## For the SKU and Price fields, set the Label to "Hidden".
# Load the product.

On initial product page load, you should see the first variation's SKU (without a field label) and Price (without a field label). Great. Upon selecting a different variation though, the AJAX load occurs, and you should see the Price change to the new variation's price. However, a) this new price is displayed with the "Price: " field label, and b) the SKU field does not change. You're now seeing the second variation's (AJAX-loaded) price with the first variation's (initial page-loaded) SKU.

The cause appears to be because the AJAX will load only the configuration from the "Manage Display" of the product variation, NOT any of the configuration from the "Manage Display" Layout Builder of the product. By default, a product variation's "Manage Display" does not display SKU, so that's never returned in the AJAX and thus is never updated in the rendered Layout Builder product. Similarly, a product variation's default "Manage Display" displays "Price" with the Label, so that label is returned/shown in the AJAX, and ignores ("breaks") the product's Layout Builder render. The same occurs with custom added fields: an image added to the product variation will be returned in the AJAX based on the product variation's "Manage Display" configuration, not the product's "Manage Display" Layout Builder configuration.

One possible site-builder workaround is to ensure that your product variation's "Manage Display" is just as "perfect" as your product's "Manage Display" LB (matching displayed fields, label configuration, etc.). However, this breaks down a little bit when you use Block Class within Layout Builder to assign CSS classes to a field, which you can't do in a normal non-LB "Manage Display" (without an extra contrib module, at least).

michaelprflores’s picture

Issue summary: View changes
morbus iff’s picture

StatusFileSize
new25.42 KB
new3.88 KB

#59 no longer cleanly applies to 2.15. Updated patch attached, including fixes:

* removed unused (but added in #59) Drupal\Core\Url.
* spelling correction of current to currency.
* spaces/tab cleanup.
* missing doxygen added.

londova’s picture

I have a similat problem, while using Commerce with "Bootstrap Layouts" module.
The price field is not visible, while the others look OK.

freelock’s picture

Status: Needs work » Needs review
StatusFileSize
new45.23 KB

Rerolled #68 for Commerce 8.x-2.16.

pavelculacov’s picture

+1 Working

mglaman’s picture

Assigned: mglaman » Unassigned

😬 forgot to remove myself. I'm currently helping support a project which has #70. Hopefully I can use this as a chance to land this issue for the next release.

londova’s picture

Sounds great. I am also waiting to get it published.

londova’s picture

Is it possible to close this issue now, so it can be implemented in the new commerce version?

morbus iff’s picture

@Londova/#74: This issue is the primary source of getting it implemented in the next Commerce. #70 is working for me (excepting the bugs I've mentioned), under Commerce 2.16.

morbus iff’s picture

Status: Needs review » Needs work

Setting this back to "Needs work". The current patch in #70 gets us half-way there, but there's still a lot of room for improvement (at least #63, #64, #65, and #66).

waspper’s picture

I've faced following bug after applying patch in #70, by trying to add a translation to any field:

Error: Call to a member function getVariationTypeId() on string in Drupal\commerce_product\ContextProvider\ProductVariationContext->getRuntimeContexts() (line 65 of /var/www/html/web/modules/contrib/commerce/modules/product/src/ContextProvider/ProductVariationContext.php)

But after checking, I've seen it's just needed a small validation before trying to get variation type ID at line 65 of commerce/modules/product/src/ContextProvider/ProductVariationContext.php. So, by just loading product type, it's ok again.

Attached newer patch, with small change. Leaved as "Needs works" to allow processing pending topics.

batkor’s picture

#70 patch worked for my.
Drupal 8.8.1
One language

mglaman’s picture

Assigned: Unassigned » mglaman
Status: Needs work » Needs review

Reviewing. This will never land perfectly. I'd like to see why we have test failures and try to get this in for 2.19, then lead for follow ups.

mglaman’s picture

Status: Needs review » Needs work
  1. +++ b/modules/cart/tests/src/FunctionalJavascript/AddToCartFieldReplacementTest.php
    @@ -68,6 +68,7 @@ class AddToCartFieldReplacementTest extends CartWebDriverTestBase {
    diff --git a/modules/cart/tests/src/FunctionalJavascript/AddToCartFieldReplacementTest.php.orig b/modules/cart/tests/src/FunctionalJavascript/AddToCartFieldReplacementTest.php.orig
    
    diff --git a/modules/cart/tests/src/FunctionalJavascript/AddToCartFieldReplacementTest.php.orig b/modules/cart/tests/src/FunctionalJavascript/AddToCartFieldReplacementTest.php.orig
    new file mode 100644
    
    new file mode 100644
    index 00000000..72bf304e
    
    index 00000000..72bf304e
    --- /dev/null
    
    --- /dev/null
    +++ b/modules/cart/tests/src/FunctionalJavascript/AddToCartFieldReplacementTest.php.orig
    

    😬somehow we got a patch containing a .orig file from a failed apply?

  2. +++ b/modules/price/src/Plugin/Field/FieldType/PriceItem.php
    @@ -150,4 +151,24 @@ class PriceItem extends FieldItemBase {
    +  /**
    +   * {@inheritdoc}
    +   */
    +  public static function generateSampleValue(FieldDefinitionInterface $field_definition) {
    +    $available_currencies = array_filter($field_definition->getSetting('available_currencies'));
    +    if (count($available_currencies) === 0) {
    +      /** @var \Drupal\commerce_price\Entity\CurrencyInterface[] $currencies */
    +      $currencies = \Drupal::entityTypeManager()->getStorage('commerce_currency')->loadMultiple();
    +      $sample_currency_code = reset($currencies)->getCurrencyCode();
    +    }
    +    else {
    +      $sample_currency_code = reset($available_currencies);
    +    }
    +    $values = [
    +      'number' => '9.99',
    +      'currency_code' => $sample_currency_code,
    +    ];
    +    return $values;
    +  }
    +
    

    We should make this its own issue, actually. Helps reduce this patch size.

  3. +++ b/modules/product/commerce_product.module
    @@ -345,3 +347,17 @@ function commerce_product_config_schema_info_alter(&$definitions) {
    +function commerce_product_block_alter(array &$info) {
    +  if (\Drupal::moduleHandler()->moduleExists('layout_builder')) {
    +    $base_plugin_id = 'field_block' . PluginBase::DERIVATIVE_SEPARATOR . 'commerce_product_variation' . PluginBase::DERIVATIVE_SEPARATOR;
    +    foreach ($info as $block_plugin_id => $block_definition) {
    +      if (strpos($block_plugin_id, $base_plugin_id) !== FALSE) {
    +        $info[$block_plugin_id]['class'] = VariationFieldBlock::class;
    +      }
    

    Would be great to see if Layout Builder improved at all to make this easier.

  4. +++ b/modules/product/commerce_product.module
    @@ -345,3 +347,17 @@ function commerce_product_config_schema_info_alter(&$definitions) {
    diff --git a/modules/product/commerce_product.module.orig b/modules/product/commerce_product.module.orig
    
    diff --git a/modules/product/commerce_product.module.orig b/modules/product/commerce_product.module.orig
    new file mode 100644
    
    new file mode 100644
    index 00000000..1bec0aa8
    
    index 00000000..1bec0aa8
    --- /dev/null
    
    --- /dev/null
    +++ b/modules/product/commerce_product.module.orig
    
    +++ b/modules/product/commerce_product.module.orig
    +++ b/modules/product/commerce_product.module.orig
    @@ -0,0 +1,347 @@
    

    😬no wonder why the patch is so huge :/ another failed hunk file.

  5. +++ b/modules/product/commerce_product.services.yml
    @@ -25,7 +25,12 @@ services:
       commerce_product.product_route_context:
         class: Drupal\commerce_product\ContextProvider\ProductRouteContext
    -    arguments: ['@current_route_match']
    +    arguments: ['@current_route_match', '@entity_type.manager']
    +    tags:
    +      - { name: 'context_provider' }
    
    +++ b/modules/product/src/ContextProvider/ProductRouteContext.php
    @@ -26,14 +27,24 @@ class ProductRouteContext implements ContextProviderInterface {
    +  /**
    +   * The product storage.
    +   *
    +   * @var \Drupal\Core\Entity\ContentEntityStorageInterface
    +   */
    +  protected $productStorage;
    +
    ...
    +   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
    +   *   The entity type manager.
        */
    -  public function __construct(RouteMatchInterface $route_match) {
    +  public function __construct(RouteMatchInterface $route_match, EntityTypeManagerInterface $entity_type_manager) {
         $this->routeMatch = $route_match;
    +    $this->productStorage = $entity_type_manager->getStorage('commerce_product');
    
    @@ -45,9 +56,8 @@ class ProductRouteContext implements ContextProviderInterface {
    -    elseif ($this->routeMatch->getRouteName() == 'entity.commerce_product.add_form') {
    -      $product_type = $this->routeMatch->getParameter('commerce_product_type');
    -      $value = Product::create(['type' => $product_type->id()]);
    +    elseif ($product_type = $this->routeMatch->getParameter('commerce_product_type')) {
    +      $value = $this->productStorage->createWithSampleValues($product_type->id());
    

    🤔this could be its own issue, too. To improve the route context provider.

  6. +++ b/modules/product/commerce_product.services.yml
    @@ -25,7 +25,12 @@ services:
    +  commerce_product.product_variation_route_context:
    +    class: Drupal\commerce_product\ContextProvider\ProductVariationContext
    +    arguments: ['@current_route_match', '@entity_type.manager']
         tags:
           - { name: 'context_provider' }
    
    +++ b/modules/product/src/ContextProvider/ProductRouteContext.php
    @@ -45,9 +56,8 @@ class ProductRouteContext implements ContextProviderInterface {
    diff --git a/modules/product/src/ContextProvider/ProductVariationContext.php b/modules/product/src/ContextProvider/ProductVariationContext.php
    
    diff --git a/modules/product/src/ContextProvider/ProductVariationContext.php b/modules/product/src/ContextProvider/ProductVariationContext.php
    new file mode 100644
    
    new file mode 100644
    index 00000000..7fd3469b
    
    index 00000000..7fd3469b
    --- /dev/null
    
    --- /dev/null
    +++ b/modules/product/src/ContextProvider/ProductVariationContext.php
    

    We should spin this into its own issue as well.

  7. +++ b/modules/product/src/Plugin/Block/VariationFieldBlock.php
    @@ -0,0 +1,36 @@
    +    $variation_field_renderer = \Drupal::getContainer()->get('commerce_product.variation_field_renderer');
    

    😬dependency injection

  8. +++ b/modules/product/tests/src/Functional/ProductVariationFieldInjectionTest.php
    @@ -112,6 +112,15 @@ class ProductVariationFieldInjectionTest extends ProductBrowserTestBase {
    +  public function testInjectedFieldsWithLayoutBuilderInstalled() {
    +    $this->container->get('module_installer')->install(['layout_builder']);
    +    $this->rebuildContainer();
    +    $this->testInjectedVariationDefault();
    

    🤔does this do anything if there's no Layout Builder override, even.

mglaman’s picture

Status: Needs work » Needs review
StatusFileSize
new22.55 KB

Here's a reroll of #77 with the *.orig files removed and the following child issues:

Not sure if this one should be spun out #3145079: Provide a product variation context.

mglaman’s picture

Oops, the price field changes still merged over, even though they were committed.

Status: Needs review » Needs work

The last submitted patch, 82: support_for_layout_b-2952529-82.patch, failed testing. View results
- codesniffer_fixes.patch Interdiff of automated coding standards fixes only.

mglaman’s picture

Status: Needs work » Needs review
StatusFileSize
new2.48 KB
new20.8 KB

Fix of the following:

  1. +++ b/modules/cart/tests/src/FunctionalJavascript/AddToCartFieldReplacementTest.php
    @@ -68,6 +68,7 @@ class AddToCartFieldReplacementTest extends CartWebDriverTestBase {
           'bundle' => 'default',
    +      'label' => 'Test Number Field',
           'settings' => [],
    

    Not needed

  2. +++ b/modules/product/src/ContextProvider/ProductVariationContext.php
    @@ -0,0 +1,111 @@
    +use Drupal\Core\Plugin\Context\ContextDefinition;
    

    use EntityContextDefinition to fix deprecations


Notes for self

  1. +++ b/modules/product/src/Plugin/Field/FieldFormatter/AddToCartFormatter.php
    @@ -64,10 +64,23 @@ class AddToCartFormatter extends FormatterBase {
    +    if ($product->id() === NULL) {
    

    Use isNew instead

  2. +++ b/modules/product/src/ProductViewBuilder.php
    @@ -81,7 +82,8 @@ class ProductViewBuilder extends EntityViewBuilder {
    -    if ($product_type->shouldInjectVariationFields() && $entity->getDefaultVariation()) {
    +    $is_layout_builder = $display instanceof LayoutEntityDisplayInterface && $display->isLayoutBuilderEnabled();
    +    if (!$is_layout_builder && $product_type->shouldInjectVariationFields() && $entity->getDefaultVariation()) {
    

    The product type is already loaded, but maybe we should make this an earlier exit before we fetch storages and load the product type.

Status: Needs review » Needs work

The last submitted patch, 84: support_for_layout_b-2952529-84.patch, failed testing. View results
- codesniffer_fixes.patch Interdiff of automated coding standards fixes only.

mglaman’s picture

Status: Needs work » Needs review
StatusFileSize
new20.95 KB
new6.13 KB

I think this fixes the tests. It was hit or miss locally, assuming that it is my local.

Status: Needs review » Needs work

The last submitted patch, 86: support_for_layout_b-2952529-86.patch, failed testing. View results
- codesniffer_fixes.patch Interdiff of automated coding standards fixes only.

mglaman’s picture

Status: Needs work » Needs review
StatusFileSize
new4.75 KB
new23.3 KB

So we're back to the same problems in #42.

Ajax field replacement for variations is not working. If you're using Cart Flyout it isn't noticeable, since replacement is done in JavaScript. But it doesn't work for our normal add to cart form. It's not working unless you allow all fields on a variation to be rendered.

\Drupal\commerce_product\Plugin\Field\FieldWidget\ProductVariationWidgetBase::ajaxRefresh invokes \Drupal\commerce_product\ProductVariationFieldRendererInterface::replaceRenderedFields which uses the variation view mode. That doesn't account for the field blocks added to the product layout.

For some reason, ProductLayoutBuilderIntegrationTest::testConfiguringOverrideLayout fails to save the override.


EDIT

To fix AJAX field replacement:

  • We would need to get the product's Layout Builder display
  • Find all variation field blocks
  • Pass their formatter config to \Drupal\commerce_product\ProductVariationFieldRenderer::renderField

That means we may need a swapped \Drupal\commerce_product\ProductVariationFieldRendererInterface::replaceRenderedFields implementation when Layout Builder is installed which doesn't try to use the variation's display config.

Status: Needs review » Needs work

The last submitted patch, 88: support_for_layout_b-2952529-88.patch, failed testing. View results
- codesniffer_fixes.patch Interdiff of automated coding standards fixes only.

mglaman’s picture

Assigned: mglaman » Unassigned

Sorry, this won't make 2.19.

@Morbus Iff has outlined all of the problems with missing variation field AJAX replacement in #63, #64, #65, #66.

valic’s picture

Status: Needs work » Needs review
StatusFileSize
new29.05 KB
new5.99 KB

Reroll of #88 with fix / implementation of ajax field replacement.

Added service provider to swap ProductVariationFieldRenderer with ProductVariationFieldRendererLayoutBuilder
which implements it's own replaceRenderedFields, with fallback to default version (if layout builder module is on, but it's not used)

Current implementation ProductVariationFieldRendererLayoutBuilder covers both default per bundle and custom per each entity layouts.
Tests should be green now.

valic’s picture

StatusFileSize
new5.99 KB

Attaching proper interdiff, by mistake had uploaded with .patch extension on #92

Regarding #63 and long SKU, not sure what we can do there, sampling for string field item (which is sku field) is done with fetching settings
$field_definition->getSetting('max_length'), and SKU does not have limit.

#66 is covered with last patch

londova’s picture

Hi,
Layout Builder is a part of Drupal core for a long time.
The fact that Commerce does NOT support all the Core functionalities is a shame for maintainers and shoud bring it back to "Beta" version.

tim.plunkett’s picture

I think that's unfair to Commerce. I say that as the primary developer of Layout Builder.
Next week will be the 3rd anniversary of Commerce 8.x-2.0, Layout Builder was added to core well after that and has only been stable for half of that time.

Please be patient with the volunteers who maintain modules!

mglaman’s picture

@Londova thanks for your feedback. Sorry you feel we should make an e-commerce framework beta due to a core feature which was experimental for most of our stable release cycle. If you'd like, we are always available for sponsored contribution development: https://www.centarro.io/products/centarro-support.

Here's a review. I'm pretty sure this is it. Just some code nits.

  1. +++ b/modules/product/src/ProductVariationFieldRendererLayoutBuilder.php
    @@ -0,0 +1,106 @@
    +    $view_mode_display = $this->entityDisplayRepository->getViewDisplay($product->getEntityTypeId(), $product->bundle());
    

    We should be passing the $view_mode, shouldn't?

  2. +++ b/modules/product/src/ProductVariationFieldRendererLayoutBuilder.php
    @@ -0,0 +1,106 @@
    +    // Check if layouts are enabled for that product.
    +    if ($view_mode_display instanceof LayoutBuilderEntityViewDisplay && $view_mode_display->isLayoutBuilderEnabled()) {
    +      // Grab sections from bundle layout view mode.
    +      $sections = $view_mode_display->getSections();
    +
    +      // If overrides are allowed, fetch them if they exists.
    +      if ($view_mode_display->isOverridable() && $overrides = $this->getEntitySections($variation->getProduct())) {
    +        $sections = $overrides;
    +      }
    +
    +      // Render fields for output.
    +      $rendered_fields = $this->renderLayoutBuilderFields($variation, $sections);
    +    }
    

    This logic seems like it could just go into an override of renderFields.

    then: if not layout builder, call parent. Else do logic.

  3. +++ b/modules/product/src/ProductVariationFieldRendererLayoutBuilder.php
    @@ -0,0 +1,106 @@
    +          // TODO: see if there is better way to get field name
    +          $field_name = str_replace('field_block:' . $variation->getEntityTypeId() . ':' . $variation->bundle() . ':', '', $plugin_id);
    

    We could just explode on `:` and the field name is the last entry of the array, isn't it?

tim.plunkett’s picture

#96
1) I believe so

2) That sounds like a plan

3) Yep, this is the code used in LB:
list (, , , $field_name) = explode(static::DERIVATIVE_SEPARATOR, $plugin_id, 4);

mglaman’s picture

StatusFileSize
new3.96 KB
new28.89 KB

So I found an interesting problem for #96.1. The view mode passed is _custom, not the original view mode. So we cannot reliable pass the view mode. Which means layout builder for non-default displays does not work. I think that can be okay, but I'd like to see if we can fix that.


Forgot to refresh before #97 😅. Will update [] = explode based on what LB does.


The original view mode is in $this->thirdPartySettings['layout_builder']['view_mode']

mglaman’s picture

StatusFileSize
new3.01 KB
new29.26 KB

This addresses the view mode support.

mglaman’s picture

StatusFileSize
new29.27 KB

Forgot [] over list() is like 7.1 or whatever.

  • mglaman committed 8a81386 on 8.x-2.x
    Issue #2952529 by mglaman, dravenk, valic, Morbus Iff, ctrlADel, waspper...
mglaman’s picture

Status: Needs review » Fixed

🥳 Boom. This solid enough for now! Anything else can be follow ups. I believe a majority use case is covered.

Thank you everyone for using the patches and providing feedback.

londova’s picture

This update doesn’t work for "Product variation", fields like Price and SKU just disappear.

@mglaman, I agree with your statement #96, but a bit different:
1) I am happy to pay for a ready functional product (not under development);
2) The seller to offer after-sales support for a certain period, like many paid modules and themes.
If you have such options, please let me know and I'll proceed to buy.

londova’s picture

Status: Fixed » Needs work
neograph734’s picture

StatusFileSize
new76.13 KB

Hi Londova, I was just playing around with this, but for me it works (commerce 8.x-2.21).

In layout builder you can choose different fields from both product (body and variations in below screenshot) and also some fields from product variations (price, SKU and images). All fields update accordingly as soon as I change an attribute.

layout builder

If this does not solve your issue, could you at least provide some steps to reproduce your issue?

tim.plunkett’s picture

Status: Needs work » Fixed

Thanks @Neograph734!

@Londova please open a new issue with steps to reproduce.

londova’s picture

StatusFileSize
new539.43 KB

Hi Neograph734,
Please give more info about your test environment.

Here are my TEST details:
Modules: Layout Builder, Layout Discovery
Default Theme: Bartik
Installation method: admin interface

I attached a PDF file with some screenshots.
The first 3 pictues are before using Layout Buider, and all fields are OK.
when the "Layout Builder" was activated from Ptoduct Type Display screen, fields Price and SKU dissapear.
Please advise what is wrong?

neograph734’s picture

There is really no use in enabling layout builder if you are not planning to change the layout of the page. You have to use the Manage Layout button to make changes. Just enabling layout builder indeed seems to remove these fields, but you can add them again.

As explained in my post above, I've managed to add multiple variation fields, including price and SKU, on the Manage Layout page, by choosing them from the Product variation fields section. You can use the 'Show content preview' checkbox at the top to see if they are actually there.

But please, there are 53 people subscribed to this issue, who all get an email if someone posts here. If this still does not solve your problem, create a separate issue for your support request as requested by Tim.

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.

jucedogi’s picture

@Neograph734, thank you. The method you posted at #105 helped me out greatly.

Problem I found here was that I have an image field in the product variation types. What happens here is that unless I specifically add an image, it will not appear. I had added a default image so that it would serve as a generic image to be used until a specific image was added. This default image is treated as non existent.
After adding an actual image to the field it now displays as expected as per the method shown in #105.

I mainly add this here so that if anyone else is having a hard time with this configuration they won't lose as much time as I did trying to figure out what was going on.

FYI using Drupal 8.9.7

lukasss’s picture

I have a product with LB (layout builder) enabled.
I am displaying variation fields in LB.
If the current product has no variations entity, then I get this error:

Drupal\Component\Plugin\Exception\MissingValueContextException: Required contexts without a value: entity in Drupal\Core\Plugin\Context\ContextHandler->applyContextMapping() (line 155 of core/lib/Drupal/Core/Plugin/Context/ContextHandler.php).

Any ideas?

nevergone’s picture

#111 comment is existing error. Is it related to this issue?

lukasss’s picture

@nevergone I create new problem here https://www.drupal.org/project/commerce/issues/3185884

jsidigital’s picture

Does this patch only work if you are running the dev version of commerce?

Also, has anyone tested if it works with Drupal 9 or is it only for Drupal 8.x?

Thank you for your time.

morbus iff’s picture

@jsdigital: this patch is currently in the latest release versions of Commerce.

It does appear to work in Drupal 9.1.

jsidigital’s picture

Thank you for the quick reply @Mobus Iff.

I was able to get layout builder working... somewhat.
I just do not get the "Product Variation Fields" as an option to add them to the layout.

I enabled layout builder on the Product Type.
On LB I click on "Add Block" and I only get "Variations" and "Default Variations" as options, no price, sku, etc.

Is there something I am missing?

jsidigital’s picture

Okay so I found the problem...

My problem was the following (in case it helps anyone else)...

I was adding the layout via the Layout Library:
/admin/structure/types/manage/product/layout-library/mylayout

When I should have been doing it here:
/admin/commerce/config/product-types/default/edit/display/default/layout

So I guess it is worth mentioning that the Commerce + Layout Builder integration is NOT working 100% if you try to have multiple layouts via the layout builder library (Layout Library module). It only works correctly if you use the single default layout of LB.

Thank you.

freelock’s picture

@jsisdigital So it sounds like this issue is fixed -- Commerce is compatible with Layout Builder.

However, it's not currently compatible with Layout Builder Library. Seems like a new issue?

jsidigital’s picture

@freelock That is correct. This issue is fixed and compatible with Layout Builder (I am using Drupal 9.1x) but not yet compatible with Layout Builder Library module.

It would have to be considered a new issue for those wanting to use the Layout Builder library which would apply for anyone that wants to give their editors more than one option to select different layouts per product type. If you have a product like a physical book AND a download version as well but want to display the digital and physical book differently (using the same product type), then Layout Builder Library is a must.

Currently it somewhat works. All product type fields work but none of the variation fields are appearing as options to add in the layout.

For the moment I can live with the default LB integration. That is why I didn't start a new issue.

rossidrup’s picture

i can confirm layout builder is not compatible with commerce....
i tried it and the image is not showing up for product variation...I dont know why
seems the same issue as 4 years ago
https://www.drupal.org/project/commerce/issues/2951841