4d-database

Pass a string to method CREATE RECORD in 4D


Can i pass a string variable to the 4D CREATE RECORD method ? or any other method i just need to set the name table as a variable. I already tried to pass a string variable but as the method only accepts table object i can't find any way to do that


Solution

  • You can do this with a pointer. Anywhere 4D expects a table you can use a dereferenced pointer to a table.

    You can get a pointer to a table in a few ways:

    C_Pointer($pTable)
    $pTable:=Table(4) // where 4 is the table number; command returns a pointer to the table
    // -OR-
    $pTable:=->[SomeTable] // directly setting a pointer to the table
    
    CREATE RECORD($pTable->) // dereferenced pointer as parameter
    // do some work here, setting field values
    SAVE RECORD($pTable->)
    

    Depending on how you are choosing the variable table name you may need some code to tie the text to the table or table number. A method that took the text and set a pointer to the table would do the trick.

    Update: Incorporating what @TomB suggested (I wasn't aware of that command), I would do something like this (though in real code I'd create a method that returned a pointer to the table rather than running Create Record in the If statement). Where $tSomeTableName is the string variable you are working with.

    ARRAY TEXT($atTableNames;0)
    ARRAY LONGINT($aLTableNumbers;0)
    GET TABLE TITLES($atTableNames;$aLTableNumbers)
    
    C_LONGINT($LFind)
    $LFind:=Find in array($atTableNames;$tSomeTableName)
    
    C_POINTER($pTable)
    If ($LFind>0)
        $pTable:=Table($aLTableNumbers{$LFind})
    
        CREATE RECORD($pTable->)
          // do some work
        SAVE RECORD($pTable->)
    
    Else 
        ALERT("Table name "+$tSomeTableName+" not recognized.")
    End if 
    

    I prefer this to Execute Formula because it handles cases where the table name in the text variable is not a valid table name in the database.