Skip to content

Commit d1be382

Browse files
committed
Move advanced form examples to individual files
1 parent 79365f7 commit d1be382

10 files changed

Lines changed: 374 additions & 284 deletions

File tree

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
---
2+
rows:
3+
- component: form
4+
action: examples/show_variables.sql
5+
- name: Fruit
6+
type: select
7+
empty_option: Select a fruit...
8+
options: '[{"label": "Orange", "value": 0}, {"label": "Apple", "value": 1}, {"label": "Banana", "value":
9+
3}]'
10+
---
11+
12+
This example illustrates the use of the `select` type.
13+
In this select input, the various options are hardcoded, but they could also be loaded from a database table,
14+
[using a function to convert the rows into a json array](/blog.sql?post=JSON%20in%20SQL%3A%20A%20Comprehensive%20Guide) like
15+
- `json_group_array()` in SQLite,
16+
- `json_agg()` in Postgres,
17+
- `JSON_ARRAYAGG()` in MySQL, or
18+
- `FOR JSON PATH` in Microsoft SQL Server.
19+
20+
21+
In SQLite, the query would look like
22+
```sql
23+
SELECT
24+
'select' as type,
25+
'Select a fruit...' as empty_option,
26+
'cherry' as prefix_icon,
27+
json_group_array(json_object(
28+
'label', name,
29+
'value', id
30+
)) as options
31+
FROM fruits
32+
```
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
---
2+
rows:
3+
- component: form
4+
action: examples/show_variables.sql
5+
reset: Reset
6+
- name: component
7+
type: select
8+
value: form
9+
options:
10+
- label: Form
11+
value: form
12+
options_source: examples/from_component_options_source.sql?category=component
13+
description: Start typing the name of a component like 'map' or 'form'...
14+
---
15+
16+
### Multi-select
17+
You can authorize the user to select multiple options by setting the `multiple` property to `true`.
18+
This creates a more compact (but arguably less user-friendly) alternative to a series of checkboxes.
19+
In this case, you should add square brackets to the name of the field (e.g. `'my_field[]' as name`).
20+
The target page will then receive the value as a JSON array of strings, which you can iterate over using
21+
- the `json_each` function [in SQLite](https://www.sqlite.org/json1.html) and [Postgres](https://www.postgresql.org/docs/9.3/functions-json.html),
22+
- the [`OPENJSON`](https://learn.microsoft.com/fr-fr/sql/t-sql/functions/openjson-transact-sql?view=sql-server-ver16) function in Microsoft SQL Server.
23+
- in MySQL, json manipulation is less straightforward: see [the SQLPage MySQL json example](https://github.com/sqlpage/SQLPage/tree/main/examples/mysql%20json%20handling)
24+
25+
[More information on how to handle JSON in SQL](/blog.sql?post=JSON%20in%20SQL%3A%20A%20Comprehensive%20Guide).
26+
27+
The target page could then look like this:
28+
29+
```sql
30+
insert into best_fruits(id) -- INSERT INTO ... SELECT ... runs the SELECT query and inserts the results into the table
31+
select CAST(value AS integer) as id -- all values are transmitted by the browser as strings
32+
from json_each($my_field); -- in SQLite, json_each returns a table with a "value" column for each element in the JSON array
33+
```
34+
35+
### Example multiselect generated from a database table
36+
37+
If you have a table of all possible options (`my_options(id int, label text)`),
38+
and want to generate a multi-select field from it, you have two options:
39+
- if the number of options is not too large, you can use the `options` parameter to return them all as a JSON array in the SQL query
40+
- if the number of options is large (e.g. more than 1000), you can use `options_source` to load options dynamically from a different SQL query as the user types
41+
42+
#### Embedding all options in the SQL query
43+
44+
Let's say you have a table that contains the selected options per user (`my_user_options(user_id int, option_id int)`).
45+
You can use a query like this to generate the multi-select field:
46+
47+
```sql
48+
select 'select' as type, true as multiple, json_group_array(json_object(
49+
'label', my_options.label,
50+
'value', my_options.id,
51+
'selected', my_user_options.option_id is not null
52+
)) as options
53+
from my_options
54+
left join my_user_options
55+
on my_options.id = my_user_options.option_id
56+
and my_user_options.user_id = $user_id
57+
```
58+
59+
This will generate a json array of objects, each containing the label, value and selected status of each option.
60+
61+
#### Loading options dynamically from a different SQL query with `options_source`
62+
63+
If the `my_options` table has a large number of rows, you can use the `options_source` parameter to load options dynamically from a different SQL query as the user types.
64+
65+
We'll write a second SQL file, `options_source.sql`, that will receive the user's search string as a parameter named `$search`,
66+
and return a json array of objects, each containing the label and value of each option.
67+
68+
When both `options` and `options_source` are set, the local `options` are loaded first. Search results from `options_source` are loaded into the same option list; a result with the same `value` updates the existing option. This is useful to set a default preselected value with `options_source`.
69+
70+
`options_source` may already contain query parameters. SQLPage preserves them and adds or replaces the `search` parameter when loading options.
71+
72+
##### `options_source.sql`
73+
74+
```sql
75+
select 'json' as component;
76+
77+
select id as value, label as label
78+
from my_options
79+
where label like $search || '%';
80+
```
81+
82+
##### `form`
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
---
2+
rows:
3+
- component: form
4+
method: GET
5+
- name: component
6+
type: radio
7+
value: form
8+
description: Read user input in SQL
9+
label: Form
10+
- name: component
11+
type: radio
12+
value: map
13+
checked: true
14+
description: Display a map based on database data
15+
label: Map
16+
- name: component
17+
type: radio
18+
value: chart
19+
description: Interactive plots of SQL query results
20+
label: Chart
21+
---
22+
23+
This example illustrates the use of the `radio` type.
24+
The `name` parameter is used to group the radio buttons together.
25+
The `value` parameter is used to set the value that will be submitted when the user selects the radio button.
26+
The `label` parameter is used to display a friendly name for the radio button.
27+
The `description` parameter is used to display a helper text near the radio button.
28+
29+
We could also save all the options in a database table, and then run a simple query like
30+
31+
```sql
32+
SELECT 'form' AS component;
33+
SELECT
34+
'radio' as type,
35+
'db' as name,
36+
option_name as label,
37+
option_id as value
38+
FROM my_options;
39+
```
40+
41+
In this example, depending on what the user clicks, the page will be reloaded with a the variable `$component` set to the string "form", "map", or "chart".
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
---
2+
rows:
3+
- component: form
4+
auto_submit: true
5+
- name: component
6+
type: select
7+
autocomplete: false
8+
options:
9+
- label: Form
10+
value: form
11+
selected: true
12+
- label: Map
13+
value: map
14+
- label: Chart
15+
value: chart
16+
description: Choose a component to view its documentation. No need to click a button, the page will be
17+
reloaded automatically.
18+
label: Component
19+
---
20+
21+
### Dynamically refresh the page when the user changes the form
22+
23+
The form will be automatically submitted when the user changes any of its fields, and the page will be reloaded with the new value.
24+
The validation button is removed.
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
---
2+
rows:
3+
- component: form
4+
validate: Delete
5+
validate_color: red
6+
- type: hidden
7+
name: resource_id
8+
value: '1234'
9+
- name: confirm
10+
label: Please type "sensitive resource" here to confirm the deletion
11+
required: true
12+
---
13+
14+
When you want to include some information in the form data, but not display it to the user, you can use a hidden field.
15+
16+
This can be used to track simple data such as the current user's id,
17+
or to implement more complex flows, such as a multi-step form,
18+
where the user is redirected to a different page after each step.
19+
20+
This can also be used to implement [CSRF protection](https://en.wikipedia.org/wiki/Cross-site_request_forgery#Synchronizer_token_pattern),
21+
if your website has authenticated users that can perform sensitive actions through simple links.
22+
But note that SQLPage cookies already have the `SameSite=strict` attribute by default, which protects you against CSRF attacks by default in most cases.
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
---
2+
rows:
3+
- component: form
4+
title: User
5+
validate: Create new user
6+
validate_color: green
7+
reset: Clear
8+
- name: first_name
9+
label: First name
10+
placeholder: John
11+
width: 4
12+
- name: middle_name
13+
label: Middle name
14+
placeholder: Fitzgerald
15+
width: 4
16+
- name: last_name
17+
label: Last name
18+
placeholder: Doe
19+
width: 4
20+
- name: email
21+
label: Email
22+
placeholder: john.doe@gmail.com
23+
width: 12
24+
- name: password
25+
label: Password
26+
type: password
27+
width: 6
28+
- name: password_confirmation
29+
label: Password confirmation
30+
type: password
31+
width: 6
32+
- name: terms
33+
label: I accept the terms and conditions
34+
type: checkbox
35+
required: true
36+
---
37+
38+
This example illustrates the use of custom validation buttons and half-width fields.
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
---
2+
rows:
3+
- component: form
4+
enctype: multipart/form-data
5+
title: Upload a picture
6+
validate: Upload
7+
action: examples/handle_picture_upload.sql
8+
- name: my_file
9+
type: file
10+
accept: image/png, image/jpeg
11+
label: Picture
12+
description: Upload a small picture
13+
required: true
14+
---
15+
16+
## File upload
17+
18+
You can use the `file` type to allow the user to upload a file.
19+
20+
The file will be uploaded to the server, and you will be able to access it using the
21+
[`sqlpage.uploaded_file_path`](functions.sql?function=uploaded_file_path) function.
22+
23+
Here is how you could save the uploaded file to a table in the database:
24+
25+
```sql
26+
INSERT INTO uploaded_file(name, data)
27+
VALUES (
28+
sqlpage.uploaded_file_name('my_file'),
29+
sqlpage.read_file_as_data_url(sqlpage.uploaded_file_path('my_file'))
30+
);
31+
```
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
---
2+
rows:
3+
- component: form
4+
method: post
5+
enctype: multipart/form-data
6+
title: Submit with different encoding types
7+
validate: Submit with form encoding type
8+
action: examples/handle_enctype.sql
9+
- name: data
10+
type: text
11+
label: Data
12+
required: true
13+
- name: percent_encoded
14+
type: submit
15+
label: Submit as
16+
width: 4
17+
formaction: examples/handle_enctype.sql
18+
formenctype: application/x-www-form-urlencoded
19+
value: application/x-www-form-urlencoded
20+
- name: multipart_form_data
21+
type: submit
22+
label: Submit as
23+
width: 4
24+
formaction: examples/handle_enctype.sql
25+
formenctype: multipart/form-data
26+
value: multipart/form-data
27+
---
28+
29+
## Form Encoding
30+
31+
You can specify the way form data should be encoded by setting the `enctype`
32+
top-level property on the form.
33+
34+
You may also specify `formenctype` on `submit` and `image` type inputs.
35+
This will take precedence over the `enctype` specified on the form and is
36+
useful in the case there are multiple `submit` buttons on the form.
37+
For example, an external site may have specific requirements on encoding type.
38+
39+
As a rule of thumb, ``multipart/form-data`` is best when fields may contain
40+
copious non-ascii characters or for binary data such as an image or a file.
41+
However, ``application/x-www-form-urlencoded`` creates less overhead when
42+
many short ascii text values are submitted.
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
---
2+
rows:
3+
- component: form
4+
title: CSV import
5+
validate: Load data
6+
action: examples/handle_csv_upload.sql
7+
- name: product_data_input
8+
type: file
9+
accept: text/csv
10+
label: Products
11+
description: Upload a CSV with a name, description, and price columns
12+
required: true
13+
---
14+
15+
## Bulk data insertion
16+
17+
You can use the `file` type to allow the user to upload a [CSV](https://en.wikipedia.org/wiki/Comma-separated_values)
18+
file containing data to insert in a table.
19+
20+
SQLPage can load data from a CSV file and insert it into a database table.
21+
SQLPage re-uses PostgreSQL's [`COPY` syntax](https://www.postgresql.org/docs/current/sql-copy.html)
22+
to specify the format of the CSV file, but makes it work with all supported databases.
23+
24+
> When connected to a PostgreSQL database, SQLPage will use the native `COPY` statement,
25+
> for super fast and efficient on-database CSV parsing.
26+
> But it will also work transparently with other databases, by
27+
> parsing the CSV locally and emulating the same behavior with simple `INSERT` statements.
28+
29+
Here is how you could easily copy data from a CSV to a table in the database:
30+
31+
```sql
32+
copy product(name, description, price) from 'product_data_input'
33+
with (header true, delimiter ',', quote '"');
34+
```
35+
36+
If you want to pre-process the data before inserting it into the final table,
37+
you can use a temporary table to store the data, and then insert it into the final table:
38+
39+
```sql
40+
-- temporarily store the data in a table with text columns
41+
create temporary table if not exists product_tmp(name text, description text, price text);
42+
delete from product_tmp;
43+
44+
-- copy the data from the CSV file into the temporary table
45+
copy product_tmp(name, description, price) from 'product_data_input' with (header true);
46+
47+
-- insert the data into the final table, converting the price column to an integer
48+
insert into product(name, description, price)
49+
select name, description, CAST(price AS integer) from product_tmp
50+
where price is not null and description is not null and length(description) > 10;
51+
```
52+
53+
This will load the processed CSV into the product table, provided it has the following structure:
54+
55+
```csv
56+
name,description,price
57+
"SQLPage","A tool to create websites using SQL",0
58+
"PostgreSQL","A powerful open-source relational database",0
59+
"SQLite","A lightweight relational database",0
60+
"MySQL","A popular open-source relational database",0
61+
```

0 commit comments

Comments
 (0)