如何在Symfony表单选择器中显示Font Awesome图标

5
我可以帮助您翻译以下内容:

我希望在Symfony表单构建器中显示所有字体图标的选择选项。

我使用以下代码添加选择字段:

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

我的函数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 ;

}

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

字段显示代码而不是图标

输入图像描述

我该怎么办? 我尝试使用htmlspecialschars和其他方法(htmlentities等),但都没有起作用。


你正在使用select2插件吗? - yceruto
2个回答

5
如果您没有使用像Select2Bootstrap-select这样的js插件,那么您可以使用http://jsfiddle.net/NyL7d/这个方法,但我们需要做一些工作才能实现它。
首先,使用<i class ="fa fa-heart"></i>作为标签是不可行的,因为

-1

我知道这是一个相当古老的帖子,@yceruto的答案是正确的并且有其存在的意义,但我认为对于像在表单上放置图标这样简单的事情来说,它太过复杂了。因此,对于新访客,我提供我的版本。

在formBilder中

public function buildForm(FormBuilderInterface $builder, array $options)
{
    // prepare an array with icons
    $icons =  [
        '&#xf042;',
        '&#xf170;',
    ];
    
    // decode our icons
    $icons = array_flip(array_map('html_entity_decode',$icons));
    
    // add field to formBuilder
    $builder->add('icon', ChoiceType::class, [
        'choices'  => $icons,
        'mapped' => false,
    ]);

}

在你的页面中引入FontAwesome库并添加CSS样式。
select { font-family: 'FontAwesome', serif }

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接