How do you define the getter to use in a CRUD form besides defining __toString()?

佐手、 提交于 2019-12-05 18:54:11

When creating an entity ( superclass of choice ) field type in a form. You need to specify which property shall be used for the labels/values otherwise the __toString() method of the underlying object will be used.

$builder->add('users', 'entity', array(
    'class' => 'AcmeHelloBundle:User',
    'property' => 'username',
));

Read more about it in the Form Type Reference for entity field Type.

Additional Info

A __toString() related error generally often comes from twig when generating a route in a template aswell. if outputting an object an object in twig with {{ object }} ... twig will call the object'S __toString method. This "trick" is used by the crud generated templates with SensioGeneratorBundle.

 {{ path('article_show', {'id': article}) }}

with the route being something like this:

article_show:
   pattern:  /article/{id}
   defaults: { _controller: AcmeArticleBundle:Article:show }

If you have the __toString method in your Article entity set to something like ...

 public function __toString()
 {
     return $this->id;
 }

... you dont't need to type

{{ path('article_show', {'id': article.id) }}

Generally Twig will automatically output Article::getId() if you use

{{ article.id }}

Hope this clarifies your findings.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!