使用静态函数为表单的选项定义数组
Use a static function to define an array for the choices options of a form
我使用 easyAdminBundle,我想知道是否可以使用 static function
或 const
(在我的应用程序中的任何位置定义)来设置 choices
选项choice
这样输入:
- { property: tag, type: choice, type_options: { choices: 'App\Entity\News::getTags' }
使用 getTags
函数,例如:
class News
{
const TAGS = ['toto','tutu'];
static public function getTags()
{
return $this::TAGS;
}
}
已经可以用 query_builder
做到这一点,但我没有在文档中找到它的任何踪迹。
实际上我收到以下错误,这让我认为这是不可能的(但也许这里有人这样做):
An error has occurred resolving the options of the form "Symfony\Component\Form\Extension\Core\Type\ChoiceType": The option "choices" with value "App\Entity\News::getTags" is expected to be of type "null" or "array" or "\Traversable", but is of type "string".
是的,将 const TAGS
设置为静态并在 getTags()
内部,
将 $this
替换为 self
.
和
{ choices: App\Entity\News::getTags() }
删除撇号并添加 () 以实际调用函数
遵循 3.2 版本后可用的 @David Alvarez, I've tried to access the const
property directly from the yaml file. This is possible thanks to this symfony update 的建议。
所以访问 const 属性 为:
class News
{
const TAGS = ['toto' => 'toto','tutu' => 'tutu'];
}
我会写:
{ choices: !php/const App\Entity\News::TAGS }
它就像一个魅力
我使用 easyAdminBundle,我想知道是否可以使用 static function
或 const
(在我的应用程序中的任何位置定义)来设置 choices
选项choice
这样输入:
- { property: tag, type: choice, type_options: { choices: 'App\Entity\News::getTags' }
使用 getTags
函数,例如:
class News
{
const TAGS = ['toto','tutu'];
static public function getTags()
{
return $this::TAGS;
}
}
已经可以用 query_builder
做到这一点,但我没有在文档中找到它的任何踪迹。
实际上我收到以下错误,这让我认为这是不可能的(但也许这里有人这样做):
An error has occurred resolving the options of the form "Symfony\Component\Form\Extension\Core\Type\ChoiceType": The option "choices" with value "App\Entity\News::getTags" is expected to be of type "null" or "array" or "\Traversable", but is of type "string".
是的,将 const TAGS
设置为静态并在 getTags()
内部,
将 $this
替换为 self
.
和
{ choices: App\Entity\News::getTags() }
删除撇号并添加 () 以实际调用函数
遵循 3.2 版本后可用的 @David Alvarez, I've tried to access the const
property directly from the yaml file. This is possible thanks to this symfony update 的建议。
所以访问 const 属性 为:
class News
{
const TAGS = ['toto' => 'toto','tutu' => 'tutu'];
}
我会写:
{ choices: !php/const App\Entity\News::TAGS }
它就像一个魅力