Question

I wish to create an event receiver that, when adding an item through an InfoPath form from one list to another, it will not create a new item if the item already exists, it will just update the 'quantity' of that item.

Eg.

Stock Items List > Add 2 Milk to Cart > Milk is already in Cart > Updates Milk to Quantity of 3.

Était-ce utile?

La solution

You should have a unique key to identify your item. Ideally this would be a number or something like that, so you can identify the item in the second list. In your example with the milk, you don't have an ID. So you could add one or you could just compare the item with the text (I suppose "Milk" will be in the title field)

When the item is being added in the list you can then in the "ItemAdding" check with an SPQuery if the item already exists in the list (enough examples to find online). If query returns 0 items, you can just let SharePoint do it's work as it normally should. If an item is found you should then update the quantity of the found item.

2 remarks you should take into account:

To avoid that the item is being added when it already is in the list you can use following code.

properties.Cancel = true;
properties.Status = SPEventReceiverStatus.CancelNoError

The cancel makes sure that the item is not being added. Normally this throws an error but by setting the status no error is thown.

The second thing you should take into account is if you want to let the item update fire on updating the quantity. Because this can cause strange behavior. I would recommend disabling event firing before updating the quantity and then enable it again.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top