Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

easy way to populate a doctrine 2 model with form data?

Tags:

php

doctrine

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?

like image 840
Max Avatar asked Sep 19 '10 13:09

Max


1 Answers

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.

like image 51
k0nG Avatar answered Oct 22 '22 23:10

k0nG