开发者

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

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 name your fields the same as the entity properties:

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

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


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

I tested it in Doctrine 1.2.4 it work very fine.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜