ios – How can I add multiple items to an invoice?


I am making an invoice maker app using swift and swiftdata, where user can input invoice title, select customers and add multiple items, I created my form but for some reason the items I add to my form doesn’t seem to show below add items section. I have got three models, Invoice, Customer and Items

could it be a problem here?

struct AddInvoiceView: View {
    @Environment(\.dismiss) private var dismiss
    @Environment(\.modelContext) private var context
    // View Properties
    @State private var InvoiceName: String = ""
    @State private var customer: Customer?
    @State private var ItemName: String = ""
    @State private var ItemPrice: Double? = nil
    @Query private var items: [Item]
    //
    @Query(animation: .snappy) private var allCustomers: [Customer]


//the form section to add items
Section(header: Text("Add Item")) {
                    TextField("Name", text: $ItemName)
                    TextField("Price", value: $ItemPrice, format: .number)
                        .keyboardType(.numberPad)
                    Button("Add") {
                        addItem()
                        ItemName = ""
                        ItemPrice = nil
                    }.disabled(!isFormValid)
                }
                
                Section("Items") {
                    List(items) { item in
                        NavigationLink(value: item) {
                            HStack {
                                Text(item.ItemName)
                                Spacer()
                                Text(item.ItemPrice, format: .currency(code: Locale.current.currency?.identifier ?? "USD"))
                            }
                        }
                        
                    }
                }


//here is my add button for adding and deleting items
    private func addItem() {
        let item = Item(ItemName: ItemName, ItemPrice: ItemPrice!)
        context.insert(item)
    }
    
    func deleteItem(_ indexSet: IndexSet) {
        for index in indexSet {
            let item = items[index]
            context.delete(item)
        }
    }

I tried so many way to fix it but, when i tried once it did add items, however i couldn’t delete them and the items were saved in the new form, which i dont want as each invoice has different items.

Latest articles

spot_imgspot_img

Related articles

Leave a reply

Please enter your comment!
Please enter your name here

spot_imgspot_img