1
votes

I made a module which will automatically add a product to Prestashop if it doesn't exist.

I've followed this subject on this matter and managed to make it work when adding a product with one image. But the problem is when I encountered a product with multiple images.

I tried to wrap it within a foreach loop so that it repeats the process for every image:

foreach ($image_arr as $image_val) {
    $image = new Image();
    $image->id_product = $product->id;
    $image->position = Image::getHighestPosition($product->id) + 1;
    $image->cover = true; // or false;
    if (($image->validateFields(false, true)) === true &&
        ($image->validateFieldsLang(false, true)) === true && $image->add())
    {
        $image->associateTo($product->id_shop_default);
        if (!copyImg($product->id, $image->id, $image_val, 'products', false))
        {
            $image->delete();
        }
    }
}

But it doesn't work. It throws duplicate error on ps_image

Any ideas how to make it work?

1

1 Answers

0
votes

You can't set all images cover property to true.

Here is the relevant indexes set on ps_image table:

 _________________________________________
| Name              | Unique | Column     |
|_________________________________________|
| id_product_cover  | Yes    | id_product |
|                   |        | cover      |
| idx_product_image | Yes    | id_image   |
|                   |        | id_product |
|                   |        | cover      |
|-----------------------------------------|

There should be only one cover per product.

You can change your code this way:

$cover = true;
foreach ($image_arr as $image_val) {
    $image = new Image();
    $image->id_product = $product->id;
    $image->position = Image::getHighestPosition($product->id) + 1;
    $image->cover = $cover;
    if (($image->validateFields(false, true)) === true &&
        ($image->validateFieldsLang(false, true)) === true && $image->add())
    {
        $image->associateTo($product->id_shop_default);
        if (!copyImg($product->id, $image->id, $image_val, 'products', false))
        {
            $image->delete();
        }
    }

    if ($cover)
    {
        $cover = false;
    }
}