【问题标题】:Use a static function to define an array for the choices options of a form使用静态函数为表单的选择选项定义数组
【发布时间】:2020-02-22 19:59:41
【问题描述】:

我使用的是easyAdminBundle,我想知道是否可以使用static functionconst(在我的应用程序中定义)来设置choice 类型的choices 选项:

- { 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 已经可以做到这一点,但我在文档中没有找到任何痕迹。

实际上我收到以下错误,导致我认为这是不可能的(但也许这里有人这样做):

解析“Symfony\Component\Form\Extension\Core\Type\ChoiceType”形式的选项时发生错误:值“App\Entity\News::getTags”的选项“choices”应为类型为“null”或“array”或“\Traversable”,但类型为“string”。

【问题讨论】:

    标签: php symfony easyadmin


    【解决方案1】:

    是的,将const TAGS 设置为静态并在getTags() 内部, 将$this 替换为self

    { choices: App\Entity\News::getTags() }
    

    去掉撇号,加上(),实际调用函数

    【讨论】:

    • 根据this(和我的编译器)你不能在php中设置static const。无论如何,这就是static function 的原因。我按照建议将$this 替换为self,并将() 替换为yaml 文件中的调用。我仍然遇到同样的错误。好像它没有被解释为一个函数......
    • 我不是 100% 的,但如果你使用非静态属性,你必须创建一个 News 实例来访问它。但是在这里你可以静态访问新闻
    • const是静态可访问的。但只是为了确保我已经尝试过 static private $TAGS 并且我仍然得到同样的错误
    • 尝试直接访问常量而不是使用函数:stackoverflow.com/questions/1685922/…
    • 相同,但按照您的建议,我去过symfony website 并找到一种直接从 yaml 访问常量的方法。奇迹般有效。我正在发布答案
    【解决方案2】:

    按照@David Alvarez 的建议,我尝试直接从yaml 文件中访问const 属性。这要归功于自 3.2 版本以来提供的 symfony update

    所以要访问 const 属性:

    class News 
    {
        const TAGS = ['toto' => 'toto','tutu' => 'tutu'];
    }
    

    我会写:

    { choices: !php/const App\Entity\News::TAGS }
    

    它就像一个魅力

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-10
      • 1970-01-01
      • 1970-01-01
      • 2013-03-02
      相关资源
      最近更新 更多