Page 1 of 1

Batch Delete Products

Posted: Wed May 04, 2011 3:22 pm
by jasonhendee
I'm wanting to delete all products except a couple from my dev site, and saw in this post: viewtopic.php?f=42&t=14280 where mazhar said:
mazhar wrote:I suggest you better make use of API code to drop products. API will make sure to keep things consistent across the database.
So, being fairly new to AbleCommerce (and .Net for that matter), does this look reasonable?

Code: Select all

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="CFLNew_BatchDeleteProducts.ascx.cs"
    Inherits="ConLib_Custom_CFLNew_BatchDeleteProducts" %>
<asp:Panel ID="BatchDeleteProductsPanel" runat="server">
    <asp:Button ID="BatchDeleteProductsButton" runat="server" Text="Delete Products..."
        OnClick="BatchDeleteProductsButton_Click" />
</asp:Panel>
<div style="font-weight: bold; color: #cc0000; padding-top: 10px;">
    <asp:Label ID="Results" runat="server" Text=""></asp:Label>
</div>
Code Behind:

Code: Select all

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CommerceBuilder.Common;
using CommerceBuilder.Products;

public partial class ConLib_Custom_CFLNew_BatchDeleteProducts : System.Web.UI.UserControl
{
    private ProductCollection Products = ProductDataSource.LoadForStore();
    private bool successful = true;

    protected void Page_Load(object sender, EventArgs e)
    {
        Products.RemoveAt(Products.IndexOf(1911));
        Products.RemoveAt(Products.IndexOf(2398));
    }

    protected void BatchDeleteProductsButton_Click(object sender, EventArgs e)
    {
        if (Products.Count > 0)
        {
            foreach (Product product in Products)
                if (!product.Delete())
                    successful = false;
            if (successful)
                Results.Text = "All specified products were deleted.";
            else
                Results.Text = "Some or all specified products were NOT deleted.";
        }
        else
            Results.Text = "No products to delete!";
    }
}
Simple, but seems effective.

So in my example, I've chosen to keep products with ProductId's 1911 & 2398. Without having source, I can't tell if the Product.Delete() method alone performs all appropriate actions to completely remove my products, but a quick glance in some related db tables (i.e. ac_ProductVariants, ac_CatalogNodes, etc) says that this is working. Am I over-simplifying this, or is that all there is to it?

Re: Batch Delete Products

Posted: Wed May 11, 2011 7:18 am
by AbleMods
Using _Product.Delete() should do all the "housekeeping" you need. The SQL cascade deletes will take care of the rest.