duncanmcclean / simple-commerce

A simple, yet powerful e-commerce addon for Statamic.
https://statamic.com/addons/duncanmcclean/simple-commerce
Other
145 stars 38 forks source link

Adding a variant to the cart without selecting it gives an error #867

Closed KingPatje closed 1 year ago

KingPatje commented 1 year ago

Description

When you press add to cart without selecting a Variant, you will get the following error:

DoubleThreeDigital\SimpleCommerce\Products\Product::variant(): Argument #1 ($optionKey) must be of type string, null given, called in D:\webdev\scommerce\vendor\doublethreedigital\simple-commerce\src\Http\Controllers\CartItemController.php on line 115

This is because in DoubleThreeDigital\SimpleCommerce\Http\Requests\CartItem\StoreRequest.php the validation rule says the variant may be nullable and if its not null it must be a string.

The Product::variant expects a string, so a null value isn't working. I tried making the variant required in the validation rules like this:

        $rules = [
            'product' => ['required', 'string'],
            'variant' => ['nullable', 'string'],
            'quantity' => ['required', 'numeric', 'gt:0'],

            'email' => ['nullable', 'email', function ($attribute, $value, $fail) {
                if (preg_match('/^\S*$/u', $value) === 0) {
                    return $fail(__('Your email may not contain any spaces.'));
                }
            }],
            'customer.email' => ['nullable', 'email', function ($attribute, $value, $fail) {
                if (preg_match('/^\S*$/u', $value) === 0) {
                    return $fail(__('Your email may not contain any spaces.'));
                }
            }],
        ];

        if(Product::find($this->get('product'))->purchasableType() == ProductType::Variant){
            $rules['variant'][0] = 'required';
        }

However, this gives a new error, where i lose track.


D:\webdev\scommerce\vendor\statamic\cms\src\View\Antlers\Language\Runtime\NodeProcessor
.php: 1799```

### Steps to reproduce

1. Install the starter kit from the documentation
2. Log in and create a Variant product
3. View the variant product and press Add to cart without selecting it

### Environment

this command does not work for me
duncanmcclean commented 1 year ago

If the product has variants, you need to supply a variant before you can add the product to the cart.

KingPatje commented 1 year ago

correct, but a customer should never see an exception, validation rules should handle this.

duncanmcclean commented 1 year ago

True, I'll re-open to fix that.

github-actions[bot] commented 1 year ago

Released as part of v5.0.2.