如何在树枝模板中显示ChoiceType键

时间:2018-02-20 11:27:55

标签: php symfony twig formbuilder

让我们说我用symfony表单构建器构建以下表单:

$builder->add('version', ChoiceType::class, [
    'choices'   => [
        'Wheezy'    => 7,
        'Jessie'    => 8,
        'Stretch'   => 9
    ]
])

稍后我需要从树枝模板访问它,例如显示一个表:

...
<td>{{ entity.version }}</td>
<td>{{ entity.foo }}</td>
<td>{{ entity.bar }}</td>
...

如果我这样做,我的版本将等于 7 8 9 ,我不会#39 ; t想要做以下事情,这显然会打败它的目的:

$builder->add('version', ChoiceType::class, [
    'choices'   => [
        'Wheezy'    => "Wheezy",
        'Jessie'    => "Jessie",
        'Stretch'   => "Stretch"
    ]
])

如何在不必将其映射到模板中的情况下执行此操作?我也真的想避免做一个完整的实体,对于如此少的条目会是一种过度杀伤力。我非常肯定,或者至少我希望有一些东西可以处理已经与symfony捆绑在一起的情况,谢谢。

1 个答案:

答案 0 :(得分:1)

您需要使用此功能,但它会在您的数据库中占用更多空间:

$builder->add('version', ChoiceType::class, [
    'choices'   => [
        'Wheezy'    => "Wheezy",
        'Jessie'    => "Jessie",
        'Stretch'   => "Stretch"
    ]
]);

或者在您的实体中处理它,例如:

class Entity {
    const VERSIONS = [
        'Wheezy'  => 7,
        'Jessie'  => 8,
        'Stretch' => 9
    ];

    // code

    public function getVersion($string = false) {
        if ($string && \in_array($this->version, self::VERSIONS))
            return \array_search($this->version, self::VERSIONS);

        return $this->version;
    }
}

在表单构建器中,您只需将选项设置为实体的版本列表。

$builder->add('version', ChoiceType::class, [
    'choices' => Entity::VERSIONS
]);

最后在模板中将getter $ string值设置为true

...
<td>{{ entity.version(true) }}</td>
<td>{{ entity.foo }}</td>
<td>{{ entity.bar }}</td>
...

默认情况下,getter getVersion的行为将正常,如果将$ string boolean参数设置为true,它会将值呈现为字符串

修改 您没有添加有关PHP版本的任何信息,因此我假设您至少使用版本7.0,因此返回类型声明。另请注意,至少需要PHP 5.6才能将数组用作常量值。