An easy way to fill out a doctrine 2 model with form data?

Imagine this User model:

 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; } } 

Sample form for submitting 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 the new User as follows:

 public function saveUser() { $user = new User(); $user->setUsername($_POST['username']); $user->setPassword($_POST['password']); $entityManager->persist($user); } 

This means that the setter method is called for each of the properties that I get through the form.

My question is: is there a method in Doctrine that allows you to automatically map form data / array structure to the Doctrine model? Ideally, you can fill in nested graphs of objects from an array using a similar 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 tips!


EDIT: It seems like 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?

+6
php doctrine
source share
3 answers

This works for me in Doctrine 2.0

$user = new User(); $user->fromArray($_POST);

As long as the key of your POST array matches the column names, this should populate the model for you.

+1
source share

If you name your fields the same as the properties of the object:

 <?php foreach($_POST as $field => $val){ $object->$field = $val; } ?> 

But this only works for public properties. However, you can calculate the method name based on this and use call_user_func () to call it.

0
source share

$ user = new User (); $ User-> fromArray ($ _ POST);

I tested it in Doctrine 1.2.4, it works great.

0
source share

All Articles