### Example Login URL
Source: https://developer.4d.com/docs/19/WebServer/gettingStarted
This example demonstrates how to call the login method using a URL. It shows the format for passing userId and password as query parameters. It is noted that this method is for simplicity and POST requests via a web form are recommended for more realistic scenarios.
```url
http://localhost/4DACTION/login/?userID=john@4d.com&password=123
```
--------------------------------
### User Creation Example
Source: https://developer.4d.com/docs/WebServer/gettingStarted
Example of how to create a new user record in the '_WebUsers' table using ORDA and the REST server.
```APIDOC
## POST /rest/WebUsers
### Description
Creates a new user record in the '_WebUsers' table. This endpoint is part of the user authentication scenario.
### Method
POST
### Endpoint
/rest/WebUsers
### Parameters
#### Request Body
- **firstName** (string) - Required - The first name of the user.
- **lastName** (string) - Required - The last name of the user.
- **password** (string) - Required - The hashed password for the user.
- **userId** (string) - Required - The unique identifier (e.g., email) for the user.
### Request Example
```json
{
"firstName": "John",
"lastName": "Doe",
"password": "Generate password hash(\"123\")",
"userId": "john@4d.com"
}
```
### Response
#### Success Response (200)
Returns the created user entity, including its unique key and timestamp.
#### Response Example
```json
{
"__DATACLASS": "WebUsers",
"__entityModel": "WebUsers",
"__KEY": "5",
"__TIMESTAMP": "2023-10-27T10:00:00.000Z",
"__STAMP": 1,
"firstName": "John",
"lastName": "Doe",
"password": "hashed_password_here",
"userId": "john@4d.com"
}
```
```
--------------------------------
### Create User
Source: https://developer.4d.com/docs/19/WebServer/gettingStarted
Demonstrates how to create a new user record in the 'WebUsers' table, including setting a password hash.
```APIDOC
## POST /WebUsers
### Description
Creates a new user in the WebUsers table. Assumes the 'WebUsers' table exists with fields like firstName, lastName, password, and userId.
### Method
POST
### Endpoint
/rest/WebUsers
### Parameters
#### Request Body
- **firstName** (string) - Required - The first name of the user.
- **lastName** (string) - Required - The last name of the user.
- **password** (string) - Required - The hashed password for the user.
- **userId** (string) - Required - The unique identifier for the user (e.g., email).
### Request Example
```javascript
// Assuming 'ds' is your datastore object and 'Generate password hash' is a server-side function
var $webUser : cs.WebUsersEntity;
$webUser := ds.WebUsers.new();
$webUser.firstName := "John";
$webUser.lastName := "Doe";
// The password would typically be generated securely on the server or passed from a secure client input
$webUser.password := Generate password hash("123"); // Example password hashing
$webUser.userId := "john@4d.com";
$webUser.save();
```
```
--------------------------------
### Testing 4D Login via URL
Source: https://developer.4d.com/docs/WebServer/gettingStarted
This is an example URL to test the 4D login method directly in a browser. It demonstrates how to pass user credentials as query parameters. For production, using POST requests with web forms is recommended.
```URL
http://localhost/4DACTION/login/?userID=john@4d.com&password=123
```
--------------------------------
### Send 'Hello World' Response in 4D
Source: https://developer.4d.com/docs/19/WebServer/gettingStarted
This 4D code snippet demonstrates how to handle incoming web requests and send a 'Hello World!' text response to the browser when a specific URL is accessed. It uses the On Web Connection database method to process requests.
```4D
Case of
: ($1="/hello")
WEB SEND TEXT("Hello World!")
Else
// Error 404 for example
End case
```
--------------------------------
### 4D Position Command Examples
Source: https://developer.4d.com/docs/commands/position
Demonstrates various uses of the Position command, including finding substrings, specifying start positions, and handling case insensitivity. It shows how to get the starting position and length of found substrings.
```4D
vlResult:=Position("ll";"Willow") // vlResult gets 3
vlResult:=Position(vtText1;vtText2) // Returns first occurrence of vtText1 in vtText2
vlResult:=Position("day";"Today is the first day";1) // vlResult gets 3
vlResult:=Position("day";"Today is the first day";4) // vlResult gets 20
vlResult:=Position("DAY";"Today is the first day";1;*) // vlResult gets 0
vlResult:=Position("œ";"Bœuf";1;$length) // vlResult =2, $length = 1
```
--------------------------------
### Get Catalog of Exposed Dataclasses
Source: https://developer.4d.com/docs/19/WebServer/gettingStarted
Retrieves a list of all dataclasses exposed as REST resources. This allows you to discover available data endpoints.
```APIDOC
## GET $catalog
### Description
Retrieves the catalog of exposed data classes and their URIs.
### Method
GET
### Endpoint
/rest/$catalog
### Response
#### Success Response (200)
- **dataClasses** (array) - A list of data class objects, each containing 'name' and 'uri'.
### Response Example
```json
{
"__UNIQID": "3F1B6ACFFE12B64493629AD76011922D",
"dataClasses": [
{
"name": "Friends",
"uri": "/rest/$catalog/Friends",
"dataURI": "/rest/Friends"
}
]
}
```
```
--------------------------------
### Create User Record (4D)
Source: https://developer.4d.com/docs/19/WebServer/gettingStarted
This snippet demonstrates how to create a new user record in a 'WebUsers' table using 4D's ORDA. It includes setting user details like first name, last name, user ID, and a hashed password.
```4d
var $webUser : cs.WebUsersEntity
$webUser:=ds.WebUsers.new()
$webUser.firstName:="John"
$webUser.lastName:="Doe"
// the password would be entered by the user
$webUser.password:=Generate password hash("123")
$webUser.userId:="john@4d.com"
$webUser.save()
```
--------------------------------
### 4D Login Method for User Authentication
Source: https://developer.4d.com/docs/19/WebServer/gettingStarted
This 4D code snippet demonstrates how to create a login method to authenticate users. It retrieves userId and password from the web request, queries the WebUsers table, verifies the password hash, and sets the user session if credentials are valid. It handles both successful logins and incorrect credentials.
```4d
var $indexUserId; $indexPassword : Integer
var $userId; $password : Text
var $user; $info : Object
ARRAY TEXT($anames; 0)
ARRAY TEXT($avalues; 0)
// get values sent in the header of the request
WEB GET VARIABLES($anames; $avalues)
// look for header login fields
$indexUserId:=Find in array($anames; "userId")
$userId:=$avalues{$indexUserId}
$indexPassword:=Find in array($anames; "password")
$password:=$avalues{$indexPassword}
//look for a user with the entered name in the users table
$user:=ds.WebUsers.query("userId = :1"; $userId).first()
If ($user#Null) //a user was found
//check the password
If (Verify password hash($password; $user.password))
//password ok, fill the session
$info:=New object()
$info.userName:=$user.firstName+" "+$user.lastName
Session.setPrivileges($info)
//You can use the user session to store any information
WEB SEND TEXT("Welcome "+Session.userName)
Else
WEB SEND TEXT("Wrong user name or password.")
End if
Else
WEB SEND TEXT("Wrong user name or password.")
End if
```
--------------------------------
### Start and Stop Web Server (4D)
Source: https://developer.4d.com/docs/20/WebServer/webServerObject
Provides examples of using the start() and stop() functions of a 4D.WebServer object to control the web server's lifecycle. It shows how to start with default settings or custom configurations.
```4D
var $status : Object
//to start a web server with default settings
$status:=webServer.start()
//to start the web server with custom settings
// $settings object contains web server properties
webServer.start($settings)
//to stop the web server
$status:=webServer.stop()
```
--------------------------------
### Basic Error Handling Setup in 4D
Source: https://developer.4d.com/docs/19/Concepts/error-handling
A concise example showing the basic steps for setting up error handling in 4D: installing an error-handling method, executing code that might cause errors, and then returning control to 4D by uninstalling the method.
```4D
//installing the error handling method
ON ERR CALL("errorMethod")
//... executing code
ON ERR CALL("") //giving control back to 4D
```
--------------------------------
### Create Web User
Source: https://developer.4d.com/docs/20-R9/WebServer/gettingStarted
Creates a new user in the _WebUsers_ table with provided details.
```APIDOC
## Create User (Internal Operation)
### Description
This section describes the internal process of creating a user record in the `WebUsers` table. It involves instantiating a new entity, populating its fields (including a hashed password), and saving it to the datastore.
### Method
Internal (simulated via code example)
### Endpoint
N/A (This is an internal operation described by code)
### Parameters
None (Operates on internal data structures)
### Request Example
None
### Response
None (This is an internal operation; success is indicated by the save() method completion)
### Code Example
```javascript
var $webUser : cs.WebUsersEntity
$webUser:=ds.WebUsers.new()
$webUser.firstName:="John"
$webUser.lastName:="Doe"
// the password would be entered by the user
$webUser.password:=Generate password hash("123")
$webUser.userId:="john@4d.com"
$webUser.save()
```
```
--------------------------------
### Expose Data via REST Server (4D)
Source: https://developer.4d.com/docs/19/WebServer/gettingStarted
This snippet illustrates how to expose data classes as a REST server in 4D. It shows the URL to access the catalog and retrieve entities from a 'Friends' dataclass. The server returns data in JSON format.
```bash
http://localhost/rest/$catalog
```
```json
{
"__UNIQID": "3F1B6ACFFE12B64493629AD76011922D",
"dataClasses": [
{
"name": "Friends",
"uri": "/rest/$catalog/Friends",
"dataURI": "/rest/Friends"
}
]
}
```
```bash
http://localhost/rest/Friends
```
```json
{
"__DATACLASS": "Friends",
"__entityModel": "Friends",
"__GlobalStamp": 0,
"__COUNT": 4,
"__FIRST": 0,
"__ENTITIES": [
{
"__KEY": "1",
"__TIMESTAMP": "2020-10-27T14:29:01.914Z",
"__STAMP": 1,
"ID": 1,
"lastName": "Smith",
"firstName": "John"
},
{
"__KEY": "2",
"__TIMESTAMP": "2020-10-27T14:29:16.035Z",
"__STAMP": 1,
"ID": 2,
"lastName": "Brown",
"firstName": "Danny"
},
{
"__KEY": "3",
"__TIMESTAMP": "2020-10-27T14:29:43.945Z",
"__STAMP": 1,
"ID": 3,
"lastName": "Purple",
"firstName": "Mark"
},
{
"__KEY": "4",
"__TIMESTAMP": "2020-10-27T14:34:58.457Z",
"__STAMP": 1,
"ID": 4,
"lastName": "Dupont",
"firstName": "Jenny"
}
],
"__SENT": 4
}
```
--------------------------------
### Start 4D Server with WebAdmin Arguments
Source: https://developer.4d.com/docs/20-R9/Admin/webAdmin
This command line example demonstrates how to start a 4D Server application in headless mode with specific WebAdmin configurations. It includes setting a custom access key, enabling auto-start for WebAdmin, and specifying a settings file.
```command-line
"%HOMEPATH%\Desktop\4D Server.exe" MyApp.4DLink --webadmin-access-key
"my Fabulous AccessKey" --webadmin-auto-start true
--webadmin-store-settings
```
--------------------------------
### 4D New Process Command Usage Example
Source: https://developer.4d.com/docs/20-R9/commands/new-process
An example demonstrating how to use the New process command to start a new process, including setting the method, stack size, and name. This is a common pattern for process creation.
```4D
Dim myProcessNb as Integer
myProcessNb := New process("MyProcessMethod"; 0; "MyProcessName")
If myProcessNb = 0
ALERT("Failed to create process.")
Else
ALERT("Process created successfully. Process number: " + Text(myProcessNb))
End if
```
--------------------------------
### Display Database Records using 4D SHTML Template
Source: https://developer.4d.com/docs/19/WebServer/gettingStarted
This HTML snippet shows how to use 4D's server-side include directives within an .shtml file to dynamically display data from a database table. It iterates through records and outputs specific fields.
```html
```
--------------------------------
### Get table rows from a specific starting row (4D)
Source: https://developer.4d.com/docs/20-R9/WritePro/commands/wp-table-get-rows
This example shows how to retrieve all rows from a specified starting row to the end of a 4D Write Pro table. It utilizes 'WP Table get rows' with a starting row number and 'MAXLONG' to indicate fetching until the last row.
```4d
WP Table get rows(tableRef;10;MAXLONG)
```
--------------------------------
### Get Entities from a Dataclass
Source: https://developer.4d.com/docs/19/WebServer/gettingStarted
Retrieves all entities (data records) from a specified dataclass. This is useful for fetching lists of data.
```APIDOC
## GET /Friends
### Description
Retrieves all entities from the 'Friends' dataclass.
### Method
GET
### Endpoint
/rest/Friends
### Response
#### Success Response (200)
- **__DATACLASS** (string) - The name of the dataclass.
- **__entityModel** (string) - The entity model name.
- **__GlobalStamp** (integer) - Global stamp information.
- **__COUNT** (integer) - The total number of entities returned.
- **__FIRST** (integer) - Index of the first entity returned.
- **__ENTITIES** (array) - An array of entity objects, each containing key, timestamp, stamp, and data fields like ID, lastName, firstName.
- **__SENT** (integer) - The number of entities sent in the response.
### Response Example
```json
{
"__DATACLASS": "Friends",
"__entityModel": "Friends",
"__GlobalStamp": 0,
"__COUNT": 4,
"__FIRST": 0,
"__ENTITIES": [
{
"__KEY": "1",
"__TIMESTAMP": "2020-10-27T14:29:01.914Z",
"__STAMP": 1,
"ID": 1,
"lastName": "Smith",
"firstName": "John"
},
{
"__KEY": "2",
"__TIMESTAMP": "2020-10-27T14:29:16.035Z",
"__STAMP": 1,
"ID": 2,
"lastName": "Brown",
"firstName": "Danny"
},
{
"__KEY": "3",
"__TIMESTAMP": "2020-10-27T14:29:43.945Z",
"__STAMP": 1,
"ID": 3,
"lastName": "Purple",
"firstName": "Mark"
},
{
"__KEY": "4",
"__TIMESTAMP": "2020-10-27T14:34:58.457Z",
"__STAMP": 1,
"ID": 4,
"lastName": "Dupont",
"firstName": "Jenny"
}
],
"__SENT": 4
}
```
```
--------------------------------
### Abordando un área 4D View Pro
Source: https://developer.4d.com/docs/es/20-R9/ViewPro/getting-started
Explains how to address a 4D View Pro area, focusing on the `vpAreaName` parameter and the `On VP Ready` event.
```APIDOC
## Addressing a 4D View Pro Area
### Description
This section details how to interact with a 4D View Pro area, which manages various objects and elements. It highlights that the `vpAreaName` parameter, representing the name of the 4D View Pro form object, is necessary for most 4D View Pro commands. An example is provided for setting the total number of columns using `VP SET COLUMN COUNT`. It also reiterates the critical requirement to execute area-related 4D View Pro code within the `On VP Ready` form event, which is triggered after the area is fully loaded, to prevent errors.
### Example
```
VP SET COLUMN COUNT("myVpArea";5)
```
### Important Note
All 4D View Pro code that manipulates the area should be executed within the `On VP Ready` form event.
```
--------------------------------
### 4D Starting a Transaction and Getting Invoice Number
Source: https://developer.4d.com/docs/ja/Develop-legacy/transactions
Illustrates the process of starting a transaction, creating a new invoice record, and obtaining a new invoice number using a separate method.
```4D
//Standard method that creates an invoice
START TRANSACTION
...
CREATE RECORD([Invoices])
//call the method to get an available number
[Invoices]InvoiceID:=GetInvoiceNum
...
SAVE RECORD([Invoices])
VALIDATE TRANSACTION
```
--------------------------------
### Enviar 'Hello World' com 4D
Source: https://developer.4d.com/docs/pt/20/WebServer/gettingStarted
Este código é executado no método banco de dados 'On Web Connection' do 4D. Ele verifica a URL solicitada e, se for '/hello', envia o texto 'Hello World!' para o navegador.
```4d
Case of
: ($1="/hello")
WEB SEND TEXT("Hello World!")
Else
// Erro 404 por exemplo
End case
```
--------------------------------
### Starting the 4D Web Server
Source: https://developer.4d.com/docs/20/WebServer/webServerAdmin
Provides methods for starting the 4D Web Server, including menu commands, automatic startup configuration, and programmatic control.
```APIDOC
## Starting the 4D Web Server
### Description
Initiates the 4D Web Server. Requires a '4D Web Application' license.
### Methods
- **Menu Command:**
- 4D: `Run > Start Web Server`
- 4D Server: `Start HTTP server` button on the HTTP Server page
- **Automatic Startup:** Enable 'Launch Web Server at Startup' on the `Web/Configuration` page of Settings.
- **Programmatic:** Call `webServer.start()` function or use the `WEB START SERVER` command.
### Notes
- The web server of a component can be started by calling `webServer.start()` on the component's web server object.
- Relaunching the 4D application is not required to start or stop the web server.
```
--------------------------------
### Retrieve Related Entities
Source: https://developer.4d.com/docs/20-R9/REST/method
This endpoint allows you to retrieve related entities for a specific entity. For example, to get the 'staff' related to a 'Company' entity, you can use the provided REST request.
```APIDOC
## GET /rest/Company/{id}/staff
### Description
Retrieves a list of related entities (e.g., staff) for a given company entity, with options for expanding related data, specifying the method, and ordering the results.
### Method
GET
### Endpoint
`/rest/Company/{id}/staff`
### Parameters
#### Query Parameters
- **$expand** (string) - Optional - Specifies related entities to expand in the response. Example: `staff`
- **$method** (string) - Optional - Specifies the method for the request. Example: `subentityset`
- **$subOrderby** (string) - Optional - Specifies the order of the results. Example: `lastName ASC`
### Request Example
`GET /rest/Company(1)/staff?$expand=staff&$method=subentityset&$subOrderby=lastName ASC`
### Response
#### Success Response (200)
Returns a JSON object containing the related entities, including details like `__KEY`, `__STAMP`, `ID`, `firstName`, `lastName`, `birthday`, and nested `employer` information.
#### 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"
}
}
}
]
}
```
```
--------------------------------
### Configure Web Session Cookie Path
Source: https://developer.4d.com/docs/commands/web-set-option
Sets or gets the path for session cookies. This allows controlling which requests the client sends cookies with, for example, restricting them to requests starting with a specific path.
```4d
WEB SET OPTION(Web session cookie path; "/4DACTION")
WEB GET OPTION(Web session cookie path)
```
--------------------------------
### Utilizando los comandos de 4D View Pro
Source: https://developer.4d.com/docs/es/20-R9/ViewPro/getting-started
Explains how to use 4D View Pro commands within the 4D code editor and how to access the command list via the Explorer. It highlights the importance of the `vpAreaName` parameter and the `On VP Ready` form event.
```APIDOC
## Using 4D View Pro Commands
### Description
Details how 4D View Pro commands can be utilized within the 4D code editor, similar to standard 4D language commands. It guides users on accessing the command list from the Explorer under 'Component Methods'. Crucially, it emphasizes that most commands require the `vpAreaName` parameter, which is the name of the 4D View Pro form object. It also stresses that any 4D View Pro code manipulating the area must be executed within the `On VP Ready` form event to avoid errors.
### Key Points
- **Command Execution:** Use within the 4D code editor.
- **Command Access:** Found in the Explorer under 'Component Methods'.
- **`vpAreaName` Parameter:** Required for most commands, refers to the 4D View Pro form object's name.
- **`On VP Ready` Event:** All 4D View Pro area manipulation code must run within this event.
```
--------------------------------
### 4D User Authentication Method
Source: https://developer.4d.com/docs/WebServer/gettingStarted
This 4D code snippet handles user login by retrieving userId and password from the web request, querying the user database, verifying the password hash, and setting up the user session upon successful authentication. It sends back a welcome message or an error message.
```4D
var $indexUserId; $indexPassword : Integer
var $userId; $password : Text
var $user; $info : Object
ARRAY TEXT($anames; 0)
ARRAY TEXT($avalues; 0)
// get values sent in the header of the request
WEB GET VARIABLES($anames; $avalues)
// look for header login fields
$indexUserId:=Find in array($anames; "userId")
$userId:=$avalues{$indexUserId}
$indexPassword:=Find in array($anames; "password")
$password:=$avalues{$indexPassword}
//look for a user with the entered name in the users table
$user:=ds.WebUsers.query("userId = :1"; $userId).first()
If ($user#Null) //a user was found
//check the password
If (Verify password hash($password; $user.password))
//password ok, fill the session
$info:=New object()
$info.userName:=$user.firstName+" "+$user.lastName
Session.setPrivileges($info)
//You can use the user session to store any information
WEB SEND TEXT("Welcome "+Session.userName)
Else
WEB SEND TEXT("Wrong user name or password.")
End if
Else
WEB SEND TEXT("Wrong user name or password.")
End if
```
--------------------------------
### Configure Web Session Cookie Path
Source: https://developer.4d.com/docs/20-R9/commands/web-set-option
Sets or gets the path value for the session cookie. This controls which requests the client sends the cookie with. For example, setting '/4DACTION' limits cookies to requests starting with that path.
```4d
WEB SET OPTION(Web session cookie path; "/4DACTION")
```
--------------------------------
### Start and Stop Web Server (4D)
Source: https://developer.4d.com/docs/19/WebServer/webServerObject
Illustrates the usage of the start() and stop() methods for a 4D.WebServer object. It shows how to start a server with default settings and with custom settings provided in an object, and how to stop the server.
```4D
var $status : Object
// To start a web server with default settings
$status:=webServer.start()
// To start the web server with custom settings
// $settings object contains web server properties
webServer.start($settings)
// To stop the web server
$status:=webServer.stop()
```
--------------------------------
### Exemple Hello World avec méthode projet 4D
Source: https://developer.4d.com/docs/fr/20/ViewPro/formulas
Cet exemple montre comment déclarer une méthode projet 4D retournant "Hello World" et comment l'enregistrer comme fonction personnalisée ("vpHello") pour l'utiliser dans une cellule 4D View Pro.
```4D
#DECLARE->$hw Text
$hw:="Hello World"
```
```4D
Case of
:(Form event code=On Load)
var $o : Object
$o:=New object
// Définir la fonction "vpHello" à partir de la méthode "myMethod"
$o.vpHello:=New object
$o.vpHello.formula:=Formula(myMethod)
VP SET CUSTOM FUNCTIONS("ViewProArea";$o)
End case
```
--------------------------------
### Get menu item modifiers Command Example
Source: https://developer.4d.com/docs/commands/get-menu-item-modifiers
This example demonstrates how to use the Get menu item modifiers command in 4D to retrieve modifier keys for a menu item. It shows how to check for Shift and Option/Alt keys.
```4D
C_INTEGER($menu;$menuItem;$process;$modifierKey)
C_INTEGER($value)
// Example: Get modifiers for menu item 3 in menu 1
$menu:=1
$menuItem:=3
$process:=0 // Process of the current application
$modifierKey:=Get menu item modifiers($menu; $menuItem; $process)
If ($modifierKey # 0)
$value:=$modifierKey & 512 // Check for Shift
If ($value = 512)
ALERT("Shift modifier is used")
End if
$value:=$modifierKey & 2048 // Check for Option/Alt
If ($value = 2048)
ALERT("Option/Alt modifier is used")
End if
Else
ALERT("No additional modifier key is used")
End if
```
--------------------------------
### Hello World Example: Calling 4D Project Method (4D)
Source: https://developer.4d.com/docs/20/ViewPro/formulas
This example shows how to create a 4D project method that returns 'Hello World' and how to expose this method as a custom function named 'vpHello' in a 4D View Pro area. It includes the method definition and the code to register it.
```4D
#DECLARE->$hw Text
$hw:="Hello World"
```
```4D
Case of
:(Form event code=On Load)
var $o : Object
$o:=New object
// Define "vpHello" function from the "myMethod" method
$o.vpHello:=New object
$o.vpHello.formula:=Formula(myMethod)
VP SET CUSTOM FUNCTIONS("ViewProArea";$o)
End case
```
--------------------------------
### 4D Code Block Example
Source: https://developer.4d.com/docs/Project/documentation
Shows how to format and highlight 4D code using the ```4d ... ``` syntax.
```4D
var $txt : Text
$txt:="Hello world!"
```
--------------------------------
### Get and Restore Error Handler Method - 4D
Source: https://developer.4d.com/docs/20-R9/commands/method-called-on-error
This example demonstrates how to get the current error handler method, install a new one, execute code that might generate an error, and then restore the original error handler. It uses the 'Method called on error' command to retrieve the initial handler and 'ON ERR CALL' to set new and restore old handlers.
```4D
$methCurrent:=Method called on error
ON ERR CALL("NewMethod")
// If the document cannot be opened, an error is generated
$ref:=Open document("MyDocument")
// Reinstallation of previous method
ON ERR CALL($methCurrent)
```
--------------------------------
### Retrieve Related Entities via REST API (GET Request)
Source: https://developer.4d.com/docs/20-R9/REST/method
Demonstrates how to retrieve related entities for a specific entity using a GET request to the 4D REST API. It shows the URL structure and the expected JSON response format, including entity details and relationship information. The example specifically retrieves 'staff' related to a 'Company' entity.
```HTTP
GET /rest/Company(1)/staff?$expand=staff&$method=subentityset&$subOrderby=lastName ASC
```
```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"
}
}
}
]
}
```
--------------------------------
### Get menu item key Example - 4D Language
Source: https://developer.4d.com/docs/20-R9/commands/get-menu-item-key
This example demonstrates how to use the 'Get menu item key' command to retrieve the shortcut key for a menu item and then use 'Get menu item modifiers' to determine the modifier keys associated with it. It handles different modifier combinations like Option key, Shift key, or both.
```4D
If(Get menu item key(mymenu;1)#0)
$modifiers:=Get menu item modifiers(mymenu;1)
Case of
:($modifiers=Option key mask)
...
:($modifiers=Shift key mask)
...
:($modifiers=Option key mask+Shift key mask)
...
End case
End if
```
--------------------------------
### Execute Specific Startup Method in Utility Mode
Source: https://developer.4d.com/docs/20/Admin/cli
Starts 4D Server in utility mode and executes a specific database method designated by the --startup-method option upon startup. 'On Startup' and 'On Exit' methods are executed as usual unless skipped.
```bash
4dserver --utility --startup-method MyStartupMethod
```
--------------------------------
### Query: Find people whose first name starts with A to M
Source: https://developer.4d.com/docs/pt/commands/query
This example searches for people whose first name starts with a letter between 'A' and 'M' (inclusive). It uses a less-than comparison to achieve this range-based search.
```4d
QUERY([Pessoas];[Pessoas]Nome<"n") // Encontrar todas as pessoas entre A e M
```
--------------------------------
### Retrieve Specific Employee Attribute via REST
Source: https://developer.4d.com/docs/18/REST/gettingStarted
This example illustrates how to retrieve a specific attribute ('Lastname') of a particular employee (identified by key '2') from the 4D database using a REST API endpoint. This allows for targeted data retrieval.
```HTTP
http://127.0.0.1/rest/Employees(2)/Lastname
```
--------------------------------
### 4D On Startup Method
Source: https://developer.4d.com/docs/20-R9/commands/theme/Database-Methods
The primary method executed when the 4D application starts. It's the main entry point for application logic.
```4d
On Startup
// Method code goes here
End Long if
```
--------------------------------
### Get Table Column Attributes Example - 4D View Pro
Source: https://developer.4d.com/docs/20-R9/ViewPro/commands/vp-get-table-column-attributes
This example demonstrates how to use the VP Get table column attributes command to retrieve attributes for a specific column in a 4D View Pro table. It checks if the dataField attribute is populated.
```4D
var $attributes : Object
$attributes:=VP Get table column attributes("ViewProArea"; $tableName; 1)
If ($attributes.dataField#"")
...
End if
```
--------------------------------
### Configuration de la page d'accueil par défaut
Source: https://developer.4d.com/docs/fr/WebServer/webServerConfig
Désigne une page spécifique comme page d'accueil par défaut pour le serveur web. Le chemin est relatif au dossier racine HTML et utilise la syntaxe POSIX. Si aucune page n'est spécifiée, la méthode `On Web Connection` est appelée.
```4d
`webServer`.`defaultHomepage`
```
```4d
`WEB SET HOME PAGE`
```
--------------------------------
### Get string resource Example - 4D
Source: https://developer.4d.com/docs/20-R9/commands/get-string-resource
This example demonstrates how to retrieve and display the content of a string resource identified by its ID (20911). It assumes the resource exists in one of the currently open resource files.
```4D
ALERT(Get string resource(20911))
```
--------------------------------
### Instantiating a Web Server Object
Source: https://developer.4d.com/docs/20/WebServer/webServerObject
Demonstrates how to instantiate a 4D.WebServer object for the host application, a specific component, or the server receiving a request.
```APIDOC
## Instantiate Web Server Object
### Description
Instantiates a 4D.WebServer object to interact with a web server.
### Method
Various methods are shown for instantiation based on context:
- `WEB Server()`: Instantiates the web server of the current context.
- `WEB Server(Web server database)`: Instantiates the web server associated with a specific database.
- `WEB Server(Web server host database)`: Instantiates the host application's web server, often from a component.
- `WEB Server(Web server receiving request)`: Instantiates the web server that is currently handling a request.
### Endpoint
N/A (This describes object instantiation, not a specific HTTP endpoint).
### Parameters
None directly for the `WEB Server` command itself, but the context determines which server is referenced.
### Request Example
```apidoc
// Instantiate the web server of the current context
var webServer : 4D.WebServer
webServer := WEB Server
// Instantiate the host application's web server from a component
var webServerHost : 4D.WebServer
webServerHost := WEB Server(Web server host database)
// Instantiate the web server receiving the current request
var webServerRequest : 4D.WebServer
webServerRequest := WEB Server(Web server receiving request)
```
### Response
- **webServer** (4D.WebServer) - An object representing the web server.
```
--------------------------------
### Instantiate and Start Web Server - 4D
Source: https://developer.4d.com/docs/20-R9/API/WebServerClass
Instantiates a Web Server object using the WEB Server command and starts it. The start method can optionally accept a settings object for configuration.
```4D
var $ws:Object
$ws := WEB Server
$ws.start()
// With settings
$ws.start({"HTTPPort": 8080, "certificateFolder": "/certs/"})
```
--------------------------------
### Launch 4D Server in Utility Mode
Source: https://developer.4d.com/docs/20/Admin/cli
Starts a 4D Server instance in utility (headless) mode. This mode executes database methods like 'On Startup' and 'On Exit' unless explicitly skipped.
```bash
4dserver --utility
```
--------------------------------
### Count occurrences and concatenate strings
Source: https://developer.4d.com/docs/commands/find-in-sorted-array
This example shows how to find multiple occurrences of strings starting with a specific pattern in a sorted array. It uses 'Find in sorted array' to get the first and last positions of matching elements and then iterates through them to build a concatenated string, also reporting the count.
```4D
var $posFirst ;$posLast : Integer
var $output : Text
If(Find in sorted array($array ;"test@";>;$posFirst ;$posLast))
$output:="Found "+String($posLast-$posFirst+1)+" results :\n"
End if
For($i ;$posFirst ;$posLast)
$output:=$output+$array{$i}+"[\n"
End for
```
--------------------------------
### 4D REST API - Get All Entities
Source: https://developer.4d.com/docs/19/REST/gettingStarted
Retrieve all entities from a specified data class.
```APIDOC
## GET /{dataClassName}
### Description
Retrieves all entities from a specified data class.
### Method
GET
### Endpoint
`/rest/Employees`
### Parameters
#### Path Parameters
- **dataClassName** (string) - Required - The name of the data class to retrieve entities from.
### Request Example
None
### Response
#### Success Response (200)
- **__entityModel** (string) - The name of the entity model.
- **__GlobalStamp** (integer) - A global stamp value.
- **__COUNT** (integer) - The number of entities returned.
- **__FIRST** (integer) - The index of the first entity returned.
- **__ENTITIES** (array) - An array of entity objects. Each entity object contains its attributes.
- **__SENT** (integer) - The number of entities sent in the response.
#### Response Example
```json
{
"__entityModel": "Employees",
"__GlobalStamp": 0,
"__COUNT": 3,
"__FIRST": 0,
"__ENTITIES": [
{
"__KEY": "1",
"__TIMESTAMP": "2020-01-07T17:07:52.467Z",
"__STAMP": 2,
"ID": 1,
"Lastname": "Brown",
"Firstname": "Michael",
"Salary": 25000
},
{
"__KEY": "2",
"__TIMESTAMP": "2020-01-07T17:08:14.387Z",
"__STAMP": 2,
"ID": 2,
"Lastname": "Jones",
"Firstname": "Maryanne",
"Salary": 35000
},
{
"__KEY": "3",
"__TIMESTAMP": "2020-01-07T17:08:34.844Z",
"__STAMP": 2,
"ID": 3,
"Lastname": "Smithers",
"Firstname": "Jack",
"Salary": 41000
}
],
"__SENT": 3
}
```
```
--------------------------------
### Hello World Example: Calling a 4D Project Method
Source: https://developer.4d.com/docs/ViewPro/formulas
This example shows how to set up a 4D project method to be called from a 4D View Pro area. It involves creating a method that sets a text variable and then using VP SET CUSTOM FUNCTIONS to link this method to a custom function named 'vpHello' in the spreadsheet.
```4D
#DECLARE->$hw :Text
$hw:="Hello World"
```
```4D
Case of
:(Form event code=On Load)
var $o : Object
$o:=New object
// Define "vpHello" function from the "myMethod" method
$o.vpHello:=New object
$o.vpHello.formula:=Formula(myMethod)
VP SET CUSTOM FUNCTIONS("ViewProArea";$o)
End case
```
--------------------------------
### 4D: Send 'Hello World' on specific URL
Source: https://developer.4d.com/docs/WebServer/gettingStarted
This code snippet demonstrates how to send a 'Hello World!' text response to a browser when a specific URL ('/hello') is requested. It utilizes the `On Web Connection` database method, which receives the requested URL as a parameter. If the URL matches '/hello', it sends the text; otherwise, it suggests handling it as an error.
```4d
Case of
: ($1="/hello")
WEB SEND TEXT("Hello World!")
Else
// Error 404 for example
End case
```
--------------------------------
### Set Placeholder Text in 4D Objects
Source: https://developer.4d.com/docs/20-R9/FormObjects/propertiesEntry
Allows setting and getting placeholder text for input fields in 4D forms. Placeholder text acts as a watermark, providing a hint or example for user input and disappears when the user starts typing. It can be set programmatically using specific commands.
```4D
OBJECT SET PLACEHOLDER
OBJECT Get placeholder
```
--------------------------------
### 4D On Server Startup Method
Source: https://developer.4d.com/docs/20-R9/commands/theme/Database-Methods
This method runs when the 4D server process starts up. It's often used for initialization tasks.
```4d
On Server Startup
// Method code goes here
End Long if
```
--------------------------------
### Get REST Catalog
Source: https://developer.4d.com/docs/20-R9/WebServer/gettingStarted
Retrieves the catalog of exposed data classes and their URIs from the REST server.
```APIDOC
## GET /rest/$catalog
### Description
Retrieves a list of all data classes exposed by the REST server, along with their respective URIs.
### Method
GET
### Endpoint
/rest/$catalog
### Parameters
None
### Request Example
None
### Response
#### Success Response (200)
- **__UNIQID** (string) - A unique identifier for the catalog response.
- **dataClasses** (array) - An array of objects, where each object represents an exposed data class.
- **name** (string) - The name of the data class.
- **uri** (string) - The URI to access the data class entities.
- **dataURI** (string) - The data URI for the data class.
#### Response Example
```json
{
"__UNIQID": "3F1B6ACFFE12B64493629AD76011922D",
"dataClasses": [
{
"name": "Friends",
"uri": "/rest/$catalog/Friends",
"dataURI": "/rest/Friends"
}
]
}
```
```
--------------------------------
### Folder Creation Examples
Source: https://developer.4d.com/docs/20/API/FolderClass
Examples demonstrating how to create folders using the Folder object in 4D.
```APIDOC
## Folder Creation Examples
### Description
Examples demonstrating how to create folders using the Folder object in 4D.
### Example 1: Create an empty folder
```4d
var $created : Boolean
$created:=Folder("/PACKAGE/SpecialPrefs").create()
```
### Example 2: Create a folder with existence check
```4d
$newFolder:=Folder("/PACKAGE/Archives2019/January")
If($newFolder.create())
ALERT("The "+$newFolder.name+" folder was created.")
Else
ALERT("Impossible to create a "+$newFolder.name+" folder.")
End if
```
```
--------------------------------
### Get command status using QR Get command status
Source: https://developer.4d.com/docs/commands/qr-get-command-status
This example demonstrates how to use the QR Get command status command to check if a specific command is enabled or disabled. It takes an area and a command number as input.
```4D
VAR
areaRefNum : Integer
commandNum : Integer
status : Integer
value : Variant
areaRefNum := 1
commandNum := 1000 // Example: Font command
status := QR Get command status(areaRefNum; commandNum; value)
If (status = 1)
ALERT("Command is enabled. Value: " + Text(value))
Else
ALERT("Command is disabled.")
End if
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.