Skip to content

[POC] Refresh product miniature dynamically #927

Description

@Hlavtox

Problem

We added an option to add products to cart from the listing, however, this brings some incosistencies.

  • If OOSP is disabled and only one piece is in stock, and you add it to cart, the button is still enabled. Also, it doesn't change with quantity.
  • The same with availability, if you have it displayed. It displays In stock, until you refresh the page. Also, it doesn't change with quantity.
  • Price doesn't change with quantity.

Solution

I am thinking of a following endpoint in ProductController. Very simmilar to how quickview works.

public function displayAjaxRefreshMiniature(): void
    {
        // Prepare product assembler and presenter
        $assembler = new ProductAssembler($this->context);
        $presenter = new ProductListingPresenter(
            new ImageRetriever(
                $this->context->link
            ),
            $this->context->link,
            new PriceFormatter(),
            new ProductColorsRetriever(),
            $this->getTranslator()
        );
        $presentationSettings = $this->getProductPresentationSettings();

        // Presenting the miniature
        $presentedProduct = $presenter->present(
            $presentationSettings,
            $assembler->assembleProduct(['id_product' => (int) Tools::getValue('id_product'), 'id_product_attribute' => (int) Tools::getValue('id_product_attribute')]),
            $this->context->language
        );

        // And render it
        ob_end_clean();
        header('Content-Type: application/json');

        $this->ajaxRender(json_encode([
            'product' => $this->render('catalog/_partials/miniatures/product',
                [
                    'product' => $presentedProduct,
                ]
            ),
        ]));
    }

Then, in the theme, you can do something like this and swap it, after cart update. Very simmilar to quickview.js.

fetch(prestashop.urls.pages.product, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
    'X-Requested-With': 'XMLHttpRequest',
    'Accept': 'application/json',
  },
  body: 'action=refreshminiature&id_product=7&id_product_attribute=0',
  credentials: 'same-origin'
})
.then(r => r.text())
.then(console.log);

No other core modification would be needed. No TPL change needed. Just JS logic.

cc @tblivet @kpodemski @ga-devfront

Points to think about

  • What about packs that depend on quantity of other products?
  • Themes could be using different TPLs for different sections (I do, for accessories, related products, other variants etc.)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No fields configured for Bug.

    Projects

    Status
    Waiting for QA

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions