Jump to content
iomedia

[1.7] save customization when add to cart

Recommended Posts

Hello everyone,

 

I need some help about the customization. I want to remove the save button for customization and save directly when i add product to cart.

 

I found this tutorial http://nemops.com/save-prestashop-custom-fields-add-to-cart/#.WYnHXp-YEUE but it's for prestashop 1.6 and I have prestashop 1.7.1.1.

 

Can anyone help me or give me a link?

 

Thanks in advance

 

Florian

Share this post


Link to post
Share on other sites

Hello, I'm also looking for a solution for 1.7 

I googled and unearthed different links but nothing applicable to 1.7

(cant figure out how to adapt and play with modules/blockcart/ajax-cart.js like in 1.6x)

 

 

1 - So I tried to AJAXify the submission of  $("#customizationForm") FORM
before fire ADD TO CART button with jquery.

2 - I also tried to recreate a function to add product to cart but. Popup window showing an empty cart.

 

//$('#submitCustomizedData').hide();
		$(document).on('click', '#submitCustomizedData', function() {
            var urlAjax = $("#customizationForm").attr("action");
  		    var actionURL = prestashop.urls.pages.cart+'?add=1&id_product='+$("#product_page_product_id").val()+'&token='+prestashop.token;          

		      console.log("actionURL : "+actionURL);    

	
            jQuery.post(actionURL, {ajax: '1', action: 'update'}, null, 'json').then(function (resp) {
                //~ console.log('UPDATE');
                prestashop.emit('updateCart', {
                reason: {
                  idProduct: resp.id_product,
                  idProductAttribute: resp.id_product_attribute,
                  linkAction: 'add-to-cart'
                }
              });
            }).fail(function (resp) {
                //~ console.log('FAIL');
                prestashop.emit('handleError', { 
                  eventType: 'addProductToCart', 
                  resp: resp 
                  });
            });            
      
            return false;
        }); 

 

Any cLue please ?

 

Thanks a lot

 

 

Share this post


Link to post
Share on other sites

This only work only for one custom on product page (THX for niltona)  minimalism for validation field :):

Mod for 3 files no more:

- product-add-to-cart.tpl

A. Make false button in file example:

        <div id="ajouter_panier" class="ajouter_panier">
            Ajouter au panier
        </div>

B. Style button in CSS and hide original buttton :)

- ps_shoppingcart.js

A. Add funciotn to file:

$('.product-message').keyup(function () { 
    this.value = this.value.replace(/[^0-9\.]/g,'');
});
  
  
$( "#ajouter_panier" ).on( "click", function() {
    
    var warnning_message = 'S’il vous plaît entrez la taille Désirée';
    
    if( !$('.product-message').val() ) {
          //$('.product-message').addClass('warning');
          alert(warnning_message);
    } else {
    
    
    var formActionAttribute_url         = $(".product-customization form").attr('action');
    var formActionAttribute_name_field     = $(".product-customization form .product-message").attr("name");
    var formActionAttribute_value_field    = $('.product-message').val();
    var submitCustomizedData            = 'submitCustomizedData';
    
    var data = {};
    data[formActionAttribute_name_field]     = formActionAttribute_value_field;
    data[submitCustomizedData]                 = 'submitCustomizedData';

    $.post( formActionAttribute_url,  data ).done(function( data ) {

        $('.add-to-cart').removeAttr('disabled');
        $('.add-to-cart').click();
    });    

    }
});

 

 

Edited by web-port.pl (see edit history)
  • Like 2

Share this post


Link to post
Share on other sites

Hello, 

I wish You a happy prestayear.

 

This piece of code works at 95% for me (thanx to web-port.pl

I say 95 % because, I don't know why, sometimes the customzation field value remain empty when I check it in the checkout cart page.
Some cookie issue ?

 

So : 

 

in tpl :  product-add-to-cart.tpl

        {if $category->id == 12 || $category->id == 13}    
          <button class="ajouter_panier btn btn-primary add-to-cart col-lg-12 col-md-12 col-sm-12 col-xs-12"
            id="ajouter_panier"
            >
            <i class="material-icons shopping-cart">&#xE547;</i>
           Ajouter au panier CUSTOM
          </button>
         {/if}        
          <button
            class="btn btn-primary add-to-cart col-lg-12 col-md-12 col-sm-12 col-xs-12"
            data-button-action="add-to-cart"
            type="submit"
            id="ajouter_panier_classique"
            {if !$product.add_to_cart_url}
              disabled
            {/if}
          >
            <i class="material-icons shopping-cart">&#xE547;</i>
            {l s='Add to cart' d='Shop.Theme.Actions'}
          </button>

 

in javascript custom.js  of your theme : 

 

    $( document ).ready(function() {
        // 1 Masquer le bouton ajouter au panier
        $('#ajouter_panier_classique').hide();   
    });

    // Action sur bouton ajouter au panier CUSTOM

    $( "#ajouter_panier" ).on( "click", function() {

        var warnning_message = 'S’il vous plaît entrez une personnalisation';

        if( !$('.product-message').val() ) {
              //$('.product-message').addClass('warning');
              alert(warnning_message);
        } else {


        var formActionAttribute_url         = $(".product-customization form").attr('action');
        var formActionAttribute_name_field     = $(".product-customization form .product-message").attr("name");
        var formActionAttribute_value_field    = $('.product-message').val();
        var submitCustomizedData            = 'submitCustomizedData';

        var data = {};
        data[formActionAttribute_name_field]     = formActionAttribute_value_field;
        data[submitCustomizedData]                 = 'submitCustomizedData';

        $.post( formActionAttribute_url,  data ).done(function( data ) {
            $('#ajouter_panier_classique').removeAttr('disabled');
            $('#ajouter_panier_classique').click();
        });    

        }
    });

 

 

 

Edited by APINGO (see edit history)
  • Like 1

Share this post


Link to post
Share on other sites
Dnia 19.11.2017 o 11:02 AM, niltona napisał:

Hello

i need this too for ps 1.7, anyone can help? Thanks :)

up

Share this post


Link to post
Share on other sites

Just use hook actionCartSave and query sql for update your customization

Share this post


Link to post
Share on other sites

Hi, 

Solution propose by APINGO do perfectly the work for me. 

I've only one problem with file upload. 

I have 1 input file and 3 input text. 

I can save the text when add to cart but I can't save the file... I don't know if it's possible with the APINGO solution. 

Some idea ?

Sorry for my english, I hope I was clear

Share this post


Link to post
Share on other sites

Hello, we find a solution modify product-customization.tpl for new theme, that permit send the customizacion and in one only button add to cart, for simplify the process, wait that can help you.

 

If have some problem contact in https://www.digitaldot.es/soporte-prestashop

 

{literal}
<script type="text/javascript">
(function($) {
$( ".product-information .add-to-cart" ).on( "click", function(event) {
if($('.product-customization form').length){
event.preventDefault();
addcustomizationcart();
}
});
 
function addcustomizationcart(){
        var formActionAttribute_url = $(".product-customization form").attr('action');
        var dat = new FormData($('.product-customization form')[0]);
        
        $.ajax({
          type: "POST",
          enctype: 'multipart/form-data',
          url : formActionAttribute_url,
          data : dat,
          contentType: false,
          cache: false,
          processData:false,
          success: function(data){
            if(typeof(data.errors) !== 'undefined')
             {
              
             }
             let query = $('#add-to-cart-or-refresh').serialize() + '&add='+$('#quantity_wanted').val()+'&action=update';
              $.post($("#add-to-cart-or-refresh").attr('action'), query, null, 'json').then((resp) => {
                prestashop.emit('updateCart', {
                reason: {
                  idProduct: resp.id_product,
                  idProductAttribute: resp.id_product_attribute,
                  idCustomization: resp.id_customization,
                  linkAction: 'add-to-cart',
                  cart: resp.cart
                },
                resp: resp
                });
              }).fail((resp) => {
                prestashop.emit('handleError', {eventType: 'addProductToCart', resp: resp});
              });
           },
           error : function(resultat, statut, erreur){
             //"errors...";
            },
            complete: function(resultat, statut){
              //important. update customization_id
            }
         })
    }
 
}(jQuery));
</script>
{/literal}

Share this post


Link to post
Share on other sites

Thank you very much, guys. You've helped me a lot, even when your solutions were not fully working in my case, because you forgot some part explained at link from first message about 1.6 solution:

We need also to override ProductController.php. The code explained at link is for PS 1.6, but we can adapt it to 1.7 version pretty easy. In my case, I made this override:

class ProductController extends ProductControllerCore
{
    public function postProcess()
    {
        if (Tools::getValue('ajax') && Tools::isSubmit('submitCustomizedData'))
        {
            // If cart has not been saved, we need to do it so that customization fields can have an id_cart
            // We check that the cookie exists first to avoid ghost carts
            
            if (!$this->context->cart->id && isset($_COOKIE[$this->context->cookie->getName()])) {
                $this->context->cart->add();
                $this->context->cookie->id_cart = (int) $this->context->cart->id;
            }
            $this->pictureUpload();
            $this->textRecord();
            $customization_datas = $this->context->cart->getProductCustomization($this->product->id, null, true);
     
            if($this->errors) {
                $error_list = implode('; ', $this->errors);
                die(Tools::jsonEncode(array('errors' => $error_list)));
            } else {
                die(Tools::jsonEncode(array('success' => true, 'id_customization' => empty($customization_datas) ? null : $customization_datas[0]['id_customization'])));
            }
        }
    }
}

This way, I get id_customization, that is necessary to have ajax cart working, at least in my theme, because it doesn't work (or does, but incorrectly) if you doesn't update #product_customization_id hidden input.

So my AJAX call to save customization without reloading page is:

var customizationContainers = $(".product-customization-item");
customizationContainers.each(function() {
  if ($($(this).find("label")[0]).text().trim()=='Custom pack') {		// My custom field has always this name
    var formActionAttribute_url = $(".product-customization form").attr('action');
    var formActionAttribute_name_field = $(this).find(".product-message").attr("name");
    var data = {};
    data[formActionAttribute_name_field] =  $(this).find(".product-message").val();
    data['submitCustomizedData'] = 1;
    data['ajax'] = 1;
    $.post(formActionAttribute_url, data, null, 'json').done(function(data) {
      $(".product-actions #product_customization_id").val(data.id_customization);
    });
    return false;
  }
});

For simplicity, I'm not taking into account in this code possible errors coming from AJAX data result.

Edited by Prestafan33 (see edit history)

Share this post


Link to post
Share on other sites

The code works for most of the time but sometimes it creates a new id_customization for every textfield.
So textfield_1 has e.g. id_customization = 3 and textfield_2 has e.g. id_customization = 4 when they should haven been both id_customization = 3

Can't put my finger on it. Bug in Presta?

Share this post


Link to post
Share on other sites

As @Prestafan33 says #product_customization_id needs to be updated before adding adding the product to the cart. 

I've been able to solve this @web-port.pl solution:

function customAdd(min_quantity) {

    if (!min_quantity) min_quantity = null;
    if(customQuantity() >= minQuantity){
        saveCustom(); //saves custom product text
        var warnning_message = 'Product customization error. Please try again or contact the seller.';

        if( !$('.product-message').text() ) {
              alert(warnning_message);
        } else {
        
        var formActionAttribute_url         = $(".product-customization form").attr('action');
        var formActionAttribute_name_field     = $(".product-customization form .product-message").attr("name");
        var formActionAttribute_value_field    = $('.product-message').text();
        var submitCustomizedData            = 'submitCustomizedData';
        
        var data = {};
        data[formActionAttribute_name_field]     = formActionAttribute_value_field;
        data[submitCustomizedData]                 = submitCustomizedData;
        

        $.post( formActionAttribute_url,  data, function( data ) {

            var id_customization = parseInt(data.match(/(id_customization" value="\d+)/i)[0].split("\" value=\"")[1]);
            
            console.log(id_customization);
            $(".product-actions #product_customization_id").val(id_customization);

            $('.add-to-cart').removeAttr('disabled');
            $('.add-to-cart').click();
        }, 'html' );    
    
        }
    }
}

Hope it helps!

  • Confused 1

Share this post


Link to post
Share on other sites

 

Does anyone have a solution to save customization when adding to the cart for Prestashop version 1.7?

 

Thank you

Share this post


Link to post
Share on other sites
On 5/24/2020 at 2:23 AM, dinasilva said:

Does anyone have a solution to save customization when adding to the cart for Prestashop version 1.7?

I'm working on a module to do this. Send me a private message if you want to (beta) test it on a test-instance of your shop

  • Like 2

Share this post


Link to post
Share on other sites
On 5/24/2020 at 7:23 AM, dinasilva said:

 

Does anyone have a solution to save customization when adding to the cart for Prestashop version 1.7?

 

Thank you

On presta 1.7, they have updated database for this. Try refer table ps_customization_* with column id_module.

Read ps class and you can find yours.

Share this post


Link to post
Share on other sites

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...

Important Information

Cookies ensure the smooth running of our services. Using these, you accept the use of cookies. Learn More