Symfony 出错 选项 "constraints" 不存在

Error with Symfony The option "constraints" does not exist

Symfony 问题,我才刚刚开始学习它。 用户上传一个文件,其中包含我要以数组形式(key-value)提交给表单进行验证的数据。我调用构建表单的方法,向其传递一个数组并尝试检查,例如,标题的长度 ('title') 是否不超过 255 个字符。抛出错误“选项“约束”不存在”。

ImportService.php

<?php

namespace App\Service;

use App\Entity\Import;  
use App\Service\ServiceInterface;  
use Box\Spout\Reader\Common\Creator\ReaderEntityFactory;  
use Symfony\Component\Form\Forms;  
use Doctrine\Persistence\ManagerRegistry; 
use Symfony\Component\Form\Form;

class ImportService implements ServiceInterface {
    public function __construct(protected ManagerRegistry $doctrine)
    {
    }
 
    public function parse(Import $import, array $scheme, array $formOptions = [])
    {
        $rowArray = [];

        $reader = ReaderEntityFactory::createXLSXReader();
        $reader->open($import->getPath());
        foreach ($reader->getSheetIterator() as $index => $sheet) {
            foreach ($sheet->getRowIterator() as $rowIndex => $row) {
                if ($rowIndex == 1) {
                    continue;
                } else {
                    $cells = $row->getCells();
                    foreach ($cells as $cell) {
                        $rowArray[] = $cell->getValue();
                    };

                    $row = array_combine($scheme, $rowArray);

                    $importRow = new ImportRow($import, $sheet, $rowIndex, $row);

                    $form = $this->buildForm($import->getFormType());
                    $form->submit($row);

                    if ($form->isValid()) {
                        $import->setSuccess('true');
                        $this->saveImport($import);

                        return $row;
                    }
                }
            };
        }
    }

    protected function buildForm(string $formType, array $formOptions = []): Form
    {
        $formFactory = Forms::createFormFactory();

        return $formFactory
            ->create(
                $formType,
                null,

            );
    }

NewsImportType.php

use App\Entity\News; use Symfony\Component\Form\AbstractType;  
use Symfony\Component\Form\FormBuilderInterface;  
use Symfony\Component\OptionsResolver\OptionsResolver;  
use Symfony\Component\Form\Extension\Core\Type\TextType; 
use Symfony\Component\Form\Extension\Core\Type\TextareaType; 
use Symfony\Component\Validator\Constraints\Collection; 
use Symfony\Component\Validator\Constraints\Email; 
use Symfony\Component\Validator\Constraints\Length; 
use Symfony\Component\Validator\Constraints\Url;

class NewsImportType extends AbstractType {

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('title', TextType::class, [
                'constraints' =>
                [new Length(['max' => 256])],
            ])
            ->add('text', TextareaType::class, [
                'constraints' =>
                [new Length(['max' => 1000])],
            ])
            ->add('image', TextType::class, [
                'constraints' =>
                [
                    new Length(['max' => 256]),
                    new Url()
                ],
            ]);
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([
            'allow_extra_fields' => true,
            'data_class' => News::class,
        ]);
    } }

错误文本

An error has occurred resolving the options of the form "Symfony\Component\Form\Extension\Core\Type\TextType": The option "constraints" does not exist. Defined options are: "action", "allow_file_upload", "attr", "attr_translation_parameters", "auto_initialize", "block_name", "block_prefix", "by_reference", "compound", "data", "data_class", "disabled", "empty_data", "error_bubbling", "form_attr", "getter", "help", "help_attr", "help_html", "help_translation_parameters", "inherit_data", "invalid_message", "invalid_message_parameters", "is_empty_callback", "label", "label_attr", "label_format", "label_html", "label_translation_parameters", "mapped", "method", "post_max_size_message", "priority", "property_path", "required", "row_attr", "setter", "translation_domain", "trim", "upload_max_size_message".

替代解决方案

在构造函数中添加'FormFactoryInterface $formFactory'。 在方法本身中,修复为 '$this->'

return $this->formFactory
            ->create(
                $formType,
                null,
                array_merge($formOptions, $baseOptions)

documentation 中所述:

This option is added in the FormTypeValidatorExtension form extension.

您可能忘记安装 Validator component:

composer require symfony/validator

根据文档,您一定有类似的东西:


->add('title', TextType::class, [
                'constraints' =>
                new Length(['max' => 256]),
            ])
            ->add('text', TextareaType::class, [
                'constraints' =>
                new Length(['max' => 1000]),
            ])
            ->add('image', TextType::class, [
                'constraints' =>
                [
                    new Length(['max' => 256]),
                    new Url()
                ],
            ]);

你把这个:

'constraints' =>
                [new Length(['max' => 256])],
            ])

医生是这样说的:

 'constraints' => new Length(['max' => 256]),

constraints 选项是 ValidatorExtension 的一部分,而不是核心表单扩展的一部分。您可以像下面这样使用它

$validator = Validation::createValidator();
$formFactory = Forms::createFormFactoryBuilder()
        ->addExtension(new ValidatorExtension($validator))
        ->getFormFactory();

也加上这个

use Symfony\Component\Form\Extension\Validator\ValidatorExtension;

refer link for details