Edit Row

Demonstrates how to edit rows in a table

Back | Explain | Code | Htmx Docs
             from fasthtml.common import Button, Div, Input, Table, Tbody, Td, Th, Thead, Tr, fast_app

app, rt = fast_app()

DATA = [
    ("Joe 1", "joe1@a.b"),
    ("Joe 2", "joe2@a.b"),
    ("Joe 3", "joe3@a.b"),
    ("Joe 4", "joe4@a.b"),
]


@app.get
def page():
    return Div(cls="container-fluid")(
        Table(
            Thead(Tr(Th("Name"), Th("Email"), Th())),
            Tbody(hx_target="closest tr", hx_swap="outerHTML")(
                tuple(get_contact(i) for i in range(4)),
            ),
        ),
    )


@app.get("/contact/{idx}")
def get_contact(idx: int):
    name, email = DATA[idx]
    return Tr(
        Td(name),
        Td(email),
        Td(Button("Edit", hx_get=f"/contact/{idx}/edit", hx_trigger="edit", onclick=JS)),
    )


@app.get("/contact/{idx}/edit")
def edit_view(idx: int):
    name, email = DATA[idx]
    return Tr(hx_trigger="cancel", hx_get=f"/contact/{idx}", cls="editing")(
        Td(Input(name="name", value=name)),
        Td(Input(name="email", value=email)),
        Td(
            Button("Cancel", hx_get=f"/contact/{idx}", cls="btn secondary"),
            Button("Save", hx_put=f"/contact/{idx}", hx_include="closest tr", cls="btn primary"),
        ),
    )


@app.put("/contact/{idx}")
def put_contact(idx: int, x: dict):
    DATA[idx] = (x["name"], x["email"])
    return get_contact(idx)


JS = """
let editing = document.querySelector('.editing')
if(editing) {
    htmx.trigger(editing, 'cancel');
}
htmx.trigger(this, 'edit')
"""

# JS = """
# let editing = document.querySelector('.editing')
# if(editing) {
#     Swal.fire({
#         title: 'Already Editing',
#         showCancelButton: true,
#         confirmButtonText: 'Yep, Edit This Row!',
#         text:'Hey!  You are already editing a row!  Do you want to cancel that edit and continue?'
#     })
#     .then((result) => {
#         if(result.isConfirmed) {
#             htmx.trigger(editing, 'cancel')
#             htmx.trigger(this, 'edit')
#         }
#     })
# } else {
#     htmx.trigger(this, 'edit')
# }
# """
           

Direct url