Suppose I have an HTML page with input data for the following relationship:
An User has the properties "given_name" and "family_name"
An User has N Phones (property "phones")
An User has 1 IdCard (property "idCard")
A Phone has the property "number"
An IdCard has the property "number"
Here's the HTML code:
<form method="POST">
<p>
<label>Given Name</label>
<input type="text" name="User[given_name]" value="My"/>
</p>
<p>
<label>Family Name</label>
<input type="text" name="User[family_name]" value="Name"/>
</p>
<fieldset>
<p>
<label>Phone 1</label>
<input type="text" name="User[Phone][][number]" value="7777-7777"/>
</p>
<p>
<label>Phone 2</label>
<input type="text" name="User[Phone][][number]" value="8888-8888"/>
</p>
<p>
<label>Phone 3</label>
<input type="text" name="User[Phone][][number]" value="9999-9999"/>
</p>
</fieldset>
<p>
<label>ID Card Number</label>
<input type="text" name="User[IdCard][number]" value="0000.0000.0000"/>
</p>
<input type="submit"/>
</form>
How would you handle the POST data on the server-side to automatically unserialize it into instances of the respective objects?
Example of desired result (pseudocode):
user = unserialize(new User, request.POST)
assert user instanceof User
assert user.given_name == "My"
assert user.family_name == "Name"
assert user.phones instanceof Array
assert user.phones.length == 3
assert user.phones[0] instanceof Phone
assert user.phones[1] instanceof Phone
assert user.phones[2] instanceof Phone
assert user.phones[0].number == "7777-7777"
assert user.phones[1].number == "8888-8888"
assert user.phones[2].number == "9999-9999"
assert user.idCard instanceof IdCard
assert user.idCard.number == "0000.0000.0000"
I'm asking this because while some web frameworks focus on shiny examples of saving a todo message into a todo list (simple and almost unstructured data), real life makes me deal with complex forms with complex relationships, and apparently there's no common solution for the problem that I described.
I come from a PHP/Yii background. Am I missing something?
Aucun commentaire:
Enregistrer un commentaire