I created a page of my products. When I change the variation of the first product, it works. But when I modify the variatons of the following products, the price does not change and the double arrow (ajax) disappears.

And a screenshot (left it works and right it does not work).

Can you help me?

Support from Acquia helps fund testing for Drupal Acquia logo

Comments

zenimagine created an issue. See original summary.

zenimagine’s picture

I put a "commerce-product.html.twig" file in the "templates" folder of my theme. Here are contents :

{#
/**
 * @file
 *
 * Default product template.
 *
 * Available variables:
 * - attributes: HTML attributes for the wrapper.
 * - product: The rendered product fields.
 *   Use 'product' to print them all, or print a subset such as
 *   'product.title'. Use the following code to exclude the
 *   printing of a given field:
 *   @code
 *   {{ product|without('title') }}
 *   @endcode
 * - product_entity: The product entity.
 * - product_url: The product URL.
 *
 * @ingroup themeable
 */
#}
<article{{ attributes }}>
  {{ product.variation_sku}}
  {{ product.variation_price}}
  {{ product.variations}}
</article>

The objective is to apply the same display for all my products, but only the first product of my view allows to change the variation. The others do not work.

zenimagine’s picture

bojanz’s picture

Category: Support request » Bug report

Are both of these products rendered by a view? Are they products of the same type?

We've had a very hard time reproducing these failures previously.

zenimagine’s picture

Yes the products are of the same type and are rendered by a view.

Here is the export of my view :

uuid: cb81dfeb-f93f-4dab-8f8d-9704171b3bc1
langcode: fr
status: true
dependencies:
  module:
    - commerce_product
id: my_product
label: 'My product'
module: views
description: ''
tag: ''
base_table: commerce_product_field_data
base_field: product_id
core: 8.x
display:
  default:
    display_plugin: default
    id: default
    display_title: Master
    position: 0
    display_options:
      access:
        type: none
        options: {  }
      cache:
        type: tag
        options: {  }
      query:
        type: views_query
        options:
          disable_sql_rewrite: false
          distinct: false
          replica: false
          query_comment: ''
          query_tags: {  }
      exposed_form:
        type: basic
        options:
          submit_button: Apply
          reset_button: false
          reset_button_label: Reset
          exposed_sorts_label: 'Sort by'
          expose_sort_order: true
          sort_asc_label: Asc
          sort_desc_label: Desc
      pager:
        type: none
        options:
          items_per_page: null
          offset: 0
      style:
        type: grid
      row:
        type: 'entity:commerce_product'
        options:
          relationship: none
          view_mode: default
      fields:
        title:
          table: commerce_product_field_data
          field: title
          id: title
          entity_type: null
          entity_field: title
          plugin_id: field
          relationship: none
          group_type: group
          admin_label: ''
          label: ''
          exclude: false
          alter:
            alter_text: false
            text: ''
            make_link: false
            path: ''
            absolute: false
            external: false
            replace_spaces: false
            path_case: none
            trim_whitespace: false
            alt: ''
            rel: ''
            link_class: ''
            prefix: ''
            suffix: ''
            target: ''
            nl2br: false
            max_length: 0
            word_boundary: true
            ellipsis: true
            more_link: false
            more_link_text: ''
            more_link_path: ''
            strip_tags: false
            trim: false
            preserve_tags: ''
            html: false
          element_type: ''
          element_class: ''
          element_label_type: ''
          element_label_class: ''
          element_label_colon: true
          element_wrapper_type: ''
          element_wrapper_class: ''
          element_default_classes: true
          empty: ''
          hide_empty: false
          empty_zero: false
          hide_alter_empty: true
          click_sort_column: value
          type: string
          settings: {  }
          group_column: value
          group_columns: {  }
          group_rows: true
          delta_limit: 0
          delta_offset: 0
          delta_reversed: false
          delta_first_last: false
          multi_type: separator
          separator: ', '
          field_api_classes: false
        rendered_entity:
          id: rendered_entity
          table: commerce_product
          field: rendered_entity
          relationship: none
          group_type: group
          admin_label: ''
          label: ''
          exclude: false
          alter:
            alter_text: false
            text: ''
            make_link: false
            path: ''
            absolute: false
            external: false
            replace_spaces: false
            path_case: none
            trim_whitespace: false
            alt: ''
            rel: ''
            link_class: ''
            prefix: ''
            suffix: ''
            target: ''
            nl2br: false
            max_length: 0
            word_boundary: true
            ellipsis: true
            more_link: false
            more_link_text: ''
            more_link_path: ''
            strip_tags: false
            trim: false
            preserve_tags: ''
            html: false
          element_type: ''
          element_class: ''
          element_label_type: ''
          element_label_class: ''
          element_label_colon: false
          element_wrapper_type: ''
          element_wrapper_class: ''
          element_default_classes: true
          empty: ''
          hide_empty: false
          empty_zero: false
          hide_alter_empty: true
          view_mode: default
          entity_type: commerce_product
          plugin_id: rendered_entity
      filters: {  }
      sorts: {  }
      title: 'My product'
      header: {  }
      footer: {  }
      empty: {  }
      relationships: {  }
      arguments: {  }
      display_extenders: {  }
    cache_metadata:
      max-age: -1
      contexts:
        - 'languages:language_content'
        - 'languages:language_interface'
      tags:
        - 'config:core.entity_view_display.commerce_product.default.default'
  page_1:
    display_plugin: page
    id: page_1
    display_title: Page
    position: 1
    display_options:
      display_extenders: {  }
      path: my-product
    cache_metadata:
      max-age: -1
      contexts:
        - 'languages:language_content'
        - 'languages:language_interface'
      tags:
        - 'config:core.entity_view_display.commerce_product.default.default'
bojanz’s picture

And just to confirm, you are running RC1 or newer, right?

I see that you also have Flag installed, which version?

zenimagine’s picture

I use :

"drupal/flag": "4.x-dev"
"drupal/commerce": "2.x-dev"

zenimagine’s picture

To test I created a product catalog without flag, but the bug is still present.

zenimagine’s picture

Priority: Normal » Major

I created a simple shop on simplytest.me
Without adding any additional modules. And I have the same problem, so it does not come from my installation or contributed modules.

zenimagine’s picture

Title: Only the first product variation works » With a view catalog, only the first product variations works
zenimagine’s picture

@bojanz
I have tested on simplytest.me and the problem is on dev and rc1.
Can you reproduce it ?

zenimagine’s picture

Status: Active » Needs work
0Sarah0Al’s picture

I am having the same problem.

zenimagine’s picture

@Sarahphp1 Thank you, I thought I was the only one with problems.

0Sarah0Al’s picture

It's an ajax error .. Uncaught Drupal.AjaxError

The error I see in the console based on the server response is:

Error: Call to a member function id() on null in /media/sf_sandbox/drupal/modules/contrib/commerce/modules/product/src/Plugin/Field/FieldWidget/ProductVariationTitleWidget.php on line 116

mglaman’s picture

We do have tests for this in

views.view.test_multiple_cart_forms_fields.yml
views.view.test_multiple_cart_forms.yml

The tests run with BigPipe enabled multiple variation types, and all of that. I ran a diff of views.view.test_multiple_cart_forms.yml against the view provided in #5 and cannot see anything noticeable. A copy can be found: https://www.diffchecker.com/bTy4dNE4

The only difference is the rendered_entity field which exists in the original view. In views.view.test_multiple_cart_forms_fields.yml we test the variations field rendered, but not the rendered product.

I guess we need to start by replicating the failure. Can we pinpoint the issue to using Views with Fields and rendering the product as a field entry?

        rendered_entity:
          id: rendered_entity
          table: commerce_product
          field: rendered_entity 

Feedback will help track this down.

EDIT

I also noticed a 404 being thrown by /views/ajax. I believe agoradesign had some bugs with Views which had AJAX enabled. I'll reach out.

agoradesign’s picture

@mglaman: I had different problems with Views and/or Ajax in the past that seem to not being related to this one. The first one was on the detail page in combination with BigPipe and a Views exposed form being present. The problem was fixed in core then: see #2710939: AddToCartFormatter lazy builder causes erroneous Ajax submits, when a second form is present

Another problem was the handling of the add to cart form ID, where we first had the static counter implementation. On adding a product to the cart, the wrong product was added because the order of the form handling was reversed on submit. So adding the last item in a view resulted in having the first one added, vice versa. #2796669: Price not updated for variations when products shown in list views

Fortunately, I didn't need variation selection in a view until now. One store doesn't have variations, the other no product views.

zenimagine’s picture

Status: Needs work » Active
0Sarah0Al’s picture

**Update**

I think the problem I am having is related to the Entity reference field available inside "product variation types" which references product attribute values.

First, it does not pick up the attribute title. The title just says: "Please select" and most likely does not pick up the values of the selected attributes even though the values' names are showing in the drop down select field.

The first attached image shows the correct behavior of a commerce product in a view. (Bartik theme is used in that test website).
1- The title of the field 'Size' in this image shows as 'Please select' in my other website (second image).
2- when you select another value (say size small), price and variation is correctly updated and no errors in the test website except the javascript error related to "quickedit" core module.
In my other website, I get errors similar to the errors zenimagine showed in his previous post. That is "Error: Call to a member function id() on null in commerce/modules/product/src/Plugin/Field/FieldWidget/ProductVariationTitleWidget.php on line 116. And "Undefined offset ... "
Line 116 is expecting a selected variation id from user input, but it is not passed.
I tested commerce with display suite in the 'test website' and everything works fine. I even tested bootstrap theme in simplytest.me and it's still working fine.
I am stumped at this point.. :(

@zenimage if you would like to contact me to discuss this issue we're both having, I would be happy to. I have a channel at Slack.

Thanks everyone.

0Sarah0Al’s picture

Ok, there is a solution! I consider it a temporary solution until you guys figure out a better code and/or do the necessary tests.

Thanks to @steveoliver at #commerce channel in Stack.
This solution is fully creditd to him.

First:
In modules/contrib/commerce/modules/product/src/Plugin/Field/FieldWidget/ProductVariationTitleWidget.php
Line 116, should be changed to:

    If ($selected_variation) {
    $form_state->set('selected_variation', $selected_variation->id());
    }

Second;
Line 128, should be changed to:

'#default_value' => $selected_variation ? $selected_variation->id() : NULL,

After I added the codes above, the rest of the varaition select input worked. However, I got a notice: "Undefined offset: in ProductVariationTitleWidget in line 158"
This can be fixed with this code. In selectVariationFromUserInput function code block and Before this:

    if (!empty($user_input['variation']) && $variations[$user_input['variation']]) {
      $current_variation = $variations[$user_input['variation']];
    }

add this line:

    if ( !isset($variations[$user_input['variation']]) ) {
      $variations[$user_input['variation']] = [];
    }

And that's it. Hope somebody improves this code and fix it.
Thanks again to @steveoliver

@zenimage could you please verify if this code works in your situation ?

p4trizio’s picture

FileSize
1.75 KB

@Sarahphp1 I created a patch based on your comments so that others can see the actual changes and review

0Sarah0Al’s picture

Thank you so much p4trizio. I appreciate it.

0Sarah0Al’s picture

The code above introduced another issue.
That is, when you choose one of the options in the second, or third ,,,etc, select input, the focus jumps to the first select input.

I think this has to do with the AJAX triggering action.

So, after:
'#default_value' => $selected_variation ? $selected_variation->id() : NULL,

add:
'#attributes' => ['data-disable-refocus' => 'true'],

p4trizio, sorry that I am adding extra work on you, could you please add the line above to the patch! :)

I think problem solved YAY..
We just need testing.. :)

p4trizio’s picture

FileSize
1.81 KB
801 bytes

Hi Sarahphp1, no worries.
Patch and diff attached.
I would ask others to review the code and also to approve this is the best way to solve the issue.

chrisrockwell’s picture

Wow - I have been chasing this bug off-and-on for days and have been keeping up with a lengthy Drupal Answers post today.

This patch resolves my issues with having multiple add-to-cart forms on the same page, whether they are included via entity reference and view mode or through custom paragraph blocks.

Most.Relieving.Patch.Ever.

0Sarah0Al’s picture

Niccceeeeee :)

I am glad I brought joy to the world ,, LOL

Thanks Patrizio for the patch.

drugan’s picture

Status: Active » Reviewed & tested by the community

I've tested the #24 patch and it works great.

I think that this patch should be commited as soon as possible because views catalog is the pretty often used method to present products for a customer.

p4trizio’s picture

Just made a PR: https://github.com/drupalcommerce/commerce/pull/810
Hope it is going to be accepted thank you all.
@Sarahphp1 just in case the code will be merged you should take the credit for it, we are good team ;-)

mglaman’s picture

Status: Reviewed & tested by the community » Needs work

I've updated the PR with comments. Will mirror here.

  1. +++ b/modules/product/src/Plugin/Field/FieldWidget/ProductVariationTitleWidget.php
    @@ -113,7 +113,9 @@ class ProductVariationTitleWidget extends ProductVariationWidgetBase implements
    +    if($selected_variation) {
    

    phpcs

  2. +++ b/modules/product/src/Plugin/Field/FieldWidget/ProductVariationTitleWidget.php
    @@ -124,7 +126,8 @@ class ProductVariationTitleWidget extends ProductVariationWidgetBase implements
    +      '#attributes' => ['data-disable-refocus' => 'true'],
    

    This is only on the title widget and not attribute selection widget. I don't see how this addresses #23, which seems to be for attributes.

    Unless the issue is that it refocuses a random form.. which is a whole new bug.

    The fact we have to do this makes me feel there is a deeper bug.

  3. +++ b/modules/product/src/Plugin/Field/FieldWidget/ProductVariationTitleWidget.php
    @@ -153,6 +156,9 @@ class ProductVariationTitleWidget extends ProductVariationWidgetBase implements
    +    if (!isset($variations[$user_input['variation']])) {
    +      $variations[$user_input['variation']] = [];
    +    }
    

    The empty checkout below is sufficient.

We also need to update our tests. We have a views based test, I'm not sure our coverage gap. I don't use views often, so I cannot really grep the configuration issue. But we definitely need a failing test and then the fix.

zenimagine’s picture

Thank you. Patch #21 works for me.

0Sarah0Al’s picture

Thanks p4trizio. So nice of you. :)

______________________

Regarding #23,
I noticed that it happens in the product catalog view in my test website which does NOT have the variation problem described here in this issue thread. So, it could be a totally different bug.
Matt is right.

For my case, the code:
'#attributes' => ['data-disable-refocus' => 'true'],
alleviated the refocusing. So, I guess I will have to keep using it until I find a fix ... :(

Wish me luck ,,

By the way, was anybody here able to reproduce the variation issue of this thread?
I tried many times, but with no luck !! Which is weird!
I am suspecting that the only way to reproduce it is by adding and removing product variation fields, and adding and removing ...... and keep doing it till the bug pops up ,, LOL
I guess that's what I did during my time going through the painful steep-learning curve of drupal (without realizing it).
:'))))

Thanks everyone

drugan’s picture

@Sarahphp1

To reproduce:

Create a bunch of products with different variation types having different attributes (I suppose you use Default order item type for all the variation types involved).

Go to /admin/commerce/config/order-item-types/default/edit/form-display/add_to_cart and choose Product variation title widget for the Add to Cart form.

Install the #5 view (remove the uuid line from the view)

Go to /my-product page.

Try to change variation on any product except the very first. Nothing happens.

Try to add this product to cart and observe the fatal error:

Fatal error: Call to a member function id() on a non-object in /home/user/*/web/modules/contrib/commerce/modules/product/src/Plugin/Field/FieldWidget/ProductVariationTitleWidget.php on line 116

Again, it's a critical issue for a common drupalcommerce site.

By the way, the issue of "jumping" after changing an attribute also persists on the Product variation attributes widget.

0Sarah0Al’s picture

"Create a bunch of products with different variation types having different attributes."

This I did!

"Go to /admin/commerce/config/order-item-types/default/edit/form-display/add_to_cart and choose Product variation title widget for the Add to Cart form."

And this I did not do! And it's indeed what caused the problem..
I totally forgot about that widget .. my bad!

Thank you so much drugan !

Now, I can rest ,, :)))

websiteworkspace’s picture

It is possible to replicate what seems like the symptoms described in this thread with a very simple view.
Create one or more products with some variations.
Create a simple view the just lists the products with their default view mode.
( optionally to keep things simple, use filter criteria to display just one product)
Add a relationship to the product variations
--
The expected results would be to see a list containing each of the variations for each of the product(s).
--
Problem:
If there is one product with five variations, what gets displayed is a list that outputs the one product five times showing only its 1st variation, when the expected result would be to see each of the five variations.

[ example (actual) view code ]


uuid: c7dc7f29-ff04-432b-9fcd-06577d62e36b
langcode: en
status: true
dependencies:
  module:
    - commerce_product
id: view_products_list
label: 'Products List'
module: views
description: 'products list'
tag: 
base_table: commerce_product_field_data
base_field: product_id
core: 8.x
display:
  default:
    display_plugin: default
    id: default
    display_title: Master
    position: 0
    display_options:
      access: { type: none, options: {  } }
      cache: { type: tag, options: {  } }
      query: { type: views_query, options: { disable_sql_rewrite: false, distinct: false, replica: false, query_comment: , query_tags: {  } } }
      exposed_form: { type: basic, options: { submit_button: Apply, reset_button: false, reset_button_label: Reset, exposed_sorts_label: 'Sort by', expose_sort_order: true, sort_asc_label: Asc, sort_desc_label: Desc } }
      pager: { type: mini, options: { items_per_page: 10, offset: 0, id: 0, total_pages: null, expose: { items_per_page: false, items_per_page_label: 'Items per page', items_per_page_options: '5, 10, 25, 50', items_per_page_options_all: false, items_per_page_options_all_label: '- All -', offset: false, offset_label: Offset }, tags: { previous: ‹‹, next: ›› } } }
      style: { type: default }
      row: { type: 'entity:commerce_product' }
      fields: { title: { table: commerce_product_field_data, field: title, id: title, entity_type: null, entity_field: title, plugin_id: field, relationship: none, group_type: group, admin_label: , label: , exclude: false, alter: { alter_text: false, text: , make_link: false, path: , absolute: false, external: false, replace_spaces: false, path_case: none, trim_whitespace: false, alt: , rel: , link_class: , prefix: , suffix: , target: , nl2br: false, max_length: 0, word_boundary: true, ellipsis: true, more_link: false, more_link_text: , more_link_path: , strip_tags: false, trim: false, preserve_tags: , html: false }, element_type: , element_class: , element_label_type: , element_label_class: , element_label_colon: true, element_wrapper_type: , element_wrapper_class: , element_default_classes: true, empty: , hide_empty: false, empty_zero: false, hide_alter_empty: true, click_sort_column: value, type: string, settings: {  }, group_column: value, group_columns: {  }, group_rows: true, delta_limit: 0, delta_offset: 0, delta_reversed: false, delta_first_last: false, multi_type: separator, separator: ', ', field_api_classes: false } }
      filters: {  }
      sorts: {  }
      title: 'Products List'
      header: {  }
      footer: {  }
      empty: {  }
      relationships: { variations: { id: variations, table: commerce_product__variations, field: variations, relationship: none, group_type: group, admin_label: 'variations: Product variation', required: false, plugin_id: standard } }
      arguments: {  }
      display_extenders: {  }
    cache_metadata:
      max-age: -1
      contexts: ['languages:language_content', 'languages:language_interface', url.query_args]
      tags: {  }
  page_1:
    display_plugin: page
    id: page_1
    display_title: Page
    position: 1
    display_options:
      display_extenders: {  }
      path: productslist
    cache_metadata:
      max-age: -1
      contexts: ['languages:language_content', 'languages:language_interface', url.query_args]
      tags: {  }


websiteworkspace’s picture

The following bug report illustrates a different problem, but a potentially related problem.

The fields based view at the following link correctly displays all the product's variations, but the attribute value(s) in the product.variations "add to cart form" do not set the attribute value (radio button set value) based on the variation being displayed. That variations are XS S M L XL, but the radio button set always shows XS no matter which variation is output by the view. However the actual individual field value is correctly shown separately by the view as an individual field.

https://www.drupal.org/node/2915356

(might the bug at the link just above be the same underlying problem?)

drugan’s picture

@DrupalSiteBuilder

It is always better to upload my-view-or-my-error-dump.txt file than copy-pasting a ton of lines directly in a comment.

websiteworkspace’s picture

@drugan

I'll add the view export .yml as a file to the other bug report.

websiteworkspace’s picture

@drugan

Can you see in the other example that the radio button set inside the variations "add to cart form" does not get set to the attribute value associated with the variation being displayed?

The just described problem seems like a bug for a variety of usage contexts. There doesn't seem to be a way to pre-set the desired variation associated attribute in the general circumstance either, i.e. pre-populate the product (full view mode) set to a specific variation.

thechanceg’s picture

I'm pretty sure @mglaman is on to something with the 404 from /views/ajax. I'm seeing that as well when products are loaded an ajax view. Loading the product works fine, but changing its variation creates the 404. I'm using the attribute widget, but everything else sounds the same (and it looks like both widgets are very similar).

I think that it is related to Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->wrapControllerExecutionInRenderContext. It looks like it calls the ViewAjaxController, and that controller is expecting a view_name and view_display_id to be present in the request. When it can't find it, it throws a NotFoundHttpException, which ends the request.

I don't know enough about the new views or EarlyRendering event subscriber to know why it is trying to do this though. I'd be happy to add some breakpoints and check it out in xDebug if anyone has any ideas though.

drugan’s picture

Before something will be found here this issue is now fixed on the Commerce Multistore module. See how:

https://github.com/drugan/commerce_multistore/blob/master/src/Plugin/Fie...

To see the effect enable the module, go to admin/commerce/config/order-item-types/YOUR-TYPE/edit/form-display/add_to_cart and change the widget for Multistore product variation title.

zenimagine’s picture

@drugan Thank you for your work, I look forward to testing your module and that it is published on drupal.org

zenimagine’s picture

Will this problem be fixed on the Commerce 2 module or is it specific to the marketplace ?

drugan’s picture

This issue is now fixed on the Commerce Correct Attributes submodule of the Commerce Extended Attributes.

zenimagine’s picture

Thank you for the module. This means that the bug will never be fixed with the base module "Commerce 2" ?

kaido.toomingas’s picture

Will add patch for core based on @drugan work.

zenimagine’s picture

Patch #45 does not work with Commerce 2.5.0

Patch #24 work with Commerce 2.5.0

zenimagine’s picture

Patch #45 does not work with Commerce 2.7.0

Could not apply patch! Skipping. The error was: Cannot apply patch https://www.drupal.org/files/issues/fix_jumping.patch

Patch #24 work

davps’s picture

Just updated patch #45 according to last 2.x branch.

zenimagine’s picture

Issue summary: View changes
andyg5000’s picture

The fix in #2897698-48: With a view catalog, only the first product variations works doesn't appear to work for me and doesn't include the equivalent fix for the ProductVariationTitleWidget in 2.x core.

The fix in #2897698-24: With a view catalog, only the first product variations works does "work", but that's because it's forcing it by using the form's user input for the element. This will likely break when you have multiple add to cart forms with different order item types or other variations that could affect the add to cart form.

Will report back when I get my issue resolved or figure out how to reproduce!

andyg5000’s picture

Ok, whenever a form is submitted, including via ajax (variation/attribute change), the view is re-invoked and all of the product forms are rebuilt. The fatal error happens during rebuild causing the form submission to die. This rebuild proves how expensive it is to use views to render all these forms!

When this happens, the user input from the triggering form is passed to ProductVariationTitleWidget::formElement, for every product form on the view. I'm not sure why this happens, but maybe @drugans link related to if ($form_state->isRebuilding()) in #40 explains this.

Depending on $selected_variation to be loaded from the user input each time is not reliable. Because of this, we should always fallback on the default variation. Otherwise, further calls with cause fatal errors as we've all seen.

I'm including a simple patch that's similar to #2897698-24: With a view catalog, only the first product variations works, but doesn't force the selected variation to a value that doesn't match the form being rebuilt.

It also includes the jumping fix from [ #2897698-48], which i didn't realize was a different issue/fix. Patches shouldn't be split like that.

This patch is only for ProductVariationTitleWidget. Once I have feedback, we can make sure ProductVaritiaonAttributesWidget follows suit

andyg5000’s picture

I've found another issue. While the patch above prevents the fatal error, it does not fix the core problem with views and add to cart forms.

If you create a view with 1 random product form, ajax requests and form submissions fail because the view is rebuilt with each request causing the product form to be different.

If you're 100% sure that he view will load the same product in its results, then this patch fixes the issue. This needs more work and someone with knowledge of the views/form render pipeline to chime in.

A "hack" that could fix this would be to query alter the view when there's a form request and make it load the correct product. Not suggesting we do that, but maybe it will give others ideas how to solve the problem.

mglaman’s picture

andyg5000 we should have a test which has VIews and add to cart forms. So if we randomized the View this should break it, right? So we can have a failing test out of the box

andyg5000’s picture

Hey @mglaman,

I think the best way to test this would be to sort the view by product id and create a new product after the form is built. This way when the form is submitted, a new product will take position 1 in the view and will break.

I've confirmed the issue on multiple sites by creating a view with 1 random product. Change the attribute/variation and see the error in browser console.

andyg5000’s picture

Status: Needs work » Needs review
FileSize
8.96 KB

@mglaman,

Here's a successful and failing test case based on #54.

Status: Needs review » Needs work
drugan’s picture

@andyg5000

For me the fail test seems too simple. We should have in the view products with default (just one) variation type, a type which has at least two required attributes, a type which has at least one optional attribute. The best way is to mock the Londova-test (origin) and wqmeng-test. Better if the whole amount of products in the view would be at least 10 products. Also, for a bullet proof test we need a block view with the same products in order to test product variation duplications on a page. Then the following test methods should be created:

  • Click on any default variation type (without attributes).
  • Choose non-default option of the very first product variation and then add to cart.
  • Choose any non-default option of any product then choose non-default option somewhere in the middle and then add to cart.
  • Repeat the same choosing / clicking in the very last product variation.
  • Try choose some product variation on the page view then choose the same non-default duplication in a block view and add to cart.
andyg5000’s picture

My thought is, let's just try to fix the views issue which would be required for any complex form to pass, since a simple form (no variations) won't even pass. Once that's discovered and resolved, we can get into testing advanced use cases.

pankaj2k12’s picture

I am still facing this issue. Can anybody confirm if it is fixed in latest version or drupal commerce?

NickDickinsonWilde’s picture

#51 does fix the problem - so even if there is more depth to the problem, would be pretty nice to get this in with a followup.

c_archer’s picture

#51 does get the price working correctly for me, however, I still get this error when a user clicks add to cart.

Notice: Undefined offset: 25 in Drupal\commerce_product\Plugin\Field\FieldWidget\ProductVariationTitleWidget->selectVariationFromUserInput() (line 162 of modules/contrib/commerce/modules/product/src/Plugin/Field/FieldWidget/ProductVariationTitleWidget.php).

It does however still add the product to the cart.

Worth noting that the error only appears when the variations have different prices.

martinhansen’s picture

My line numbers are different so I might be on a different version of commerce (8.x-2.21) than previous comments, but I made the changes in #51 and it worked for me, and then also resulted in the other error from #61.

To fix this I changed line 167 from:
if (!empty($user_input['variation']) && $variations[$user_input['variation']]) {
to:
if (!empty($user_input['variation']) && !empty($variations[$user_input['variation']])) {

orodicio’s picture

I have rerroled #51 patch and applied the #62 changes and it works perfectly fine for me in 8.x.2.24.

tunic’s picture

Status: Needs work » Needs review

The last submitted patch, 48: fix_jumping-2897698-48.patch, failed testing. View results

jsacksick’s picture

Ok, I've been debugging this today and it looks like fixes that were made to ProductVariationAttributesWidget were never actually ported to ProductVariationTitleWidget.

So it appears the problem (as explained in comment #51) is that the code is trying to select a variation from the user input for another add to cart form.

See the fixes from #2956043: ProductVariationAttributeMapper::selectVariation() returns the first variation, not the default one and #2893182: Multiple add to cart forms with different variation types throws exception.
I worked on a similar fix and it immediately started to work.

It'd be great to write a failing test though I think this was done in #55, so perhaps we could reuse the test from there... Attaching the fix for now.

I'm thinking we should expand MultipleCartFormsTest to test the "commerce_product_variation_title" widget as well (it's currently testing the attributes widget only for now).

Status: Needs review » Needs work

The last submitted patch, 67: 2897698-67.patch, failed testing. View results

jsacksick’s picture

Not sure why we had code changing the sort handler instead of setting it from the view directly :p.

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

  • jsacksick committed c8809a8 on 8.x-2.x
    Issue #2897698 by jsacksick, p4trizio, andyg5000, orodicio, kaido....
jsacksick’s picture

Status: Needs review » Fixed

Committed! Thanks everyone!

Status: Fixed » Closed (fixed)

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