Prestashop: add customized product to cart

前端 未结 2 1049
情深已故
情深已故 2020-12-15 14:48

I\'m writnig a custom controller for Prestashop. It is suposed to do a simple task: 1. Create a new cart if it wasn\'t created (working fine) 2. Get attribute ID from databa

相关标签:
2条回答
  • 2020-12-15 14:55

    I managed to fix the problem.

    1. Proper way to create a cart:

      if (!$this->context->cart->id)
      {
          if (Context::getContext()->cookie->id_guest)
          {
              $guest = new Guest(Context::getContext()->cookie->id_guest);
              $this->context->cart->mobile_theme = $guest->mobile_theme;
          }
          $this->context->cart->add();
          if ($this->context->cart->id)
              $this->context->cookie->id_cart = (int)$this->context->cart->id;
      }
      
    2. Add customization

      $this->product = new Product(1, true, (int)($this->context->cookie->id_lang));
      
      $authorized_text_fields = array();
      
      if (!$field_ids = $this->product->getCustomizationFieldIds())
              return false;
      
      foreach ($field_ids as $field_id)
          if ($field_id['type'] == Product::CUSTOMIZE_TEXTFIELD)
              $authorized_text_fields[(int)$field_id['id_customization_field']] = 'textField'.(int)$field_id['id_customization_field'];
      
          $indexes = array_flip($authorized_text_fields);
          foreach ($_POST as $field_name => $value)
              if (in_array($field_name, $authorized_text_fields) && !empty($value))
              {
                  if (!Validate::isMessage($value))
                      $this->errors[] = Tools::displayError('Invalid message');
                  else
                  $this->context->cart->addTextFieldToProduct($this->product->id, $indexes[$field_name], Product::CUSTOMIZE_TEXTFIELD, $value);
              }
              else if (in_array($field_name, $authorized_text_fields) && empty($value))
                  $this->context->cart->deleteCustomizationToProduct((int)$this->product->id, $indexes[$field_name]);
      
    3. Get the customizations

      $texts = $this->context->cart->getProductCustomization($this->product->id, Product::CUSTOMIZE_TEXTFIELD, true);
      $text_fields = array();
      foreach ($texts as $text_field)
          $text_fields['textFields_'.$this->product->id.'_'.$text_field['index']] = str_replace('<br />', "\n", $text_field['value']);
      
    0 讨论(0)
  • 2020-12-15 15:09

    The most simple to validate a cart:

    // Validate the object cart $this->context->cart->save(); $this->context->cookie->id_cart = (int)$this->context->cart->id;

    the save() method upate the cart if exists or create a new if not. Then force the cookie to have the same id.

    0 讨论(0)
提交回复
热议问题