Function loadFormData
Load form data into fields of a given struct or array.
In comparison to registerFormInterface
this method can be used in the case you have many optional form fields. It is not an error if not all fields of the struct are filled, but if it is present it must be convertible to the type of the corresponding struct field (properties are not supported). It is also not an error if the form contains more data than applied, the method simply returns the form length and the number of applied elements, so you can decide what todo.
The keys in the form must be named like "name_field" for struct, where name
is the one passed to this function. If you pass "" for name
then the form is queried for "field" where field is the identifier of a field in the struct, as before.
If you pass an array to the struct the elements get filled with elements from the form named like: "name0", "name1", ....
If the struct/array contains structs/arrays whose identifier can not be found in the form, its fields will be filled recursively.
Only dynamic arrays are supported. Their length will be expanded/reduced so the found form data matches exactly. For efficiency reason arr.assumeSafeAppend() gets called by the implementation if the length is reduced. So keep in mind that your data can be overridden.
A little example:
struct Address { string street; int door; int zipCode; string country; } struct Person { string name; string surname; Address address; } // Assume form data: [ "customer_name" : "John", "customer_surname" : "Smith", "customer_address_street" : "Broadway", "customer_address_door" : "12", "customer_address_zipCode" : "1002"] void postPerson(HttpServerRequest req, HttpServerResponse res) { Person p; // We have a default value for country if not provided, so we don't care that it is not: p.address.country="Important Country"; p.name="Jane"; enforce(loadFormData(req, p, "customer"), "More data than needed provided!"); // p will now contain the provided form data, non provided data stays untouched. assert(p.address.country=="Important Country"); assert(p.name=="John"); assert(p.surname=="Smith"); }
The mechanism is more useful in get requests, when you have good default values for unspecified parameters.
Prototype
FormDataLoadResult loadFormData(T)(HttpServerRequest req, ref T load_to, string name = "") if (is(T == struct) || isDynamicArray!(T))( HttpServerRequest req, ref T load_to, string name );
Parameters
Name | Description |
---|---|
req | The HttpServerRequest that contains the form data. (req.query or req.form will be used depending on HttpMethod) |
load_to | The struct you wan to be filled. |
name | The name of the struct, it is used to find data in the form. (form is queried for name_fieldName). |
Authors
Sönke Ludwig, Jan Krüger
Copyright
© 2012 RejectedSoftware e.K.
License
Subject to the terms of the MIT license, as written in the included LICENSE.txt file.