nineskeletor/src/Form/Type/FaChoiceType.php

75 lines
2.1 KiB
PHP

<?php
namespace App\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 FaChoiceType extends AbstractType
{
/**
* Cache for multiple icon fields or sub-requests.
*
* @var array
*/
private $choices;
private $fontawesomeIconsFile;
public function __construct($fontawesomeIconsFile)
{
// Liste des icones FontAwesome au format JSON
// Récupéré depuis le dépôt officiel via la commande "make fetch-fontawesome-icons"
// Voir service.yml
$this->fontawesomeIconsFile = $fontawesomeIconsFile;
}
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.
'class' => 'select2-icon',
],
'choices' => $this->getFontAwesomeIconChoices(),
]);
}
public function getParent()
{
return ChoiceType::class;
}
protected function getFontAwesomeIconChoices()
{
if (null !== $this->choices) {
return $this->choices;
}
$fileContent = file_get_contents($this->fontawesomeIconsFile);
if (!$fileContent) {
throw new \Error('Could not load fontawesome icons file');
}
$icons = json_decode($fileContent, true);
foreach ($icons as $iconName => $iconStyle) {
$iconClass = $iconStyle['type'].' fa-'.$iconName;
$this->choices[$iconStyle['name']] = trim($iconClass);
}
return $this->choices;
}
}