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
Posted (edited)

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

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


×
×
  • Create New...

Important Information

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