Imagine a User
model like this:
class User {
/**
* ...some mapping info...
*/
private $username;
/**
* ...some mapping info...
*/
private $password;
public function setUsername($username) {
$this->username = $username;
}
public function setPassword($password) {
$this->password = $password;
}
}
A sample form to submit a new User
:
<form action="/controller/saveUser" method="post">
<p>Username: <input type="text" name="username" /></p>
<p>Password: <input type="text" name="password" /></p>
</form>
Currently in my controller I save a new User
like this:
public function saveUser() {
$user = new User();
$user->setUsername($_POST['username']);
$user->setPassword($_POST['password']);
$entityManager->persist($user);
}
That means, calling the setter method for each of the properties I receive via the form.
My question: is there a method in Doctrine which allows you to automatically map form data/an array structure to a Doctrine model? Ideally it is possible to populate nested object graphs from an array with a similiar structure.
Ideally I could change my controller code to something along these lines (pseudo code/example):
public function saveUser() {
$user = Doctrine::populateModelFromArray('User', $_POST); // does this method exist?
$entityManager->persist($user);
}
Thanks in advance for any hints!
EDIT: It seems something like this exists in Doctrine 1 ( http://www.doctrine-project.org/projects/orm/1.2/docs/manual/working-with-models%3Aarrays-and-objects%3Afrom-array/en ) - so, is there an equivalent in Doctrine 2?
This works for me in Doctrine 2.0
$user = new User();
$user->fromArray($_POST);
As long as the key's of your POST array match the column names this should populate the model for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With