Jump to content

Add to cart from the product list in PrestaShop 1.7


Recommended Posts

Hi Fabio,

i tried to modify the file: themes/classic/templates/catalog/_partials/miniatures/product.tpl

adding this code as you described:

<form action="{$urls.pages.cart}" method="post">
          	<input type="hidden" value="{$product.id_product}" name="id_product">
          	<input type="number" style="padding: 9px 10px; float:left;width: 30%; margin-left: 10px;" class="input-group form-control" name="qty" min="1" value="1">
          	<button style="float:left;margin-left: 13px" data-button-action="add-to-cart" class="btn btn-primary">
          	Ad to cart	
          	</button>
          	</form>

          	</div>

refreshing

browser cache

and

performance-->clear the cache

 

but when i press the "Add to cart" button created, the item never go in the cart.

Any idea ?

Thanks

Link to comment
Share on other sites

  • 3 weeks later...

The reason it's not working is missing token input:

 <input type="hidden" name="token" value="{$static_token}">

So the correct form would be something like this:

<form action="{$urls.pages.cart}" method="post">
    <input type="hidden" name="token" value="{$static_token}">
    <input type="hidden" value="{$product.id_product}" name="id_product">
    <input type="number" style="padding: 9px 10px; float:left;width: 30%; margin-left: 10px;" class="input-group form-control" name="qty"
    <button style="float:left;margin-left: 13px" data-button-action="add-to-cart" class="btn btn-primary">Add to cart</button>
</form>

Edited by greenender (see edit history)
  • Like 3
Link to comment
Share on other sites

 

The reason it's not working is missing token input:

 <input type="hidden" name="token" value="{$static_token}">

So the correct form would be something like this:

<form action="{$urls.pages.cart}" method="post">
    <input type="hidden" name="token" value="{$static_token}">
    <input type="hidden" value="{$product.id_product}" name="id_product">
    <input type="number" style="padding: 9px 10px; float:left;width: 30%; margin-left: 10px;" class="input-group form-control" name="qty"
    <button style="float:left;margin-left: 13px" data-button-action="add-to-cart" class="btn btn-primary">Add to cart</button>
</form>

HI, and thanks for provide possible solution.

The page was response:

 
  1. Status Code:
     
    500 Internal Server Error

I guess I have the setting disabled in the back office, must be why mine works without :)

Disable where ?

Thanks

Link to comment
Share on other sites

  • 2 weeks later...

Hi, this is great stuff but i have a little problem. The quick view thingy gets hidden underneath the product description. How can we fix this? I've been toggling around with the height and position in #products .thumbnail-container, but can get it right.

 

Also, how can i make it accept only integer numbers?

Edited by gafonso (see edit history)
Link to comment
Share on other sites

EDIT:

 

Just found out this can be edited in theme.css, around line 6164:

#products .thumbnail-container:hover .highlighted-informations.no-variants, .featured-products .thumbnail-container:hover .highlighted-informations.no-variants, .product-accessories .thumbnail-container:hover .highlighted-informations.no-variants {
        bottom: 5.375rem; }

What about only accepting integer numbers in the quantity?

Edited by gafonso (see edit history)
Link to comment
Share on other sites

There's a problem adding to the cart, if you use a search filter like the included faceted search or if you press to show the next page in product list it doesn't add products until you refresh the page.

 

Any way to fix this? I guess forcing to refresh the page would work, but i have no idea where to do this.

 

Here is a video of the problem:

 

Link to comment
Share on other sites

I found a way to fix the problem. This is what i've done:

 

Go to theme folder/assets/js/theme.js and replace this code:

	  (0, _jquery2['default'])('body').on('change', '#search_filters input[data-search-url]', function (event) {
	    _prestashop2['default'].emit('updateFacets', event.target.dataset.searchUrl);
	  });
	
	  (0, _jquery2['default'])('body').on('click', '.js-search-filters-clear-all', function (event) {
	    _prestashop2['default'].emit('updateFacets', event.target.dataset.searchUrl);
	  });
	
	  (0, _jquery2['default'])('body').on('click', '.js-search-link', function (event) {
	    event.preventDefault();
	    _prestashop2['default'].emit('updateFacets', (0, _jquery2['default'])(event.target).closest('a').get(0).href);
	  });
	
	  (0, _jquery2['default'])('body').on('change', '#search_filters select', function (event) {
	    var form = (0, _jquery2['default'])(event.target).closest('form');
	    _prestashop2['default'].emit('updateFacets', '?' + form.serialize());
	  });

with this:

 (0, _jquery2['default'])('body').on('change', '#search_filters input[data-search-url]', function (event) {
	    _prestashop2['default'].emit('updateFacets', event.target.dataset.searchUrl);
        setInterval('window.location.reload()', 1000);
	  });    
        
	  (0, _jquery2['default'])('body').on('click', '.js-search-filters-clear-all', function (event) {
	    _prestashop2['default'].emit('updateFacets', event.target.dataset.searchUrl);
	  setInterval('window.location.reload()', 1000);
      });
	

That's it! All works fine now!

Link to comment
Share on other sites

  • 1 month later...

Hello,

 

I have a question about how to make a call to "submitCustomizedData", its inthe Save Customization button on the product page.

in fact, i wish to save submitCustomizedData in one step when user click on the "add-to-cart" button.

 

Please help

Link to comment
Share on other sites

  • 2 weeks later...

I found a way to fix the problem. This is what i've done:

 

Go to theme folder/assets/js/theme.js and replace this code:

	  (0, _jquery2['default'])('body').on('change', '#search_filters input[data-search-url]', function (event) {
	    _prestashop2['default'].emit('updateFacets', event.target.dataset.searchUrl);
	  });
	
	  (0, _jquery2['default'])('body').on('click', '.js-search-filters-clear-all', function (event) {
	    _prestashop2['default'].emit('updateFacets', event.target.dataset.searchUrl);
	  });
	
	  (0, _jquery2['default'])('body').on('click', '.js-search-link', function (event) {
	    event.preventDefault();
	    _prestashop2['default'].emit('updateFacets', (0, _jquery2['default'])(event.target).closest('a').get(0).href);
	  });
	
	  (0, _jquery2['default'])('body').on('change', '#search_filters select', function (event) {
	    var form = (0, _jquery2['default'])(event.target).closest('form');
	    _prestashop2['default'].emit('updateFacets', '?' + form.serialize());
	  });
with this:

 (0, _jquery2['default'])('body').on('change', '#search_filters input[data-search-url]', function (event) {
	    _prestashop2['default'].emit('updateFacets', event.target.dataset.searchUrl);
        setInterval('window.location.reload()', 1000);
	  });    
        
	  (0, _jquery2['default'])('body').on('click', '.js-search-filters-clear-all', function (event) {
	    _prestashop2['default'].emit('updateFacets', event.target.dataset.searchUrl);
	  setInterval('window.location.reload()', 1000);
      });
	
That's it! All works fine now!

 

 

 

This is not the right fix because it causes hard refreshing of whole page every second.

 

It does not work because ajax method responsible for fetching new filtered products does not deliver cart URL and token, which you originally added to the template.

You can easily fix it by adding those variables into template.

 

In classes/controller/ProductListingFrontController.php line:

$rendered_products = $this->render('catalog/_partials/products', array('listing' => $search));

replace with:

$rendered_products = $this->render('catalog/_partials/products',
array('listing' => $search,
'static_token' => Tools::getToken(false), // added token
'urls' => array('pages'=>array('cart'=>$this->context->link->getPageLink('cart'))))); // added link to the cart

This fix edits core files so with an update it will broke again.

Edited by hrtlik (see edit history)
  • Like 5
Link to comment
Share on other sites

  • 3 weeks later...

Hi,

 

don´t forget to check if catalog or not availible:

{if !$configuration.is_catalog}
    <form action="{$urls.pages.cart}" method="post">
        <input type="hidden" name="token" value="{$static_token}" />
        <input type="hidden" value="{$product.id_product}" name="id_product" />
        <input type="number" class="input-group form-control" name="qty" min="1" value="1" />
        <button data-button-action="add-to-cart" class="btn grid-cart-btn btn-primary" {if $product.availability == 'unavailable'}disabled{/if}>
                      Ad to cart    
        </button>
    </form>
{/if}

regards

Andy

  • Like 1
Link to comment
Share on other sites

  • 3 weeks later...

Hi, Can You reassume step by step what i have to do to get this function available? 
Which files i have to edit? which are the right code ?
I have installed prestashop  1.7.1 , i'm still working in his configuration so not online now (i mean that i don't sell until now)

I think this is a "normal" and basic feature for an ecommerce , maybe i'm wrong but in the previous version of prestashop
i remember the existence.
 

Many Thanks

Enrico
 

Link to comment
Share on other sites

I solved it myself, you need to call save customisations submit from core.js line 1836 in ps1.7.1.0

$body.on('click', '[data-button-action="add-to-cart"]', function (event) { 

add

if( $('#customizationForm').length > 0 )
	    {
	    	var customAction = $('#customizationForm').attr('action');
	    	$('body select[id^="group_"]').each(function() {
        	customAction = customAction.replace(new RegExp(this.id + '=\\d+'), this.id +'=' + this.value);
        	});
	    	// ajax to product page with custom action
		    var customization_entries = $('#customizationForm').serialize();
		    console.log(customization_entries);

		    $.ajax({
		        async:false,
		        type: 'POST',
		        data: customization_entries+ '&ajax=1',
		        dataType: 'json',
		        url: customAction,
		        success: function(data){
				   if(typeof(data.errors) !== 'undefined')
		            {
		                alert('Error while saving customization data');
		                return;
		            }
		            alert(data);
				},
				error : function(resultat, statut, erreur){
					//"errors...";
       			},
       			complete: function(resultat, statut){
       				//important. update customization_id
       				$('#product_customization_id').val( resultat.responseText );
       			}	
		    }) 

	    } 
Link to comment
Share on other sites

  • 1 month later...

It does not work because ajax method responsible for fetching new filtered products does not deliver cart URL and token, which you originally added to the template.

You can easily fix it by adding those variables into template.

 

In classes/controller/ProductListingFrontController.php line:

$rendered_products = $this->render('catalog/_partials/products', array('listing' => $search));

replace with:

$rendered_products = $this->render('catalog/_partials/products',
array('listing' => $search,
'static_token' => Tools::getToken(false), // added token
'urls' => array('pages'=>array('cart'=>$this->context->link->getPageLink('cart'))))); // added link to the cart

This fix edits core files so with an update it will broke again.

 

I changed only this, and searchbar, sorting and filters work now. :)

Edited by stdeykun (see edit history)
  • Like 1
Link to comment
Share on other sites

  • 5 months later...
On 3/19/2017 at 2:10 AM, hrtlik said:

 

 

This is not the right fix because it causes hard refreshing of whole page every second.

 

It does not work because ajax method responsible for fetching new filtered products does not deliver cart URL and token, which you originally added to the template.

You can easily fix it by adding those variables into template.

 

In classes/controller/ProductListingFrontController.php line:


$rendered_products = $this->render('catalog/_partials/products', array('listing' => $search));

replace with:


$rendered_products = $this->render('catalog/_partials/products',
array('listing' => $search,
'static_token' => Tools::getToken(false), // added token
'urls' => array('pages'=>array('cart'=>$this->context->link->getPageLink('cart'))))); // added link to the cart

This fix edits core files so with an update it will broke again.

 

Its a great fix! And it will not be lost after the update if you do the proper class override. Never edit the core files itself.

Link to comment
Share on other sites

  • 1 month later...

reanimated is totally right! @hrtlik you should put your fix in a class override.

Original class is in classes/controller/ProductListingFrontController

Overrided class should be in override/classes/controller/ProductListingFrontController.php

Code:

<?php
abstract class ProductListingFrontController extends ProductListingFrontControllerCore {
    /**
     * Similar to "getProductSearchVariables" but used in AJAX queries.
     *
     * It returns an array with the HTML for the products and facets,
     * and the current URL to put it in the browser URL bar (we don't want to
     * break the back button!).
     *
     * @return array
     */
    protected function getAjaxProductSearchVariables()
    {
        $search = $this->getProductSearchVariables();

        $rendered_products_top = $this->render('catalog/_partials/products-top', array('listing' => $search));
        $rendered_products = $this->render('catalog/_partials/products', array('listing' => $search, 'static_token' => Tools::getToken(false), 'urls' => array('pages'=>array('cart'=>$this->context->link->getPageLink('cart')))));
        $rendered_products_bottom = $this->render('catalog/_partials/products-bottom', array('listing' => $search));

        $data = array(
            'rendered_products_top' => $rendered_products_top,
            'rendered_products' => $rendered_products,
            'rendered_products_bottom' => $rendered_products_bottom,
        );

        foreach ($search as $key => $value) {
            $data[$key] = $value;
        }

        return $data;
    }
}

PS: Remember to delete the class_index.php file in whether app/cache/dev/class_index.php or app/cache/prod/class_index.php to take the override into account

Link to comment
Share on other sites

  • 1 year later...
  • 1 year later...

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...