Created
May 14, 2018 15:54
-
-
Save digilist/2412e9d34b1a1087c3e29e979ee00690 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Form\Extension; | |
use Symfony\Component\Form\AbstractTypeExtension; | |
use Symfony\Component\Form\Extension\Core\Type\FormType; | |
use Symfony\Component\Form\FormInterface; | |
use Symfony\Component\Form\FormView; | |
use Symfony\Component\Translation\TranslatorInterface; | |
/** | |
* Append an (optional) prefix to any form field. | |
*/ | |
class OptionalSuffixExtension extends AbstractTypeExtension | |
{ | |
/** | |
* @var TranslatorInterface | |
*/ | |
private $translator; | |
public function __construct(TranslatorInterface $translator) | |
{ | |
$this->translator = $translator; | |
} | |
public function finishView(FormView $view, FormInterface $form, array $options) | |
{ | |
unset($form); | |
unset($options); | |
if (!$view->vars['required']) { | |
if ($view->parent !== null && $view->parent->vars['block_prefixes'][1] === 'choice') { | |
// Do not add an optional to any element of an expanded choice tpye. | |
return; | |
} | |
if (!empty($view->vars['label'])) { | |
if ($view->vars['translation_domain'] !== false) { | |
// Translate the label | |
$view->vars['label'] = $this->translator->trans( | |
$view->vars['label'], | |
[], | |
$view->vars['translation_domain'] | |
); | |
} | |
$view->vars['label'] .= sprintf(' (%s)', $this->translator->trans('optional')); | |
$view->vars['translation_domain'] = false; // Prevent a second translation attempt | |
} | |
} | |
} | |
/** | |
* Returns the name of the type being extended. | |
* | |
* @return string The name of the type being extended | |
*/ | |
public function getExtendedType() | |
{ | |
return FormType::class; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment