How to populate zend_form from Doctrine2 entity?
Right now I'm populating/setDefaults a zend_form like this from the controller:
$data = array('user' => $account->getUser(),
'password' => $account->getPassword(),
'name' => $account->getName());
$form->setDefaults($data);
It's working but seams very manual the process. Is there a bet开发者_如何学JAVAter way to do it?
The "obvious" solution is to somehow factor out flattening entities into arrays. This is not too hard to do, though some corner cases can get ugly.
The best-looking (I haven't tried it yet, but am about to) canned implementation I've run across is this one (some docs are here).
It uses reflection to look at an entities metadata, and then makes some good guesses about what kind of structure to return. This seems like the best strategy, overall. I suspect that to handle unusually structured entities, you might want to tweak Boris' class to check for a custom serialization method on the entity, and if present, let the entity serialize itself.
The solution that I apply was to add this function to the entity:
public function toArray ()
{
return get_object_vars($this);
}
And then just:
$form->setDefaults($test->toArray());
Also if you need to do it the other way arround (array to object) you can take a look here
精彩评论