Ocsigen by example, Part 5: GET forms
We've previously seen that Eliom ensures that hyperlinks to services are type-safe, ie, you cannot for example provide an alphabetic string (or no parameters at all) to a service that expects an integer. This type-safety is also extended to the creation and validation of XHTML forms. You can therefore provide together with a service a function that creates forms for that service. Eliom — or rather the compiler — makes sure the types are in harmony. Moreover, bear in mind that before invoking a service with any parameters, Eliom first checks that the parameters have values as expected. It will therefore raise an error if the user provided us with an alphabetic string in a form field that required an integer or a float, for example (it is of course possible to provide a custom handler for this sort of error situations instead of relying on the default one — check the Eliom tutorial for details).
Another cool feature is the possibility of Eliom services accepting custom types, and not just the predefined integers, floats, strings, etc. Again, check the tutorial for details.
The code below demonstrates the use of GET forms. It defines a "coucou" service taking three GET parameters of different types, and defines also a function "coucou_form" to create the contents of a form for "coucou". In service "main", this function is used as a parameter to Eliom_predefmod.Xhtml.get_form to actually create the form.
(************************************************************************)
(* Demonstration of forms for services with GET parameters. *)
(************************************************************************)
open XHTML.M
open Eliom_parameters
(************************************************************************)
(* Service "coucou" takes three GET parameters and no POST parameters.
*)
let coucou_handler _ (i, (j, s)) () =
Lwt.return
(html
(head (title (pcdata "Coucou")) [])
(body [p
[
pcdata "You sent: ";
strong [pcdata (string_of_int i)];
pcdata ", ";
strong [pcdata (string_of_float j)];
pcdata " and ";
strong [pcdata s]
]]))
let coucou_service =
Eliom_predefmod.Xhtml.register_new_service
~path: ["coucou"]
~get_params: (Eliom_parameters.int "i" ** (Eliom_parameters.float "j" ** Eliom_parameters.string "s"))
coucou_handler
(************************************************************************)
(* This function is used for building forms for service "coucou".
Note that its parameter is a nested pair defined in the same
fashion as the GET parameters for "coucou". Also note that
proper XHTML forms should make use of fieldsets for logically
dividing the form, and that field labels should be declared
with the

Many thanks for these posts.
Reply to this