Reputation: 179
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)
Upvotes: 2
Views: 3088
Reputation: 1654
What you need is to create a new custom extension which extends the TextType like this for example:
<?php
namespace App\Form;
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\OptionsResolver\OptionsResolver;
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
Upvotes: 4
Reputation: 179
thanks for your help
I tried to do that, but still get the same error:
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",
]);
$resolver->setAllowedTypes("format", "string");
}
}
EDIT: I think it is because the resolver there adds the options to form, instead of the option iteself ('date', the one added in buildForm)
Upvotes: 0
Reputation: 1920
You need to add a call to $resolver->setAllowedTypes() in your configureOptions() method.
See https://symfony.com/doc/current/forms.html#passing-options-to-forms
Upvotes: 1