2

I'm using KNP Translatable and I have the following data structure:

User (id, name, email, password...) Role (id, name @translatable)

User Role is a many to many relation.

I have the form type defined as this:

->add('roles', 'entity', [
    'class' => 'SocialCarBackendBundle:Role',
    'property' => 'name',
    'multiple' => true,
    'expanded' => true
])

And I implemented the __call method in the role entity:

public function __call($method, $arguments)
    {
        try {
            return $this->proxyCurrentLocaleTranslation($method, $arguments);
        } catch (\Symfony\Component\Debug\Exception\ContextErrorException $e) {
            return $this->proxyCurrentLocaleTranslation('get' . ucfirst($method), $arguments);
        }

    }

Now, in the twig template I can call the name property of the roles without problems and it renders it correctly.

But when trying to render the form I get this error:

Neither the property "name" nor one of the methods "getName()", "name()", "isName()", "hasName()", "__get()" exist and have public access in class "SocialCar\BackendBundle\Entity\Role".

Is there any workaround for this? Thanks a lot

petekaner
  • 8,071
  • 5
  • 29
  • 52

1 Answers1

4

symfony's propertyaccessor component has not magic calls enabled for EntityType property

you can see vendor/symfony/symfony/src/Symfony/Bridge/Doctrine/Form/Type/DoctrineType.php to prove that.

so you have three ways(in order of complexity):

  1. do getter and setters that call proxyCurrentLocaleTranslation, imho there are nothing bad using less magic things:)

  2. use a more complex property like this

    'property' => 'translations[' . $options['locale'] . '].name',

    where $options['locale'] is the locale injected inside the form as an option

  3. you can create a different EntityType class that extends your custom DoctrineType class that initializes PropertyAccessor to support magic calls

for more info about property accessor:

http://symfony.com/doc/current/components/property_access/introduction.html

and about the second way:

https://github.com/KnpLabs/DoctrineBehaviors/issues/67

Marino Di Clemente
  • 3,120
  • 1
  • 23
  • 24
  • Hi, thanks a lot, looks I'm going with option 2. The only thing is I'm trying ot inject the session object to use the getLocale method but it looks like it doesnt exist anymore. – petekaner May 20 '15 at 08:38
  • here the new way http://stackoverflow.com/questions/18949397/how-to-get-the-current-locale-in-symfony-2-3 – Marino Di Clemente May 20 '15 at 09:48