简体   繁体   中英

How to add options to a Symfony Form field?

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)

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

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM