Table refresh on button push

This button puts “beds.bed_id” into a new record on “bed.bed”. I want the “bed” table to refresh automatically so that I can see the new record without needing to click in the table and then click refresh.
This is the query that chatgpt helped me make:


Sub InsertBedWithSQL(Event As Object)
    Dim oForms As Object, oBedsForm As Object, oPlotsForm As Object
    oForms = ThisComponent.DrawPage.Forms
    oPlotsForm = oForms.getByName("Plots")
    oBedsForm = oPlotsForm.getByName("Beds")

    If oBedsForm.RowCount = 0 Then
        MsgBox "No bed selected.", 48, "Insert Cancelled"
        Exit Sub
    End If

    Dim bedID As String
    bedID = oBedsForm.getString(oBedsForm.findColumn("bed_id"))

    ' Check if the bed.bed already exists in the "bed" table
    Dim oConnection As Object
    oConnection = oBedsForm.ActiveConnection

    Dim oStatement As Object
    oStatement = oConnection.createStatement()

    ' Check if "bed.bed" already exists in the table
    Dim sSQL As String
    sSQL = "SELECT COUNT(*) FROM ""bed"" WHERE ""bed"" = '" & bedID & "'"

    On Error GoTo ColumnCheckError
    Dim oResultSet As Object
    oResultSet = oStatement.executeQuery(sSQL)

    oResultSet.next()
    If oResultSet.getInt(1) > 0 Then
        ' Pop-up message if the bed.bed already exists
        MsgBox "The bed ID " & bedID & " already exists in the table.", 48, "Insert Cancelled"
        Exit Sub
    End If

    ' Proceed with the insert if bed.bed doesn't already exist
    sSQL = "INSERT INTO ""bed"" (""bed"") VALUES ('" & bedID & "')"

    On Error GoTo ErrHandler
    oStatement.executeUpdate(sSQL)
    MsgBox "Inserted bed = " & bedID, 64, "Success"

    ' Re-query the data for the form (this should update the table control)
    oBedsForm.reload() ' Reloading the entire form to refresh all controls, including the table control

    Exit Sub

ColumnCheckError:
    MsgBox "Error checking column: " & Error$, 16, "Column Error"
    Exit Sub

ErrHandler:
    MsgBox "SQL Insert Error: " & Error$, 16, "Insert Failed"
End Sub`Preformatted text`


here is the database:https://www.dropbox.com/scl/fo/h9kn7rdru9s7e20h1s1f8/AFQNeUMCKouLx093XxMdxfI?rlkey=wdyderdusistlnlbkvedxfxf3&st=rn4rgjdy&dl=0

https://forum.openoffice.org/en/forum/download/file.php?id=35500 refreshes anything anywhere in the same form document after some record has been inserted, deleted or updated.

  • Run the install macro in the downloaded Writer document.
  • Add a hidden control to your form that is going to be modified (form navigator, right-click>New>Hidden Control)
  • Name it “AutoRefresh”
  • Add the hierarchical name(s) of one or more forms, list boxes or combo boxes, separated by semicolon.
  • Bind the form’s “After record action” event to the installed macro MyMacros>pyDBA>AutoRefresh>formAction

Sample:
../Form2/TableControl/Lisbox1;Subform refreshes “Listbox1” in “TableControl” which is part of “Form2” in this form’s parent node ../ AND this form’s “Subform”. The entries are separated by semicolon.
With this setup, you can use the same unmodified macro code for all use cases.

Deleted by skyandrews

Thank you for going beyond my initial issue and explaining how to improve the database. I think you are suggesting that I create a new table “latin_name” with pk integer “latin_name_id” and “latin_name” varchar. Then replace “latin name” varchar on “species”.“latin_name” with “latin_name_id”. I have the tables stored in a calc document. I can use vlookup to do that and recreate the tables… It’s like starting over from the beginning again… ugh… better late than never I guess…

Based on goedible dropbox sample version dated 4/20/25
Instructions to create new Primary Key in populated table of LO Base connected to split hsqldb (not embedded), while preserving relational integrity to dependant tables. Do not ignore the numerous “save” operations (ctrl+s) as each is critical to the process. Upon completion of this procedure, there will be some necessary, yet relatively minor modifications to related macros, forms, queries, or views. After saving a valid copy of the split database folder,

  • 1 Delete Relationships. Open the odb file from the original database folder, goto Tools / Relationships, delete all relations between the old Primary Key (oldPK) of the parent table (pTable) and all related old Foreign Keys (oldFK) of child tables (cTable). Save and close Relations! Save odb!
  • 2 Create copy of pTable. In the LO Base Tables list, drag and drop pTable in an empty area below the Tables list. In the prompt, name like “pTable2”, select only the “Definition and data” option, then Create. Do Not create new primary key. Verify the new pTable2 appears in the Tables list and then open to verify it is properly populate. If it appears correct, close the table and save the odb!
  • 3 Delete all pTable rows of data. Open pTable, select all rows (left click upper left corner header “block”), then right click the corner block and select “Delete rows”. The deletion may require some time, depending on the amount of data. When completed, close the empty pTable. Save odb, close the LO app, and then reopen the odb! (This clears LO cache in order to accomodate the following procedures adequately, preventing crashes)
  • 4 Edit pTable. Select and edit the pTable to remove the Primary Key designation of the current primary field (oldPK) by right clicking its row marker, then deselect “Primary Key”. (The key icon should disappear) Save table! Then append an integer type field named like “ID”. Save and close the table! Save and close the odb! To simplify and avoid confusion, try giving primary key fields a name like “ID” (standard Caps), and related foreign keys like “ptable_id” (descriptive lowercase).
  • 5 Edit “ID” field properties in db script file. In the original db folder, open the “mydb.script” file in a reliable text editor (notepad, notepad++, etc…). With editor’s “Word Wrap” OFF, find the line which begins with something like this: CREATE CACHED TABLE “pTable” - Select the line and then switch the editor’s “Word Wrap” to ON. Near the end of the selection is a segment that should be like this - “ID” INTEGER - Carefully replace with - “ID” INTEGER GENERATED BY DEFAULT AS IDENTITY(START WITH 0) NOT NULL PRIMARY KEY - Save and close script!
  • 6 Append data into pTable from pTable2. Reopen the odb, then in the Tables list, drag and drop pTable2 directly onto pTable. In the prompt, name = “pTable”, select only the “Append data” option, then Create. Do Not create new primary key! After process completes, verify pTable now has complete data, including a valid “ID” primary key auto-increment field at the last column. Close table.
  • 7 Delete pTable2 (optional). The pTable2 may now be deleted, or keep for backup. Upon deletion, save the odb! (Recommend delete to optimize odb)
  • 8 Create new Foreign Key fields (ptable_id) in all related child tables. Edit each child table which is related to pTable and append an integer field named like “ptable_id”. Save and close child table! Then open the child table and move it to the side to remain in view. In the LO main menu bar, select Tools / SQL. Type, or copy and paste the following into the SQL command window - UPDATE “cTable” SET “ptable_id” = SELECT “ID” FROM “pTable” WHERE “cTable”.“oldFK” = “pTable”.“oldPK” (Replace table and field names with the applicable names in your own database) Execute! If there is an error, it will be indicated in the Status window. (The command will fail, stop) The command may take a few minutes, based upon the amount of data to query. Successful completion will be indicated in the Status window. Upon successful completion, refresh the previously opened cTable by clicking the table’s menu bar “Refresh” icon. (May need to select “Refresh”) Visually verify that the new foreign key field (ptable_id) was successfully populated. If so, save and close table! Before opening the next child table, the SQL command tool must be closed! Close the SQL tool and then open the next related child table and move to the side. Then reopen the SQL tool and repeat this step for each of the other related child tables! (To clear its cache, it is recommended the LO app be saved, then completely closed and reopened between each successful SQL command update)
  • 9 Recreate relations between new pTable.ID primary key and all related cTables containing the new ptable_id foreign key. Goto LO main menu bar Tools / Relationships and recreate relations as previously described. With each relation, edit the Update property to “Update cascade” (right click the connecting line and select Edit). This will maintain the relationship even in the event the primary key integer is changed. Save and close relationship tool! Save the odb!
  • 10 Cleanup and debug. Before deleting all of the unneeded oldPK and oldFK fields, they may be used to debug any conversion problems which may arrise while implementing the new PK and FK fields. Otherwise, the old fields should be deleted.

BlockquoteThen save odb! Now set the auto increment of field ID to “YES”. Save and close table! Save odb! The empty “species_2” table is now ready to be appended with the data of table “species”.

Step 3: If I save the option to change AutoValue becomes grey/unchangeable. If I change AutoValue to Yes, after I press save it goes back to NO and becomes grey/unchangeable.

In a LO Base connection to a split hsqldb database, anytime that a table’s field properties need changed, they may be edited in the script file of the split odb. Before starting, there must not be any other field in the “tableName” marked as Primary Key. (right click far left row marker) There must also exist a simple integer field like “ID” with default properties

  • Save and close the odb! In the split odb folder, open the odb “mydb.script” file with a text editing app (notepad, or notepad++) and scroll to the line that starts with CREATE CACHED TABLE “tableName”.
  • Carefully replace - “ID” INTEGER - with - “ID” INTEGER GENERATED BY DEFAULT AS IDENTITY(START WITH 0) NOT NULL PRIMARY KEY - (Use “wordwrap” to see the whole line without horizontal scrolling).
  • Save and close the script file! Reopen the odb and check tableName.ID properties again. The ID properties will still be “greyed” out, but the auto-increment should now be YES and the row marked as Primary Key.
  • This is the easiest way IMO to edit the ID field properties in an empty table! Do not try this with a populated table as existing data will be cleared. An alternative method exists using the SQL tool, but for me, this method is much quicker and straight forward.
1 Like

Blockquote…VARCHAR(20),“Flower_Type” VARCHAR(20),“Pollinators” VARCHAR(100),“Self_fertile” BOOLEAN,“Known_hazards” VARCHAR(4000),“Synonyms” VARCHAR(400),“Cultivation_details” VARCHAR(4000),“Edible_uses” VARCHAR(3200),“Uses_notes” VARCHAR(3200),“Propagation” VARCHAR(2400),“Cultivars” BOOLEAN,“Cultivars_in_cultivation” BOOLEAN,“Heavy_clay” BOOLEAN,“Pull_out” BOOLEAN,“Last_update” TIMESTAMP,“Record_checked” BOOLEAN,“EdibilityRating” INTEGER,“FrostTender” BOOLEAN,“SiteSpecificNotes” VARCHAR(500),“Scented” BOOLEAN,“MedicinalRating” INTEGER,“ID” INTEGER NOT NULL PRIMARY KEY)
ALTER TABLE PUBLIC.“beds” ADD FOREIGN KEY(“plot_id”) REFERENCES PUBLIC.“Plots”(“plot_id”) ON DELETE CASCADE…

changed to

Blockquote…VARCHAR(20),“Flower_Type” VARCHAR(20),“Pollinators” VARCHAR(100),“Self_fertile” BOOLEAN,“Known_hazards” VARCHAR(4000),“Synonyms” VARCHAR(400),“Cultivation_details” VARCHAR(4000),“Edible_uses” VARCHAR(3200),“Uses_notes” VARCHAR(3200),“Propagation” VARCHAR(2400),“Cultivars” BOOLEAN,“Cultivars_in_cultivation” BOOLEAN,“Heavy_clay” BOOLEAN,“Pull_out” BOOLEAN,“Last_update” TIMESTAMP,“Record_checked” BOOLEAN,“EdibilityRating” INTEGER,“FrostTender” BOOLEAN,“SiteSpecificNotes” VARCHAR(500),“Scented” BOOLEAN,“MedicinalRating” INTEGER,“ID” INTEGER GENERATED BY DEFAULT AS IDENTITY(START WITH 0) NOT NULL PRIMARY KEY)
ALTER TABLE PUBLIC.“beds” ADD FOREIGN KEY(“plot_id”) REFERENCES PUBLIC.“Plots”(“plot_id”) ON DELETE CASCADE…

I get:

The connection to the data source “LANdpLAN” could not be established.
SQL Status: S1000
Error code: -25

error in script file line: 60 /root/Desktop/NewestLANdpLAN/LANdpLAN/mydb unknown token: at ./connectivity/source/drivers/jdbc/Object.cxx:173

In step 2 I get

BlockquoteSQL “Status: 42561
Error code: -5561
incompatible data type in conversion: from SQL type VARCHAR to java.lang.Long, value: Zoysia japonica at ./connectivity/source/drivers/jdbc/Object.cxx:173”

I click ok and the table seems to be fine.

In step 5 where you mention “pTable”, should it be “pTable2”?

pTable2 definition or data should never be changed. It is the “exact” copy of the original pTable. pTable is the only one to be modified (edit “ID” INTEGER …) before appending the pTable2 (original data) back into it.

After step 5. when I open .odb I got and error. Chat gpt helped me discover:

This part at the end is the issue:

,“ID” INTEGER)

The double quotes around ID are not standard ASCII double quotes. They are curly quotes (a.k.a. “smart quotes”):

“ and ” (instead of ") — these often get inserted by word processors like Microsoft Word or some text editors.