如何以 symfony 形式选择显示很棒的字体图标

OcB*_*974 5 php forms symfony font-awesome

我想在 Symfony Form Builder 的选择选项中显示所有字体很棒的图标。

我添加选择字段:

$choices = $this->getFontAwesome();
$form->add( $key, ChoiceType::class, array('label' => 'Texte', 'choices' => $choices, 'attr' => array('class' => "fa" ) ) );
Run Code Online (Sandbox Code Playgroud)

我的函数 getFontAwesome();

    public function getFontAwesome(){

    $webroot = $this->get('kernel')->getRootDir() . '/../web';
    $pattern = '/\.(fa-(?:\w+(?:-)?)+):before\s+{\s*content:\s*"\\\\(.+)";\s+}/';
    $subject =  file_get_contents( $webroot . '/assets/vendor/font-awesome/css/font-awesome.css');
    preg_match_all($pattern, $subject, $matches, PREG_SET_ORDER);
    foreach($matches as $match) {
        $icons[$match[1]] = '&#x' . $match[2] . ';' ;
    }

    return $icons ;

}
Run Code Online (Sandbox Code Playgroud)

但在选择字段中,看不到该图标:

字段显示代码而不是图标

在此输入图像描述

我该怎么办?我尝试 htmlspecialschars 和其他( htmlentities,.. )但不起作用。

yce*_*uto 5

如果您没有使用任何 js 插件,例如Select2Bootstrap-select,那么您就有http://jsfiddle.net/NyL7d/这种可能性,但我们需要做一些工作才能实现它。

首先,要说的是,使用<i class="fa fa-heart"></i>as label 不是一个选择,因为<option>元素不能有任何子元素,只能有文本。(参见相关问题

为了可重用性,让我们构建一个名为“IconChoiceType”的表单类型作为“ChoiceType”的子项:

namespace AppBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\OptionsResolver\OptionsResolver;

class IconChoiceType extends AbstractType
{
    /**
     * Cache for multiple icon fields or sub-requests.
     * 
     * @var array
     */
    private $choices;

    private $kernelRootDir;

    public function __construct($kernelRootDir)
    {
        $this->kernelRootDir = $kernelRootDir;
    }

    public function buildView(FormView $view, FormInterface $form, array $options)
    {
        // Pass this flag is necessary to render the label as raw. 
        // See below the twig field template for more details.
        $view->vars['raw_label'] = true;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'attr' => [
                // It's the key of the solution and can be done in many ways.
                // Now, the rendered <select> element will have a new font.
                'style' => "font-family: 'FontAwesome';"
            ],
            'choices' => $this->getFontAwesomeIconChoices(),
        ]);
    }

    public function getParent()
    {
        return ChoiceType::class;
    }

    protected function getFontAwesomeIconChoices()
    {
        if (null !== $this->choices) {
            // don't to load again for optimal performance.
            // useful for multi-icon fields and sub-requests.
            return $this->choices;
        }

        // BTW we could configure the path to the "font-awesome.css".
        $fontAwesome = file_get_contents($this->kernelRootDir.'/../web/assets/vendor/font-awesome/css/font-awesome.css');

        // this regular expression only works with uncompressed version (not works with "font-awesome.min.css")
        $pattern = '/\.(fa-(?:\w+(?:-)?)+):before\s+{\s*content:\s*"\\\\(.+)";\s+}/';

        if (preg_match_all($pattern, $fontAwesome, $matches, PREG_SET_ORDER)) {
            foreach ($matches as list(, $class, $code)) {
                // this may vary depending on the version of Symfony, 
                // if the class name is displayed instead of the icon then swap the key/value
                $this->choices['&#x'.$code.';'] = $class;
            }
        }

        return $this->choices;

    }
}
Run Code Online (Sandbox Code Playgroud)

以及各自的注册服务:

# app/config/service.yml
services:
    app.form.icon_choice_type:
        class: AppBundle\Form\Type\ChoiceIconType
        # Symfony has already a container parameter to the kernel root directory.
        arguments: ['%kernel.root_dir%']
        tags:
            - { name: form.type }
Run Code Online (Sandbox Code Playgroud)

嗯,到目前为止,没有任何结果与你的不同。

<select id="form_icon" name="form[icon]" style="font-family: 'FontAwesome';">
    <option value="fa-glass">&#xf000;</option>
    <option value="fa-music">&#xf001;</option>
    ...
</select>
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

现在问题出在哪里?字体<select>系列已准备就绪,但图标未显示,为什么?

默认情况下,在 Symfony 中,Twig 环境会转义使用htmlspecialchars更多详细信息)渲染的所有值,因此我们只需要覆盖此表单类型的此行为。为此,我们fields.html.twig在目录中创建一个模板app/Resources/views/form并将此代码复制到其中:

{# app/Resources/views/form/fields.html.twig #}

{# 
   here isn't need to create the expected `icon_choice_widget` like shown 
   the documentation, because this looks equal to `choice_widget` from 
   `ChoiceType`, only we need overwrite the block that renders the label. 
 #}

{%- block choice_widget_options -%}
    {% for group_label, choice in options %}
        {%- if choice is iterable -%}
            <optgroup label="{{ choice_translation_domain is same as(false) ? group_label : group_label|trans({}, choice_translation_domain) }}">
                {% set options = choice %}
                {{- block('choice_widget_options') -}}
            </optgroup>
        {%- else -%}

            {# this line has been overwritten, see {{- block('choice_option_label') -}} to end #}
            <option value="{{ choice.value }}"{% if choice.attr %} {% set attr = choice.attr %}{{ block('attributes') }}{% endif %}{% if choice is selectedchoice(value) %} selected="selected"{% endif %}>{{- block('choice_option_label') -}}</option>

        {%- endif -%}
    {% endfor %}
{%- endblock choice_widget_options -%}

{%- block choice_option_label -%}
    {# this block has been called from choice_widget_options block #}

    {%- if raw_label|default(false) -%}
        {# the label is rendered as raw when IconChoiceType is used #}
        {{ choice_translation_domain is same as(false) ? choice.label|raw : choice.label|trans({}, choice_translation_domain)|raw }}
    {%- else -%}
        {{ choice_translation_domain is same as(false) ? choice.label : choice.label|trans({}, choice_translation_domain) }}
    {%- endif -%}
{%- endblock -%}
Run Code Online (Sandbox Code Playgroud)

请注意,{{ choice.label|raw }} 原始过滤器将存储的原始文本(防止转义)显示到标签中,在本例中为图标字体内容。

最后,您需要注册表单主题,如描述文档

# app/config/config.yml

{# ... #}

twig:
    form_themes:
        - 'form/fields.html.twig'
Run Code Online (Sandbox Code Playgroud)

结论:

$form->add('icon', IconChoiceType::class);
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述