Bukimedia / PrestaSharp

CSharp .Net client library for the PrestaShop API via web service
GNU General Public License v3.0
154 stars 152 forks source link

Error changing id_category_default on product #446

Closed infosteo closed 1 year ago

infosteo commented 1 year ago

Hello, I'm getting this error: You cannot set a position greater than the total number of products in the category, which starts at 1.

This happens after I deleted some categories in a product and after I changed id_category_default (and updated the product).

my code:

// Artico is my product

Bukimedia.PrestaSharp.Entities.AuxEntities.category[] aDelCats = new Bukimedia.PrestaSharp.Entities.AuxEntities.category[Artico.associations.categories.Count];
Artico.associations.categories.CopyTo(aDelCats);

        foreach (Bukimedia.PrestaSharp.Entities.AuxEntities.category delCat in aDelCats)
        {
          if (delCat.id != 2) //default, never delete
          {
            if (dtCate.Select("xx_psid = '" + delCat.id.ToString() + "'").Length == 0) //expression needed to find items to delete
            {
              Artico.associations.categories.Remove(delCat);
            }
          }
        }
        idCatDef = 222; //new default (example)

    if (Artico.id_category_default != idCatDef)
    {          
      Artico.id_category_default = idCatDef;
      productfactory.Update(Artico); // <== exception
    }

Any suggestion?

Thank you!

infosteo commented 1 year ago

Here is the solution: change the last lines of code:

    if (Artico.id_category_default != idCatDef)
    {          
      Thread.Sleep(250);
      productfactory.Update(Artico);
      //read again the product
      Artico = productfactory.Get((long)Artico.id); 
      Artico.id_category_default = idCatDef;
      productfactory.Update(Artico);
    }