I'm currently working on a module that adds specific products to the cart when the customer adds a normal product. I created an observer for the checkout_cart_product_add_after. The user will select a few options which will be posted and this observer will form a sku with that, get the specific product and add it to the cart.
The problem is that sometimes a product with the formed sku might not exist, so I want to create and then add it to the cart. I've tried a few things, but it doesn't seem to work.
Here is the code I currently have, which adds the specific products to the cart.
Thanks for the help.
// Get the custom variations values added through the VariationsInput block. $post = $this->_request->getParam('variations'); // Create the custom sku. $customSku = 'SV'; foreach ($post as $key => $value) { if ($key == '' || $value == '') { continue; } $customSku .= $value; } // Get the current product the user is trying to add to cart. $currentProduct = $observer->getEvent()->getData('product'); // Get the additional product that needs to be added to cart. $productToAdd = $this->_productRepository->get($customSku); // Here is the part where I need to check if the product doesn't exist and then create it. if (empty($productToAdd)) { //Code to create the product and assign it to the $productToAdd variable. } // Enter the id of the prouduct which are required to be added to avoid recurrssion if ($currentProduct->getId() != $productToAdd->getId()) { $params = array( 'product' => $productToAdd->getId(), 'qty' => $currentProduct->getQty() ); $this->_cart->addProduct($productToAdd, $params); $this->_cart->save(); }