Saverian
Saverian
Incrementing items by drag and drop
I'm trying to handle incrementing item quantities rather than adding new items when you drag and drop an item to a character sheet, as long as the item already exists in their inventory and is of the right type. I've set up a hook in my ready hook section (using the Boilerplate as a base) but now it's both incrementing the existing item and adding a brand new one.
  Hooks.on("preCreateItem", async (item, options, userId) => {
    const actor = item.parent;

    // Define the item types that should have quantity incremented
    const incrementableTypes = ["gear", "consumable", "scroll", "lootbox"];

    // Check if the item type is one where the quantity should be incremented
    if (incrementableTypes.includes(item.type)) {
      // Find if the actor already has an item with the same name and type
      const existingItem = actor.items.find(i => i.name === item.name && i.type === item.type);

      if (existingItem) {
        // Increment the quantity of the existing item
        const newQuantity = (existingItem.system.quantity || 1) + (item.system.quantity || 1);

        // Update the existing item's quantity
        await existingItem.update({ "system.quantity": newQuantity });

        // Prevent creating a new item
        return false;
      }
    }

    return true;
  });
  Hooks.on("preCreateItem", async (item, options, userId) => {
    const actor = item.parent;

    // Define the item types that should have quantity incremented
    const incrementableTypes = ["gear", "consumable", "scroll", "lootbox"];

    // Check if the item type is one where the quantity should be incremented
    if (incrementableTypes.includes(item.type)) {
      // Find if the actor already has an item with the same name and type
      const existingItem = actor.items.find(i => i.name === item.name && i.type === item.type);

      if (existingItem) {
        // Increment the quantity of the existing item
        const newQuantity = (existingItem.system.quantity || 1) + (item.system.quantity || 1);

        // Update the existing item's quantity
        await existingItem.update({ "system.quantity": newQuantity });

        // Prevent creating a new item
        return false;
      }
    }

    return true;
  });
3 replies