Reputation: 682
How can I create FormType in Symfony2 for converting an entity to a string and back?
I've done all that is saying in here but there is an error:
Expected argument of type "string", "<Vendor>\<Bundle>\Entity\User" given
How can I create a form where a text field will be converted to an user object?
Upvotes: 1
Views: 722
Reputation: 48899
Assuming User
has an username
field i would do a transform like the following. Please pay attention that transform
is for User
to string
transform, while reverseTransform
is the opposite.
Add the transformer to your form field:
$builder
->add('user', 'text')
->addViewTransformer($transformer)
Relevant code (like example you've cited):
/**
* Transforms an User to a string.
*
* @param User|null $user
* @return string
*/
public function transform($user)
{
return $user ? $user->getUsername() : '';
}
/**
* Transforms a string to an User.
*
* @param string $username
* @return User|null
*/
public function reverseTransform($username)
{
if(empty($username)) return null;
$user = $this->om
->getRepository('AcmeHelloBundle:User')
->findOneBy(array('username' => $username))
;
return $user; // Can be null
}
Upvotes: 3
Reputation: 529
You can extract this form type here and use that. https://github.com/symfony/symfony/pull/1951 it does what you are asking.
Upvotes: 0