knockout.js Magento 2产品列表小工具 AJAX 添加到购物车

xxls0lw8  于 2023-04-30  发布在  其他
关注(0)|答案(1)|浏览(86)

我不知道如何绑定产品列表小部件添加到购物车按钮 AJAX 。下面的代码只适用于类别页面和产品详细信息页面。

<script type="text/x-magento-init">
        {
            "[data-role=tocart-form], .form.map.checkout": {
                "catalogAddToCart": {
                    "bindSubmit": true
                }
            }
        }
        </script>

任何想法真的很感激:)

cyvaqqii

cyvaqqii1#

这里是一个自定义解决方案,用于使用自定义路线代码在购物车中添加产品。

注意:无论参数中的数据都必须从列表产品添加到表单中设置。
您的自定义PHTML文件:

<form data-role="tocart-form" action="<?php /* @escapeNotVerified */ echo $postParams['action']; ?>" method="post" id="product_addtocart_form" <?php if ($_item->getOptions()) :?> enctype="multipart/form-data"<?php endif; ?>>

    <input type="hidden" name="product" value="<?php /* @escapeNotVerified */ echo $postParams['data']['product']; ?>">
    <input type="hidden" name="is_cart_page_addcrosssale" value="1" />
    <input type="hidden" name="is_configurable" value="<?php echo $product_type; ?>" />
    <input type="hidden" name="selected_configurable_option" value="" />
    <input type="hidden" name="<?php /* @escapeNotVerified */ echo Action::PARAM_NAME_URL_ENCODED; ?>" value="<?php /* @escapeNotVerified */ echo $postParams['data'][Action::PARAM_NAME_URL_ENCODED]; ?>">
    <?php echo $block->getBlockHtml('formkey')?>
    
    <?php if($block->getChildBlock("configurable_options")){ ?>
        <?= $block->getChildBlock("configurable_options")->setData('product', $_item)->toHtml(); ?> 
    <?php } ?>

    <?php 
    $productTypeInstance = $this->configable; //Magento\ConfigurableProduct\Model\Product\Type\Configurable
    $productAttributeOptions = $productTypeInstance->getConfigurableAttributesAsArray($_item);
    if (!empty($productAttributeOptions)) {
        foreach($productAttributeOptions as $productAttributeOption){
            ?>
                <span><?php // echo $productAttributeOption['label']; ?></span>
                <select name="super_attribute[<?php echo $productAttributeOption['attribute_id'] ?>]" data-selector="super_attribute[151]" data-validate="{required:true}" id="attribute151" class="super-attribute-select" aria-required="true">
                    <?php
                    $opt = 1;
                        foreach($productAttributeOption['values'] as $configure_option)
                        {
                            if ($opt == '1') {
                                $_op_selected = 'selected';
                            }else{
                                $_op_selected = '';
                            }
                            ?>
                            <option selected="<?php echo $_op_selected; ?>" value="<?php echo $configure_option['value_index']; ?>"><?php echo $configure_option['label'] ?></option>
                            <?php
                            $opt++;
                        }
                    ?>
                    
                </select>
            <?php
        }
    }
    ?>
    <button type="submit"
            title="<?php echo $block->escapeHtml(__('Add to Cart')); ?>"
            class="action tocart primary">
        <span><?php /* @escapeNotVerified */ echo __('Add to Cart') ?></span>
    </button>                                               
</form>

控制器文件:

<?php
/* HSCode snippet
* Ajax product add to cart 
* remove item from cart
*/
namespace Vendor\Namespace\Controller\Index;

use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;
use Magento\Catalog\Model\ProductFactory;
use Magento\Checkout\Model\Cart;
use Magento\Catalog\Model\Product;
use Magento\Framework\Controller\ResultFactory;
class AddProducttocart extends Action
{
    /**
     * @var PageFactory
     */
    protected $_resultPageFactory;

    protected $cart;
    
    protected $product;

    
    public function __construct(
        Context $context,
        PageFactory $resultPageFactory,
        \Magento\Framework\Data\Form\FormKey $formKey,
        Cart $cart,
        Product $product,
        \Magento\Catalog\Api\ProductRepositoryInterface $productRepository
    ) {
        $this->_resultPageFactory = $resultPageFactory;
        $this->formKey = $formKey;
        $this->cart = $cart;
        $this->product = $product;
        $this->productRepository = $productRepository;
        parent::__construct($context);
    }

   
    public function execute()
    {

        $content = '';

        try {
            // Ajax add to cart 
            if($this->getRequest()->getParam('is_configurable') == 'simple'){
               $content = $this->addProductToCartSimple();
            }

            if($this->getRequest()->getParam('is_configurable') == 'configurable'){
               $content = $this->addProductToCartConfig();
            }

            // remove item from cart by id 
            if($this->getRequest()->getParam('accessory_remove_id') != '' ){
                $content = $this->removeItemFromCart($this->getRequest()->getParam('accessory_remove_id'));
            }             
           

            
        }catch (LocalizedException $e) {
            
            return $content="false";

        }

        $resultPage = $this->_resultPageFactory->create();
        // return $resultPage;

        $response = $this->resultFactory->create(ResultFactory::TYPE_RAW);
        $response->setContents($content);
        return $response;
    }

    public function addProductToCartSimple(){
        
        $productid = $this->getRequest()->getParam('product', false);

        $productprice = $this->getRequest()->getParam('price', false);

        $form_key = $this->getRequest()->getParam('form_key', false);

        $params = array(
            'form_key' => $form_key,
            'product' =>$productid,
            'qty'   =>1,
            'price' =>$productprice
        );

        $product = $this->product->load($productid);

        $this->cart->addProduct($product, $params);

        $this->cart->save();
        
        $content=$productid;

        return $content;
    }

    public function addProductToCartConfig(){

        $productid = $this->getRequest()->getParam('product', false);

        $productprice = $this->getRequest()->getParam('price', false);

        $form_key = $this->getRequest()->getParam('form_key', false);
        
        $options = $this->getRequest()->getParam('super_attribute', false);

        $params = array(
            'product' => $productid,
            'super_attribute' => $options,
            'qty' => '1'
        );
        
        $product = $this->product->load($productid);

        $this->cart->addProduct($product, $params);

        $this->cart->save();

        $content = $productid;

        return $content;
    }

    public function removeItemFromCart($productId){

       $productInfo = $this->cart->getQuote()->getItemsCollection();

       foreach ($productInfo as $item){

            if($productId == $item['product_id']){

                $item_id = $item['item_id'];

                $quote_id = $item['quote_id'];

                $this->cart->removeItem($item_id)->save();

            }
       }

       $content = $productId;

       return $content;
    }
}

相关问题