Warm tip: This article is reproduced from stackoverflow.com, please click
prestashop

How to update product.quantity in PrestaShop with PrestaSharp?

发布于 2020-03-27 15:47:29

I'm using prestaSharp for C#. I need to update the product quantity but product.quantity property is readonly.

var ProductFactory = new Bukimedia.PrestaSharp.Factories.ProductFactory(BaseUrl, Account, Password);
List<Bukimedia.PrestaSharp.Entities.product> products = ProductFactory.GetAll();
foreach (var item in myItems)
{
    var productToUpdate = products.First(x => x.reference == item.Ref);
    // update the quantities
    if (productToUpdate != null)
    {
        productToUpdate.quantity = item.Quantity;
    }
}
await ProductFactory.UpdateListAsync(products);

How should i proceed? Thanks in advance

Questioner
Biiz
Viewed
459
Biiz 2020-02-03 20:52

based on that github reply i was able to convert the VB code, and update all the stocks in a single call

var ProductFactory = new Bukimedia.PrestaSharp.Factories.ProductFactory(BaseUrl, Account, Password);
var StockAvailableFactory = new Bukimedia.PrestaSharp.Factories.StockAvailableFactory(BaseUrl, Account, Password);

// call prestasharp/api/Products to get the products
List<Bukimedia.PrestaSharp.Entities.product> products = ProductFactory.GetAll();

var stocksToUpdate = new List<Bukimedia.PrestaSharp.Entities.stock_available>();
foreach (var itemQ in itemsQuantity)
{
    var productToUpdate = products.First(x => x.reference == itemQ.Ref);
    // update the quantities
    if (productToUpdate != null)
    {
        var dtnSearch = new Dictionary<string, string>();
        dtnSearch.Add("id_product", productToUpdate.id.ToString());
        var currentStock = await StockAvailableFactory.GetByFilterAsync(dtnSearch, null, null);
        if(0 < currentStock.Count())
        {
            currentStock[0].quantity = Decimal.ToInt32(itemQ.Quantity);
            stocksToUpdate.Add(currentStock[0]);
        }
    }
}
await StockAvailableFactory.UpdateListAsync(stocksToUpdate);