Prestashop - 如何在从代码创建产品时添加图像

Prestashop - How can I add image at the time of product create from code

我有代码可以用来创建新的 prestashop 产品。我无法获得一些可以在创建产品(创建新产品)时添加图像的工作代码。

我得到的分享图片上传方式的链接很少,但 none 有效。有人可以指导我如何进行吗

prestashop add images to products

工作代码

$product = new Product();        // insert case
// $product = new Product(7467); // update case
$product->name = [$default_lang => $roomname . '/' . $hotelname . ' (Room/Hotel/Ratekey)'];
$product->link_rewrite = [$default_lang => 'hotels'];
$product->price = $price;
$product->description = $ratekey;
$product->id_category = [30];
$product->id_category_default = 30;

// add products
if($product->add()) {
                          $product->updateCategories($product->id_category);
                          StockAvailable::setQuantity((int)$product->id, 0, $product->quantity, Context::getContext()->shop->id);
                        }

// need to write code that adds the image along with the newly product created.

当我 运行 使用新产品的代码时,它的图像也应该更新。

我设法解决了图片上传问题。这是为那些可能面临同样问题的人准备的。

首先,图片上传只能在控制器页面中使用,而不能在核心 PHP 页面中使用,因此请在控制器上调用该页面。

假设在 tpl link 中你有一个按钮,它的事件你将转到控制器

<form id="myform" action="{$link->getModuleLink('hotelapi', 'testing')|escape:'html'}" method="post">
        <input type="hidden" name="testing">
        <input type="submit" name="testsubmit" value="Test Link" />
</form>

mymodule/controllers/front/addtocart.php

<?php
// class customTestingController extends ModuleFrontController
class hotelapiAddtocartModuleFrontController extends ModuleFrontController
{
    /*public function init()
    {
        echo $_POST['test'];
        echo 'kkkkkkkkkk'; die('dddddddddddd');
    }*/

    public function postProcess()
    {       

        /*===================== Handeling Image for Prestashop Upload: Start ===================== */
             $query = "SELECT `id_product` FROM `"._DB_PREFIX_."product` ORDER BY id_product DESC LIMIT 1";
             $id = Db::getInstance()->executeS($query);
             $id_product = $id[0]['id_product'];

             $langId = (int) (Configuration::get('PS_LANG_DEFAULT'));


                // checking image
                $image = new Image();
                $image->id = 1;
                $image->position = Image::getHighestPosition($id_product) + 1;
                $image->cover = true; // or false;
                $image->id_product = intval($id_product);

                if(Image::getImagesTotal($id_product)>0)
                 $image->cover = false;
                else
                  $image->cover = true;

                $languages = Language::getLanguages();

                foreach ($languages as $language)
                 $image->legend[$language['id_lang']] = 'Click to view';
                $id_image = $image->id;
                /*if($image->add()) {
                    echo "yes";
                } else {
                    echo "no";
                }*/
                if (($image->validateFields(false, true)) === true &&
                ($image->validateFieldsLang(false, true)) === true && $image->add())
                {   $url = trim($_POST['hotelimage'], "'");    // hotel image
                    // test images
                    // $url = "http://photos.hotelbeds.com/giata/00/001075/001075a_hb_r_001.jpg";
                    // $url = "http://photos.hotelbeds.com/giata/original/00/004200/004200a_hb_ro_006.jpg";
                    $image->associateTo($shops);

                    if (!self::copyImg($id_product, $image->id, $url, 'products'))
                    {
                        $image->delete();
                    }

                    echo 'iamge uploaded';
                }
        /*===================== Handeling Image for Prestashop Upload: End ===================== */

        /*===================== Handeling Cart for Product Upload: Start ===================== */
            if ($this->context->cookie->id_cart)
           {
             // die('restrict cart....');
             $cart = new Cart($this->context->cookie->id_cart);


             // To get Product ID
             $query = "SELECT `id_product` FROM `"._DB_PREFIX_."product` ORDER BY id_product DESC LIMIT 1";
             $latest_idnumber = Db::getInstance()->executeS($query);

             // getting cart information here
              $customData = $this->context->cookie->id_customer;    //user id
              $quantity   = 1; // room booking qty will always be 1
              $attribute  = 74; //enter the id_product_attribute
              $id_product = (int) $latest_idnumber[0]['id_product'];
              // $id_product = 8067;                                   // product

              $Cart = $this->context->cart;

              /*print_r($Cart->updateQty($quantity, $id_product, $id_product_attribute = null, $id_customization = false, $operator = 'up', $id_address_delivery = 0, $shop = null, $auto_add_cart_rule = true));*/

              $Cart->updateQty($quantity, $id_product, $id_product_attribute = null, $id_customization = false, $operator = 'up', $id_address_delivery = 0, $shop = null, $auto_add_cart_rule = true);

              Tools::redirect('/gb/module/hotelapi/display');


           }

           // create new cart if needed
            if (!isset($cart) OR !$cart->id)
            {
                $cart = new Cart();
                $cart->id_customer = (int)($this->context->cookie->id_customer);
                $cart->id_address_delivery = (int)  (Address::getFirstCustomerAddressId($cart->id_customer));
                $cart->id_address_invoice = $cart->id_address_delivery;
                $cart->id_lang = (int)($this->context->cookie->id_lang);
                $cart->id_currency = (int)($this->context->cookie->id_currency);
                $cart->id_carrier = 1;
                $cart->recyclable = 0;
                $cart->gift = 0;
                $cart->add();
                $this->context->cookie->id_cart = (int)($cart->id);    

                $cart->update();
            }
/*===================== Handeling Cart for Product Upload: End ===================== */

    } // end function

    // This function handels image upload for prestashop product
    function copyImg($id_entity, $id_image = null, $url, $entity = 'products')
            {
                $tmpfile = tempnam(_PS_TMP_IMG_DIR_, 'ps_import');
                $watermark_types = explode(',', Configuration::get('WATERMARK_TYPES'));

                switch ($entity)
                {
                    default:
                    case 'products':
                        $image_obj = new Image($id_image);
                        $path = $image_obj->getPathForCreation();
                    break;
                    case 'categories':
                        $path = _PS_CAT_IMG_DIR_.(int)$id_entity;
                    break;
                }
                $url = str_replace(' ' , '%20', trim($url));
                // Evaluate the memory required to resize the image: if it's too much, you can't resize it.
                if (!ImageManager::checkImageMemoryLimit($url))
                    return false;
                // 'file_exists' doesn't work on distant file, and getimagesize make the import slower.
                // Just hide the warning, the traitment will be the same.
                if (@copy($url, $tmpfile))
                {
                    ImageManager::resize($tmpfile, $path.'.jpg');
                    $images_types = ImageType::getImagesTypes($entity);
                    foreach ($images_types as $image_type) 
                    { 
                        ImageManager::resize($tmpfile, $path.'-'.stripslashes($image_type['name']).'.jpg', $image_type['width'], $image_type['height']); 

                        if (in_array($image_type['id_image_type'], $watermark_types)) 
                            Hook::exec('actionWatermark', array('id_image' => $id_image, 'id_product' => $id_entity)); 
                    }

                }
                else
                {
                    unlink($tmpfile);
                    return false;
                }
                unlink($tmpfile);
                return true;
            }
}

干杯! :)