Prestashop - как я могу добавить изображение во время создания продукта из кода
У меня есть код, с помощью которого я могу создать новый продукт prestashop. Я не могу получить какой-то рабочий код, который может добавить изображение во время создания продукта (новый продукт создан).
Я получил несколько ссылок, которые разделяют способ загрузки изображений, но ни один из них не работал. Может ли кто-нибудь направить меня, как я могу продолжить
PrestaShop Добавить картинки к товарам
Как добавить изображение при импорте программного продукта в prestashop?
рабочий код
$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.
Когда я запускаю код с новым продуктом, его изображение также должно быть обновлено.
Ответы - Prestashop - как я могу добавить изображение во время создания продукта из кода / Prestashop - How can I add image at the time of product create from code

10.09.2019 02:00:05
Мне удалось исправить проблему загрузки изображений. Это для тех, кто может столкнуться с той же проблемой.
Во-первых, загрузка изображения будет работать только на странице контроллера, а не на основной странице PHP, поэтому вызовите страницу на контроллере.
Предположим, в ссылке tpl у вас есть кнопка, по событию которой вы перейдете к контроллеру
<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 / контроллеры / фронт / addtocart.РНР
<?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;
}
}
Ваше здоровье !! :)