I am rather new to PHP & Symfony, and am struggling with the form options:
I have the following, simple code:
//OnceType.php
class OnceType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('date', TextType::class, [
"format" => "date"
])
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Once::class,
'format' => "date",
]);
}
}
I get an error because the format is not an option of TextType, but I cannot find a way to add my own options (But I know this is possible, from the others posts I read)
I have read a lot of other posts with similar issues, but cannot grasp how to do this (I tried the setDefaults options, but it didn’t lead me anywhere)
Advertisement
Answer
What you need is to create a new custom extension which extends the TextType like this for example:
<?php
namespace AppForm;
use SymfonyComponentFormAbstractTypeExtension;
use SymfonyComponentFormExtensionCoreTypeFormType;
use SymfonyComponentFormFormInterface;
use SymfonyComponentFormFormView;
use SymfonyComponentOptionsResolverOptionsResolver;
class TextTypeExtension extends AbstractTypeExtension
{
public function buildView(FormView $view, FormInterface $form, array $options)
{
$view->vars['format'] = $options['format'];
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'format' => null,
]);
}
public static function getExtendedTypes(): iterable
{
return [TextType::class];
}
}
Read more here: https://symfony.com/doc/current/form/create_form_type_extension.html