Paul Seleznev
Paul Seleznev

Reputation: 682

Create new type in symfony2

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

Answers (2)

gremo
gremo

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

Henrik Bj&#248;rnskov
Henrik Bj&#248;rnskov

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

Related Questions