### Starting Global and Local Processes in 4D Source: https://developer.4d.com/docs/18/Concepts/identifiers Illustrates how to start global and local processes using the New process command. The first example starts a global process, and the second starts a local process. ```4D //Starting the global process "Add Customers" $vlProcessID:=New process("P_ADD_CUSTOMERS";48*1024;"Add Customers") ``` ```4D //Starting the local process "$Follow Mouse Moves" $vlProcessID:=New process("P_MOUSE_SNIFFER";16*1024;"$Follow Mouse Moves") ``` -------------------------------- ### Example Query with $queryplan Source: https://developer.4d.com/docs/18/REST/queryplan This example shows how to pass the $queryplan parameter in a GET request to retrieve the query plan for a filter operation. ```http GET /rest/People/$filter="employer.name=acme AND lastName=Jones"&$queryplan=true ``` -------------------------------- ### Basic Error-Handling Method Example Source: https://developer.4d.com/docs/18/Concepts/error-handling A simple example demonstrating how to install an error-handling method, execute code, and then disable error catching. The errorMethod project method logs specific errors. ```4D //installing the error handling method ON ERR CALL("errorMethod") //... executing code ON ERR CALL("") //giving control back to 4D ``` ```4D // errorMethod project method If(Error#1006) //this is not a user interruption ALERT("The error "+String(Error)+" occurred". The code in question is: """+Error formula+""") End if ``` -------------------------------- ### Using Collection and Object Methods Source: https://developer.4d.com/docs/18/Concepts/quick-tour Shows how to use collection and object methods with dot notation. Examples include creating a collection and slicing it, and getting the last employee. ```4D $c:=New collection(1;2;3;4;5) $nc:=$c.slice(0;3) //$nc=[1,2,3] $lastEmployee:=$employee.last() ``` -------------------------------- ### Example REST GET Request with Query Parameters Source: https://developer.4d.com/docs/18/REST/REST_requests Demonstrates a GET request to a Person dataclass with a filter, method, and timeout parameter. Values can be quoted for clarity. ```http GET /rest/Person/?$filter="lastName!=Jones"&$method=entityset&$timeout=600 ``` -------------------------------- ### SEND PACKETS Project Method Example Source: https://developer.4d.com/docs/18/Concepts/parameters This example demonstrates how a project method can accept a fixed time parameter followed by a variable number of text parameters using parameter indirection. ```4D //SEND PACKETS Project Method //SEND PACKETS ( Time ; Text { ; Text2... ; TextN } ) //SEND PACKETS ( docRef ; Data { ; Data2... ; DataN } ) C_TIME($1) C_TEXT(${2}) C_LONGINT($vlPacket) For($vlPacket;2;Count parameters) SEND PACKET($1;${$vlPacket}) End for ``` -------------------------------- ### Looping Through a Collection with Begin and End Parameters Source: https://developer.4d.com/docs/18/Concepts/looping This example illustrates using the begin and end parameters to control the iteration range of a collection. It demonstrates how to append elements to another collection based on specified start and end indices, including negative index calculations. ```4D C_COLLECTION($col;$col2) $col:=New collection("a";"b";"c";"d";"e") $col2:=New collection(1;2;3) C_TEXT($item) For each($item;$col;0;3) $col2.push($item) End for each //$col2=[1,2,3,"a","b","c"] For each($item;$col;-2;-1) $col2.push($item) End for each //$col2=[1,2,3,"a","b","c","d"] ``` -------------------------------- ### Line JSON Example with startPoint Source: https://developer.4d.com/docs/18/FormObjects/shapesOverview Defines a static line object for a 4D form, including its starting point and dashed style. The startPoint property is not visible in the Property List. ```json "myLine": { "type": "line", "left": 20, "top": 40, "width": 100, "height": 80, "startPoint": "topLeft", "strokeDashArray": "6 2" } ``` -------------------------------- ### Install Error-Handling Method Source: https://developer.4d.com/docs/18/Concepts/error-handling Installs a custom project method to handle errors in the current process. Call with an empty string to disable error catching. ```4D ON ERR CALL("IO_ERRORS") //Installs the error-handling method ON ERR CALL("") //gives back control to 4D ``` -------------------------------- ### Repeat...Until Loop Example Source: https://developer.4d.com/docs/18/Concepts/looping This example adds a record and then checks if the user wants to continue. Unlike While...End while, initialization of the condition is not required before the loop. ```4D Repeat ADD RECORD([aTable]) Until(OK=0) ``` -------------------------------- ### Example of Modifying a Customer Record Source: https://developer.4d.com/docs/18/Concepts/methods This code snippet demonstrates the steps to find a customer using query by example, set the input form, and modify the record. It is intended to be encapsulated within a project method for reuse. ```4D QUERY BY EXAMPLE([Customers]) FORM SET INPUT([Customers];"Data Entry") MODIFY RECORD([Customers]) ``` -------------------------------- ### Using 4D Commands with Parameters Source: https://developer.4d.com/docs/18/Concepts/quick-tour Demonstrates how to use 4D commands with parameters, which are passed in brackets and separated by semicolons. This example copies a document. ```4D COPY DOCUMENT("folder1\\name1";"folder2\\" ; "new") ``` -------------------------------- ### Infinite While Loop Example Source: https://developer.4d.com/docs/18/Concepts/looping This example demonstrates an infinite loop where the condition NeverStop is always TRUE. Use tracing facilities to manage such situations. ```4D NeverStop:=True While(NeverStop) End while ``` -------------------------------- ### Retrieve Company Data as Array Source: https://developer.4d.com/docs/18/REST/asArray This example demonstrates how to fetch company data using the $asArray query option to get the results in an array format. It includes filtering by name and limiting the number of results. ```APIDOC ## GET /rest/Company/ ### Description Returns the result of a query in an array (i.e. a collection) instead of a JSON object. ### Method GET ### Endpoint /rest/Company/ ### Query Parameters - **$filter** (string) - Optional - Filters the results based on a specified condition (e.g., "name begin a"). - **$top** (integer) - Optional - Limits the number of results returned (e.g., 3). - **$asArray** (boolean) - Optional - If set to true, the response will be formatted as an array of objects. Defaults to false. ### Request Example `GET /rest/Company/?$filter="name begin a"&$top=3&$asArray=true` ### Response #### Success Response (200) - The response will be a JSON array where each element is an object representing a company record. #### Response Example ```json [ { "__KEY": 15, "__STAMP": 0, "ID": 15, "name": "Alpha North Yellow", "creationDate": "!!0000-00-00!!", "revenues": 82000000, "extra": null, "comments": "", "__GlobalStamp": 0 }, { "__KEY": 34, "__STAMP": 0, "ID": 34, "name": "Astral Partner November", "creationDate": "!!0000-00-00!!", "revenues": 90000000, "extra": null, "comments": "", "__GlobalStamp": 0 }, { "__KEY": 47, "__STAMP": 0, "ID": 47, "name": "Audio Production Uniform", "creationDate": "!!0000-00-00!!", "revenues": 28000000, "extra": null, "comments": "", "__GlobalStamp": 0 } ] ``` ``` -------------------------------- ### Default JSON Response Example Source: https://developer.4d.com/docs/18/REST/asArray This example shows the same data in its default JSON format, which includes metadata like __entityModel, __COUNT, and __FIRST, with entities nested within an __ENTITIES array. ```JSON { "__entityModel": "Company", "__GlobalStamp": 50, "__COUNT": 52, "__FIRST": 0, "__ENTITIES": [ { "__KEY": "15", "__TIMESTAMP": "2018-03-28T14:38:07.434Z", "__STAMP": 0, "ID": 15, "name": "Alpha North Yellow", "creationDate": "0!0!0", "revenues": 82000000, "extra": null, "comments": "", "__GlobalStamp": 0, "employees": { "__deferred": { "uri": "/rest/Company(15)/employees?$expand=employees" } } }, { "__KEY": "34", "__TIMESTAMP": "2018-03-28T14:38:07.439Z", "__STAMP": 0, "ID": 34, "name": "Astral Partner November", "creationDate": "0!0!0", "revenues": 90000000, "extra": null, "comments": "", "__GlobalStamp": 0, "employees": { "__deferred": { "uri": "/rest/Company(34)/employees?$expand=employees" } } }, { "__KEY": "47", "__TIMESTAMP": "2018-03-28T14:38:07.443Z", "__STAMP": 0, "ID": 47, "name": "Audio Production Uniform", "creationDate": "0!0!0", "revenues": 28000000, "extra": null, "comments": "", "__GlobalStamp": 0, "employees": { "__deferred": { "uri": "/rest/Company(47)/employees?$expand=employees" } } } ], "__SENT": 3 } ``` -------------------------------- ### If Else End if Statement Example Source: https://developer.4d.com/docs/18/Concepts/branching Presents the equivalent logic of the 'Case of' example using nested 'If...Else...End if' statements. ```4D If(vResult=1) //Test if the number is 1 ALERT("One.") //If it is 1, display an alert Else If(vResult=2) //Test if the number is 2 ALERT("Two.") //If it is 2, display an alert Else If(vResult=3) //Test if the number is 3 ALERT("Three.") //If it is 3, display an alert Else //If it is not 1, 2, or 3, display an alert ALERT("It was not one, two, or three.") End if End if End if ``` -------------------------------- ### Using a 4D Plug-in Command Source: https://developer.4d.com/docs/18/Concepts/quick-tour Illustrates calling a command from a 4D plug-in. This example uses a hypothetical PDF plug-in to remove a page. ```4D PDF REMOVE PAGE(path;page) ``` -------------------------------- ### Enable 'Start a New Process' for Menu Command Source: https://developer.4d.com/docs/18/Menus/properties Control whether a menu command executes in a new process using the SET MENU ITEM PROPERTY command with the 'Start a New Process' property. ```4D SET MENU ITEM PROPERTY("MyMenuItem"; "Start a New Process"; "1") ``` -------------------------------- ### Retrieving all attributes from related entities (Company example) Source: https://developer.4d.com/docs/18/REST/attributes This example shows how to retrieve all attributes from the 'employees' related entities by using '$attributes=employees.*'. ```APIDOC ## GET /rest/Company(1)/?$attributes=employees.* ### Description Allows selecting all attributes from related entities. This example retrieves all attributes for the 'employees' relation of a Company entity. ### Method GET ### Endpoint /rest/Company(1)/?$attributes=employees.* ### Parameters #### Query Parameters - **$attributes** (string) - Required - Defines the path of attributes whose values you want to get for the related entity or entities. Use `*` to retrieve all attributes. ### Response #### Success Response (200) (Response structure will include all attributes for each employee) ### Response Example (Response will be similar to the previous example but include all fields for each employee) ``` -------------------------------- ### Example Usage of Capitalize_text Method Source: https://developer.4d.com/docs/18/Concepts/string Demonstrates how to call the Capitalize_text project method and display the result using an ALERT box. ```4D ALERT(Capitalize_text("hello, my name is jane doe and i'm running for president!")) ``` -------------------------------- ### Get Distinct Company Names Starting with 'a' Source: https://developer.4d.com/docs/18/REST/distinct Retrieves a list of unique company names that begin with the letter 'a'. This example demonstrates the basic usage of the $distinct parameter with a $filter. ```HTTP GET /rest/Company/name?$filter="name=a*"&$distinct=true ``` ```JSON [ "Adobe", "Apple" ] ``` -------------------------------- ### Declaring a Date Variable Source: https://developer.4d.com/docs/18/Concepts/quick-tour Shows how to formally create a typed variable using the C_XXX command. This example declares a variable of the date type. ```4D C_DATE(MyDate) //Date type for MyDate variable ``` -------------------------------- ### Calling Project Methods Source: https://developer.4d.com/docs/18/Concepts/identifiers Demonstrates how to call project methods. Method names can be used directly. Some commands expect method names as strings. ```4D If(New client) DELETE DUPLICATED VALUES APPLY TO SELECTION([Employees];INCREASE SALARIES) ``` ```4D //This command expects a method (function) or formula QUERY BY FORMULA([aTable];Special query) //This command expects a method (procedure) or statement APPLY TO SELECTION([Employees];INCREASE SALARIES) //But this command expects a method name ON EVENT CALL("HANDLE EVENTS") ``` -------------------------------- ### Skip to the 20th Entity Source: https://developer.4d.com/docs/18/REST/skip Use the $skip query option to start retrieving entities from a specific position in the collection. This example retrieves entities starting from the 20th. ```http GET /rest/Employee/$entityset/CB1BCC603DB0416D939B4ED379277F02?$skip=20 ``` -------------------------------- ### Line JSON Example with different startPoint Source: https://developer.4d.com/docs/18/FormObjects/shapesOverview Demonstrates an alternative configuration for a static line object in a 4D form, using a different startPoint and dashed line style. ```json "myLine": { "type": "line", "left": 20, "top": 40, "width": 100, "height": 80, "startPoint": "bottomLeft", "strokeDashArray": "6 2" } ``` -------------------------------- ### Accessing nested related attributes (Employee example) Source: https://developer.4d.com/docs/18/REST/attributes This example demonstrates how to access attributes of a nested related entity, such as getting the 'lastname' of employees related to an employer. ```APIDOC ## GET /rest/Employee(1)?$attributes=employer.employees.lastname ### Description Allows accessing attributes of nested related entities. This example retrieves the 'lastname' of all 'employees' related to the 'employer' of a given Employee. ### Method GET ### Endpoint /rest/Employee(1)?$attributes=employer.employees.lastname ### Parameters #### Query Parameters - **$attributes** (string) - Required - Defines the path of attributes whose values you want to get for nested related entities. Use dot notation to traverse relations. ### Response #### Success Response (200) (Response structure will show the employer, and within it, a list of employees with their lastnames) ### Response Example (Response will show the employer object, and nested within it, an 'employees' array containing objects with a 'lastname' field for each employee.) ``` -------------------------------- ### Display "Hello, World!" Message Source: https://developer.4d.com/docs/18/Concepts/quick-tour Use the ALERT command to display a platform-standard alert dialog box with a message. This is the simplest way to show a message to the user. ```4D ALERT("Hello, World!") ``` -------------------------------- ### Project Methods with Parameters and Return Values Source: https://developer.4d.com/docs/18/Concepts/identifiers Illustrates how project methods can accept parameters passed in parentheses and separated by semicolons. Local variables $1, $2, etc., are used for parameters, and $0 is used for the return value in functions. ```4D //Within DROP SPACES $1 is a pointer to the field [People]Name DROP SPACES(->[People]Name) ``` ```4D //Within Calc creator: //- $1 is numeric and equal to 1 //- $2 is numeric and equal to 5 //- $3 is text or string and equal to "Nice" //- The result value is assigned to $0 $vsResult:=Calc creator(1;5;"Nice") ``` ```4D //Within Dump: //- The three parameters are text or string //- They can be addressed as $1, $2 or $3 //- They can also be addressed as, for instance, ${$vlParam} where $vlParam is 1, 2 or 3 //- The result value is assigned to $0 vtClone:=Dump("is";"the";"it") ``` -------------------------------- ### Declaring Generic Parameters Source: https://developer.4d.com/docs/18/Concepts/parameters Example of declaring generic parameters using a compiler directive to specify the data type for a range of parameters starting from a specific index. ```4D C_LONGINT(${4}) ``` -------------------------------- ### Example Query with $querypath (No Entities Found) Source: https://developer.4d.com/docs/18/REST/querypath Demonstrates how to use the $querypath parameter when no entities are found. The response shows the query path taken by 4D Server. ```http GET /rest/Employee/$filter="employer.name=acme AND lastName=Jones"&$querypath=true ``` ```http GET /rest/$querypath ``` -------------------------------- ### Apply Yellow Letters to Text Objects with Text Attribute Starting With 'Hello' Source: https://developer.4d.com/docs/18/FormEditor/stylesheets Use the [attribute|="value"] selector to match objects where an attribute's value begins with a specific string. This example targets 'text' type objects where the 'text' attribute starts with 'Hello'. ```css text[text|=Hello] { stroke: yellow; } ``` -------------------------------- ### Retrieve Company Data as Array Source: https://developer.4d.com/docs/18/REST/asArray Use the $asArray=true parameter in your REST request to get the response in an array format. This example filters companies by name and limits the results. ```HTTP GET /rest/Company/?$filter="name begin a"&$top=3&$asArray=true ``` -------------------------------- ### Example Query with $querypath (Entities Found) Source: https://developer.4d.com/docs/18/REST/querypath Shows a query using $querypath where at least one entity is found. The subsequent $querypath call will reflect the executed path. ```http GET /rest/Employee/$filter="employer.name=a* AND lastName!=smith"&$querypath=true ``` ```http GET /rest/$querypath ``` -------------------------------- ### Dataclass Employee Information Response Source: https://developer.4d.com/docs/18/REST/catalog This is an example JSON response for a GET request to retrieve information about the 'Employee' dataclass. It details the dataclass's properties, attributes, and primary key. ```JSON { name: "Employee", className: "Employee", collectionName: "EmployeeCollection", scope: "public", dataURI: "http://127.0.0.1:8081/rest/Employee", defaultTopSize: 20, extraProperties: { panelColor: "#76923C", __CDATA: "\n\n\t\t\n", panel: { isOpen: "true", pathVisible: "true", __CDATA: "\n\n\t\t\t\n", position: { X: "394", Y: "42" } } }, attributes: [ { name: "ID", kind: "storage", scope: "public", indexed: true, type: "long", identifying: true }, { name: "firstName", kind: "storage", scope: "public", type: "string" }, { name: "lastName", kind: "storage", scope: "public", type: "string" }, { name: "fullName", kind: "calculated", scope: "public", type: "string", readOnly: true }, { name: "salary", kind: "storage", scope: "public", type: "number", defaultFormat: { format: "$###,###.00" } }, { name: "photo", kind: "storage", scope: "public", type: "image" }, { name: "employer", kind: "relatedEntity", scope: "public", type: "Company", path: "Company" }, { name: "employerName", kind: "alias", scope: "public", type: "string", path: "employer.name", readOnly: true }, { name: "description", kind: "storage", scope: "public", type: "string", multiLine: true }, ], key: [ { name: "ID" } ] } ``` -------------------------------- ### Addressing Array Elements in 4D Source: https://developer.4d.com/docs/18/Concepts/identifiers Demonstrates how to access elements in interprocess, process, and local arrays using curly braces with a numeric index. The last example shows how to get the size of an array. ```4D //Addressing an element of an interprocess array If(<>asKeywords{1}="Stop") <>atSubjects{$vlElem}:=[Topics]Subject $viNextValue:=<>aiBigArray{Size of array(<>aiBigArray)} //Addressing an element of a process array If(asKeywords{1}="Stop") atSubjects{$vlElem}:=[Topics]Subject $viNextValue:=aiBigArray{Size of array(aiBigArray)} //Addressing an element of a local array If($asKeywords{1}="Stop") $atSubjects{$vlElem}:=[Topics]Subject $viNextValue:=$aiBigArray{Size of array($aiBigArray)} ``` -------------------------------- ### Retrieve Related Entities Source: https://developer.4d.com/docs/18/REST/method This example demonstrates how to retrieve related entities for a specific entity using a GET request. It shows how to expand the 'staff' relation attribute in the Company dataclass linked to the Employee dataclass. ```APIDOC ## GET /rest/Company(1)/staff ### Description Retrieves related entities for a specific company, expanding the 'staff' relation. ### Method GET ### Endpoint /rest/Company(1)/staff ### Query Parameters - **$expand** (string) - Optional - Specifies related entities to expand, e.g., 'staff'. - **$method** (string) - Optional - Set to 'subentityset' to retrieve a sub-entity set. - **$subOrderby** (string) - Optional - Specifies the order for sub-entity sets, e.g., 'lastName ASC'. ### Response #### Success Response (200) Returns a JSON object containing a list of related entities (employees in this case) with their details. #### Response Example ```json { "__ENTITYSET": "/rest/Employee/$entityset/FF625844008E430B9862E5FD41C741AB", "__entityModel": "Employee", "__COUNT": 2, "__SENT": 2, "__FIRST": 0, "__ENTITIES": [ { "__KEY": "4", "__STAMP": 1, "ID": 4, "firstName": "Linda", "lastName": "Jones", "birthday": "1970-10-05T14:23:00Z", "employer": { "__deferred": { "uri": "/rest/Company(1)", "__KEY": "1" } } }, { "__KEY": "1", "__STAMP": 3, "ID": 1, "firstName": "John", "lastName": "Smith", "birthday": "1985-11-01T15:23:00Z", "employer": { "__deferred": { "uri": "/rest/Company(1)", "__KEY": "1" } } } ] } ``` ``` -------------------------------- ### While Loop with User Confirmation Source: https://developer.4d.com/docs/18/Concepts/looping This example uses a While loop that continues as long as the user confirms adding a record. The OK system variable is controlled by user interaction and record saving. ```4D CONFIRM("Add a new record?") While(OK=1) ADD RECORD([aTable]) End while ``` -------------------------------- ### Get Employee Photo with Specific Version Source: https://developer.4d.com/docs/18/REST/version This example defines the image format as JPEG and passes the actual version number sent by the server to retrieve an employee's photo. The $version parameter helps bypass browser cache. ```http GET /rest/Employee(1)/photo?$imageformat=jpeg&$version=3&$expand=photo ``` -------------------------------- ### Calling ALERT with Optional Parameters Source: https://developer.4d.com/docs/18/Concepts/parameters Illustrates calling the ALERT command with one or two parameters, demonstrating the use of optional parameters. ```4D ALERT("Are you sure?";"Yes I am") //2 parameters ALERT("Time is over") //1 parameter ``` -------------------------------- ### Array Response Example Source: https://developer.4d.com/docs/18/REST/asArray This is an example of the response received when using the $asArray=true parameter. The data is structured as a JSON array of objects. ```JSON [ { "__KEY": 15, "__STAMP": 0, "ID": 15, "name": "Alpha North Yellow", "creationDate": "!!0000-00-00!!", "revenues": 82000000, "extra": null, "comments": "", "__GlobalStamp": 0 }, { "__KEY": 34, "__STAMP": 0, "ID": 34, "name": "Astral Partner November", "creationDate": "!!0000-00-00!!", "revenues": 90000000, "extra": null, "comments": "", "__GlobalStamp": 0 }, { "__KEY": 47, "__STAMP": 0, "ID": 47, "name": "Audio Production Uniform", "creationDate": "!!0000-00-00!!", "revenues": 28000000, "extra": null, "comments": "", "__GlobalStamp": 0 } ] ``` -------------------------------- ### Calling a Project Method with Multiple Parameters Source: https://developer.4d.com/docs/18/Concepts/parameters Shows how to call a custom project method named DO SOMETHING with three distinct parameters. ```4D DO SOMETHING(WithThis;AndThat;ThisWay) ``` -------------------------------- ### Retrieving all attributes from a related entity (Employee example) Source: https://developer.4d.com/docs/18/REST/attributes This example shows how to retrieve all attributes from the 'employer' related entity by using '$attributes=employer.*'. ```APIDOC ## GET /rest/Employee(1)?$attributes=employer.* ### Description Allows selecting all attributes from a related entity. This example retrieves all attributes for the 'employer' relation of an Employee entity. ### Method GET ### Endpoint /rest/Employee(1)?$attributes=employer.* ### Parameters #### Query Parameters - **$attributes** (string) - Required - Defines the path of attributes whose values you want to get for the related entity. Use `*` to retrieve all attributes. ### Response #### Success Response (200) (Response structure will include all attributes for the employer) ### Response Example (Response will be similar to the previous example but include all fields for the employer) ``` -------------------------------- ### Call Project Method with Return Value Source: https://developer.4d.com/docs/18/Concepts/quick-tour Demonstrates calling a project method ('Do_Something') and assigning its return value to a variable. The called method uses $1 for input and $0 for the return value. Ensure the 'Do_Something' method is defined in your project. ```4D $myText:="hello" $myText:=Do_Something($myText) //Call the Do_Something method ALERT($myText) //"HELLO" //Here the code of the method Do_Something $0:=Uppercase($1) ``` -------------------------------- ### Example JSON Result Structure Source: https://developer.4d.com/docs/18/REST/orderby This is an example of the JSON structure returned when querying entities, showing the __ENTITIES array which contains the sorted data. ```JSON { __entityModel: "Employee", __COUNT: 10, __SENT: 10, __FIRST: 0, __ENTITIES: [ { __KEY: "1", __STAMP: 1, firstName: "John", lastName: "Smith", salary: 90000 }, { __KEY: "2", __STAMP: 2, firstName: "Susan", lastName: "O'Leary", salary: 80000 }, // more entities ] } ``` -------------------------------- ### Using Collection Methods: Copy and Push Source: https://developer.4d.com/docs/18/Concepts/collection Demonstrates the usage of collection member functions like 'copy' for deep copying and 'push' for adding elements to a collection. ```4D $newCol:=$col.copy() //deep copy of $col to $newCol $col.push(10;100) //add 10 and 100 to the collection ``` -------------------------------- ### Using Predefined Constants Source: https://developer.4d.com/docs/18/Concepts/quick-tour Demonstrates the use of predefined constants to improve code readability. This example opens a document in read-only mode using the 'Read Mode' constant. ```4D vRef:=Open document("PassFile";"TEXT";Read Mode) // open doc in read only mode ``` -------------------------------- ### GET /$catalog/{dataClass} Source: https://developer.4d.com/docs/18/REST/catalog Returns information about a specific data class and its attributes. Use this endpoint to get details for a single data class. ```APIDOC ## GET /$catalog/{dataClass} ### Description Returns information about a specific data class and its attributes. Use this endpoint to get details for a single data class. ### Method GET ### Endpoint /rest/$catalog/{dataClass} ### Parameters #### Path Parameters - **dataClass** (string) - Required - The name of the data class for which to retrieve information. ### Response #### Success Response (200) - **name** (string) - Name of the data class. - **collectionName** (string) - Name of an entity selection on the data class. - **tableNumber** (number) - Table number in the 4D database. - **scope** (string) - Scope for the data class (e.g., "public"). - **dataURI** (string) - A URI to the data in the data class. - **attributes** (array) - An array of attribute objects associated with the data class. - **name** (string) - Name of the attribute. - **kind** (string) - The kind of attribute (e.g., "storage", "relatedEntities"). - **fieldPos** (number) - Field position in the data class. - **scope** (string) - Scope of the attribute (e.g., "public"). - **indexed** (boolean) - Indicates if the attribute is indexed. - **type** (string) - Data type of the attribute (e.g., "long", "string", "number"). - **identifying** (boolean) - Indicates if the attribute is part of the primary key. - **reversePath** (boolean) - Indicates if a reverse path exists for related entities. - **path** (string) - The path for related entities. - **key** (array) - An array of objects representing the primary key of the data class. - **name** (string) - The name of the key attribute. ``` -------------------------------- ### While Loop Equivalent for 100 Iterations Source: https://developer.4d.com/docs/18/Concepts/looping Demonstrates how to achieve the same result as a basic For loop using a While loop. Requires manual counter initialization and increment. ```4D $i:=1 //Initialize the counter While($i<=100) //Loop 100 times //Do something $i:=$i+1 //Need to increment the counter End while ``` -------------------------------- ### Example Response for Retrieving Related Entities Source: https://developer.4d.com/docs/18/REST/method This is an example of the JSON response structure when retrieving related entities, showing entity details and count information. ```JSON { "__ENTITYSET": "/rest/Employee/$entityset/FF625844008E430B9862E5FD41C741AB", "__entityModel": "Employee", "__COUNT": 2, "__SENT": 2, "__FIRST": 0, "__ENTITIES": [ { "__KEY": "4", "__STAMP": 1, "ID": 4, "firstName": "Linda", "lastName": "Jones", "birthday": "1970-10-05T14:23:00Z", "employer": { "__deferred": { "uri": "/rest/Company(1)", "__KEY": "1" } } }, { "__KEY": "1", "__STAMP": 3, "ID": 1, "firstName": "John", "lastName": "Smith", "birthday": "1985-11-01T15:23:00Z", "employer": { "__deferred": { "uri": "/rest/Company(1)", "__KEY": "1" } } } ] } ``` -------------------------------- ### Calling a Plug-In Command Source: https://developer.4d.com/docs/18/Concepts/identifiers Shows how to call a plug-in command using its name as defined by the plug-in. Plug-in command names can be up to 31 characters. ```4D $error:=SMTP_From($smtp_id;"henry@gmail.com") ``` -------------------------------- ### Example: User Input Validation Source: https://developer.4d.com/docs/18/Concepts/branching Demonstrates using If...Else...End if to process user input, querying a database or alerting the user. ```4D // Ask the user to enter a name $Find:=Request(Type a name) If(OK=1) QUERY([People];[People]LastName=$Find) Else ALERT("You did not enter a name.") End if ``` -------------------------------- ### Pointer Creation and Dereferencing Source: https://developer.4d.com/docs/18/Concepts/quick-tour Shows how to create a pointer to a variable ('MyPointer') and then dereference it to access the variable's value using 'ALERT()'. This demonstrates pointer usage. ```4D MyVar:="Hello" MyPointer:=->MyVar ALERT(MyPointer->) ``` -------------------------------- ### Selecting specific attributes from a related entity (Employee example) Source: https://developer.4d.com/docs/18/REST/attributes This example shows how to retrieve a specific attribute ('name') from a single related entity ('employer') of an Employee. ```APIDOC ## GET /rest/Employee(1)?$attributes=employer.name ### Description Allows selecting specific attributes from a related entity. This example retrieves the 'name' attribute from the 'employer' relation of an Employee entity. ### Method GET ### Endpoint /rest/Employee(1)?$attributes=employer.name ### Parameters #### Query Parameters - **$attributes** (string) - Required - Defines the path of attributes whose values you want to get for the related entity. For a single related entity, use the format `relatedEntity.attributePath`. ### Response #### Success Response (200) - **__entityModel** (string) - The entity model name. - **__KEY** (string) - The primary key of the entity. - **__TIMESTAMP** (string) - The timestamp of the entity. - **__STAMP** (integer) - The stamp of the entity. - **employer** (object) - An object containing information about the related employer. - **__KEY** (string) - The primary key of the employer. - **__TIMESTAMP** (string) - The timestamp of the employer. - **__STAMP** (integer) - The stamp of the employer. - **name** (string) - The name attribute of the employer. ### Response Example ```json { "__entityModel": "Employee", "__KEY": "1", "__TIMESTAMP": "2019-12-01T20:18:26.046Z", "__STAMP": 5, "employer": { "__KEY": "1", "__TIMESTAMP": "2018-04-25T14:41:16.237Z", "__STAMP": 0, "name": "Adobe" } } ``` ``` -------------------------------- ### Accessing Host Database Tables from a Component Source: https://developer.4d.com/docs/18/Concepts/components Demonstrates how a component can call a host database method to create a record and insert data into a host database table using pointers. ```4D // calling a component method methCreateRec(->[PEOPLE];->[PEOPLE]Name;"Julie Andrews") ``` ```4D C_POINTER($1) //Pointer on a table in host database C_POINTER($2) //Pointer on a field in host database C_TEXT($3) // Value to insert $tablepointer:=$1 $fieldpointer:=$2 CREATE RECORD($tablepointer->) $fieldpointer->:=$3 SAVE RECORD($tablepointer->) ``` -------------------------------- ### Get Window Rect in SDI Source: https://developer.4d.com/docs/18/Menus/sdi When -1 is passed as the window parameter to the `GET WINDOW RECT` command in SDI mode, it returns 0;0;0;0. ```4D // When -1 is passed in window parameter, the command returns 0;0;0;0 GET WINDOW RECT(-1) ``` -------------------------------- ### Selecting multiple specific attributes from related entities (Company example) Source: https://developer.4d.com/docs/18/REST/attributes This example demonstrates retrieving multiple specific attributes ('lastname', 'jobname') from the 'employees' related entities. ```APIDOC ## GET /rest/Company(1)/?$attributes=employees.lastname,employees.jobname ### Description Allows selecting multiple specific attributes from related entities. This example retrieves 'lastname' and 'jobname' for the 'employees' relation of a Company entity. ### Method GET ### Endpoint /rest/Company(1)/?$attributes=employees.lastname,employees.jobname ### Parameters #### Query Parameters - **$attributes** (string) - Required - Defines the path of attributes whose values you want to get for the related entity or entities. Separate multiple attribute paths with a comma. ### Response #### Success Response (200) (Response structure will include 'lastname' and 'jobname' for each employee) ### Response Example (Response will be similar to the first example, but only include 'lastname' and 'jobname' for each employee) ``` -------------------------------- ### Define Row Height Array Example Source: https://developer.4d.com/docs/18/FormObjects/propertiesCoordinatesAndSizing Example of how to define and populate a row height array in 4D. This array can then be associated with a list box to control individual row heights. ```4D ARRAY LONGINT(RowHeights;20) RowHeights{5}:=3 ``` -------------------------------- ### Address and Initialize Individual Bytes of a BLOB in 4D Source: https://developer.4d.com/docs/18/Concepts/blob Demonstrates how to set the size of a BLOB and then iterate through its bytes to initialize each one to zero using individual byte addressing. ```4D ` Declare a variable of type BLOB C_BLOB(vBlob) ` Set the size of the BLOB to 256 bytes SET BLOB SIZE(vBlob;256) ` The loop below initializes the 256 bytes of the BLOB to zero For(vByte;0;BLOB size(vBlob)-1) vBlob{vByte}:=0 End for ``` -------------------------------- ### Selecting specific attributes from related entities (Company example) Source: https://developer.4d.com/docs/18/REST/attributes This example demonstrates how to use the $attributes parameter to retrieve specific attributes (lastname) from a related entity (employees) of a Company. ```APIDOC ## GET /rest/Company(1)/?$attributes=employees.lastname ### Description Allows selecting the related attribute(s) to get from the dataclass. This example shows retrieving the 'lastname' attribute from the 'employees' relation of a Company entity. ### Method GET ### Endpoint /rest/Company(1)/?$attributes=employees.lastname ### Parameters #### Query Parameters - **$attributes** (string) - Required - Defines the path of attributes whose values you want to get for the related entity or entities. For related entities, use the format `relatedEntities.attributePath1, relatedEntities.attributePath2, ...`. ### Response #### Success Response (200) - **__entityModel** (string) - The entity model name. - **__KEY** (string) - The primary key of the entity. - **__TIMESTAMP** (string) - The timestamp of the entity. - **__STAMP** (integer) - The stamp of the entity. - **employees** (object) - An object containing information about related employees. - **__ENTITYSET** (string) - The entity set URL for the related entities. - **__GlobalStamp** (integer) - The global stamp for the related entities. - **__COUNT** (integer) - The total count of related entities. - **__FIRST** (integer) - The index of the first related entity. - **__ENTITIES** (array) - An array of related entity objects. - **__KEY** (string) - The primary key of the related entity. - **__TIMESTAMP** (string) - The timestamp of the related entity. - **__STAMP** (integer) - The stamp of the related entity. - **lastname** (string) - The lastname attribute of the employee. ### Response Example ```json { "__entityModel": "Company", "__KEY": "1", "__TIMESTAMP": "2018-04-25T14:41:16.237Z", "__STAMP": 2, "employees": { "__ENTITYSET": "/rest/Company(1)/employees?$expand=employees", "__GlobalStamp": 50, "__COUNT": 135, "__FIRST": 0, "__ENTITIES": [ { "__KEY": "1", "__TIMESTAMP": "2019-12-01T20:18:26.046Z", "__STAMP": 5, "lastname": "ESSEAL" }, { "__KEY": "2", "__TIMESTAMP": "2019-12-04T10:58:42.542Z", "__STAMP": 6, "lastname": "JONES" }, ... } } ``` ``` -------------------------------- ### Method DO SOMETHING receiving Text Parameters Source: https://developer.4d.com/docs/18/Concepts/parameters Illustrates the internal code of a method that accepts three text parameters, assigning them to local variables $1, $2, and $3, and then displays them using ALERT. ```4D //Code of the method DO SOMETHING //Assuming all parameters are of the text type C_TEXT($1;$2;$3) ALERT("I received "+$1+" and "+$2+" and also "+$3) //$1 contains the WithThis parameter //$2 contains the AndThat parameter //$3 contains the ThisWay parameter ``` -------------------------------- ### Using Named Selections in 4D Source: https://developer.4d.com/docs/18/Concepts/identifiers Demonstrates how to use named selections in 4D. The first example shows an interprocess named selection, and the second shows a standard process named selection. ```4D //Interprocess Named Selection USE NAMED SELECTION([Customers];"<>ByZipcode") ``` ```4D //Process Named Selection USE NAMED SELECTION([Customers];"<>ByZipcode") ``` -------------------------------- ### Help Button JSON Configuration Source: https://developer.4d.com/docs/18/FormObjects/buttonOverview Configuration for a button with the Help style, typically displayed as a question mark in a circle. This style has limitations on supported properties. ```json "myButton": { "type": "button", "style":"help", "text": "OK", "dropping": "custom", "left": 60, "top": 160, "width": 100, "height": 20 } ``` -------------------------------- ### Call 4D Method from Web Area Source: https://developer.4d.com/docs/18/FormObjects/webAreaOverview Demonstrates calling a 4D method named HelloWorld from a Web area using the $4d JavaScript object. ```javascript $4d.HelloWorld(); ``` -------------------------------- ### Example REST Request to Filter Data Source: https://developer.4d.com/docs/18/REST/configuration This example demonstrates how to filter data from an Employee table using a REST request. Ensure the 4D REST server is enabled and the Employee table is exposed. ```http http://127.0.0.1:8044/rest/Employee/?$filter="salary>10000" ``` -------------------------------- ### Managing Sets in 4D Source: https://developer.4d.com/docs/18/Concepts/identifiers Demonstrates the usage of interprocess, process, and client sets. Sets are managed on the Server but can be worked with locally on the Client using client sets. ```4D //Interprocess sets USE SET("<>Deleted Records") CREATE SET([Customers];"<>Customer Orders") If(Records in set("<>Selection"+String($i))>0) ``` ```4D //Process sets USE SET("Deleted Records") CREATE SET([Customers];"Customer Orders") If(Records in set("<>Selection"+String($i))>0) ``` ```4D //Client sets USE SET("$Deleted Records") CREATE SET([Customers];"$Customer Orders") If(Records in set("$Selection"+String($i))>0) ``` -------------------------------- ### Chaining Collection Methods: Push and Sort Source: https://developer.4d.com/docs/18/Concepts/collection Shows how collection methods can be chained, such as using 'push' to add elements and then 'sort' to order them. Some methods return the modified collection, allowing sequential calls. ```4D $col:=New collection(5;20) $col2:=$col.push(10;100).sort() //$col2=[5,10,20,100] ```