How to update a custom filed in submittable doctype on change of value of another filed?

Is it possible to update a custom filed in submittable doctype on change of value of another filed in same doctype?

My requirement is pretty simple.

I want to create and update a custom filed “amount_paid” in doctype “Sales Invoice” whenever a “Payment Entry” is submitted for this Sales Invoice.

I observed that field “outstanding_amount” is updating while “Payment Entry” is created for “Sales Invoice”.

Is my approach is correct ? Is there another way to achieve this more easily?

Instead of updating submitted “Sales Invoice” through client script or server script.

Now, I am trying to create “Payment Entry” on submit of Sales Invoice (has a custom field “custom_advance_paid”, amount will be paid against this sales invoice).

Here is my test code to achieve this.

todo = frappe.get_doc({
    "doctype":"Payment Entry",
    "naming_series": "ACC-PAY-.YYYY.-",
    "payment_type": "Receive",
    "party_type": "Customer",
    "party": doc.customer,
    "paid_amount": doc.custom_advance_paid,
    "received_amount": doc.custom_advance_paid,
    "target_exchange_rate": "0",
    "paid_to": "Cash - AR",
    "mode_of_payment": "Cash",
    "paid_to_account_currency": doc.currency,
    "references": [
        {
            "reference_doctype": "Sales Invoice",
            "reference_name": "ACC-SINV-2023-00063",
            "due_date": "2023-12-22",
            "account": "Debtors - AR"
        }
    ]
})
todo.insert(ignore_permissions=True)
todo.submit()

I don’t know what is wrong, this code is unable to insert row in table “references” in payment entry, while Payment entry getting submitted successfully.

I am refering this document.

Tried below method but still I am not able to create table “references” inside “Payment Entry”.

My Server Script.

p = frappe.get_doc({
    "doctype":"Payment Entry",
    "naming_series": "ACC-PAY-.YYYY.-",
    "payment_type": "Receive",
    "party_type": "Customer",
    "posting_date": "2023-12-23",
    "party": doc.customer,
    "paid_amount": doc.custom_advance_paid,
    "received_amount": doc.custom_advance_paid,
    "target_exchange_rate": "0",
    "paid_to": "Cash - AR",
    "mode_of_payment": "Cash",
    "paid_to_account_currency": doc.currency,
})

p.append("references", {
    "reference_doctype": "Sales Invoice",
    "reference_name": doc.name
})
p.insert()
p.submit()