Symfony 4.为什么提交的表格仅部分填充了模型?

时间:2019-06-17 21:25:49

标签: php symfony symfony4 symfony-forms

有些恐慌-我正在生成Symfony表单以进行复杂的搜索,即映射到实体的数据将仅用于搜索查询构建。

我从ChoiceType创建简单的表单,模型和一些扩展类型,以便通过某种逻辑预先填充选择。表单是使用GET方法提交的。

在模型中,您可以找到makermodel字段。选择制造商后,后者将在前端填充AJAX。当我确实提交表单并且makermodel具有非默认值时,handleRequest仅填充模型的maker属性,而{{1} }留空。如果选中,复选框也将正确填充。总之,model仅返回Maker和复选框,其他字段为null。 $form->getData()具有所有参数。

数据映射器在这里毫无意义。而且,数据中没有任何要转换的内容,该模型主要来自标量值。该请求包含所有内容,但处理不正确。我尝试实现$request->query,但对我来说不起作用,因为在加载选择期间,我必须访问表单的ChoiceLoaderInterface,而我没有访问权限(我使用了本文{ {3}}。

我正在使用Symfony 4.2.4; PHP 7.2。

控制器方法

options

CarSimpleSearchModel

/**
     * @Route("/search/car", name="car_search", methods={"GET"})
     * @param Request $request
     */
    public function carSearchAction(Request $request)
    {
        $carModel = new CarSimpleSearchModel();
        $form     = $this->createForm(CarSimpleSearchType::class, $carModel);
        $form->handleRequest($request);

        $form->getData();

        .....
    }

CarSimpleSearch键入表单

class CarSimpleSearchModel
{
    public $maker;
    public $model;
    public $priceFrom;
    public $priceTo;
    public $yearFrom;
    public $yearTo;
    public $isCompanyOwner;
    public $isPrivateOwners;
    public $isRoublePrice;
}

CarMakerSelectType字段

class CarSimpleSearchType extends AbstractType
{
    protected $urlGenerator;

    public function __construct(UrlGeneratorInterface $urlGenerator)
    {
        $this->urlGenerator = $urlGenerator;
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('vehicle_type', HiddenType::class, [
                'data' => VehicleTypeType::CAR,
                'mapped' => false,
            ])
            ->add('maker', CarMakerSelectType::class)
            ->add('model', CarModelsSelectType::class)
            ->add(
                'priceFrom',
                VehiclePriceRangeType::class,
                [
                    'vehicle_type' => VehicleTypeType::CAR,
                ]
            )
            ->add(
                'priceTo',
                VehiclePriceRangeType::class,
                [
                    'vehicle_type' => VehicleTypeType::CAR,
                ]
            )
            ->add(
                'yearFrom',
                VehicleYearRangeType::class,
                [
                    'vehicle_type' => VehicleTypeType::CAR,
                ]
            )
            ->add(
                'yearTo',
                VehicleYearRangeType::class,
                [
                    'vehicle_type' => VehicleTypeType::CAR,
                ]
            )
            ->add('isCompanyOwner', CheckboxType::class)
            ->add('isPrivateOwners', CheckboxType::class)
            ->add('isRoublePrice', CheckboxType::class)
            ->add('submit', SubmitType::class);
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(
            [
                'data_class' => CarSimpleSearchModel::class,
                'compound'   => true,
                'method'     => 'GET',
                'required'   => false,
                'action'     => $this->urlGenerator->generate('car_search'),
            ]
        );
    }

    public function getBlockPrefix()
    {
        return 'car_search_form';
    }
}

CarModelSelectType字段

class CarMakerSelectType extends AbstractType
{
    /**
     * @var VehicleExtractorService
     */
    private $extractor;

    /**
     * VehicleMakerSelectType constructor.
     *
     * @param VehicleExtractorService $extractor
     */
    public function __construct(VehicleExtractorService $extractor)
    {
        $this->extractor = $extractor;
    }

    public function getParent()
    {
        return ChoiceType::class;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(
            [
                'placeholder'  => null,
                'vehicle_type' => null,
                'choices'      => $this->getVariants(),
            ]
        );
    }

    private function getVariants()
    {
        $makers  = $this->extractor->getMakersByVehicleType(VehicleTypeType::CAR);
        $choices = [];

        foreach ($makers as $maker) {
            $choices[$maker['name']] = $maker['id'];
        }

        return $choices;
    }
}

VehiclePriceRangeType字段

class CarModelsSelectType extends AbstractType
{
    private $extractor;
    public function __construct(VehicleExtractorService $extractor)
    {
        $this->extractor = $extractor;
    }

    public function getParent()
    {
        return ChoiceType::class;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(
            [
                'disabled'    => true,
            ]
        );
    }
}

VehicleYearRangeType字段

class VehiclePriceRangeType extends AbstractType
{
    private $extractor;

    public function __construct(VehicleExtractorService $extractor)
    {
        $this->extractor = $extractor;
    }

    public function getParent()
    {
        return ChoiceType::class;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(
            [
                'vehicle_type' => null,
            ]
        );
    }

    public function buildView(FormView $view, FormInterface $form, array $options)
    {
        foreach ($this->getRange($options['vehicle_type']) as $value) {
            $view->vars['choices'][] = new ChoiceView($value, $value, $value);
        }
    }

    private function getRange(int $vehicleType)
    {
        return PriceRangeGenerator::generate($this->extractor->getMaxVehiclePrice($vehicleType));
    }
}

因此,我可以使用class VehicleYearRangeType extends AbstractType { private $extractor; public function __construct(VehicleExtractorService $extractorService) { $this->extractor = $extractorService; } public function getParent() { return ChoiceType::class; } public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults( [ 'vehicle_type' => null, ] ); } public function buildView(FormView $view, FormInterface $form, array $options) { foreach ($this->getRange($options['vehicle_type']) as $value) { $view->vars['choices'][] = new ChoiceView($value, $value, $value); } } protected function getRange(int $vehicleType): array { $yearRange = RangeGenerator::generate( $this->extractor->getMinYear($vehicleType), $this->extractor->getMaxYear($vehicleType), 1, true, true ); return $yearRange; } } 中的原始数据并手动验证-填充模型并发送到进一步处理,但是我想这不是正确的方法,我想用框架填充表单。我怎么?..

1 个答案:

答案 0 :(得分:1)

就我而言,我有一个依赖项EntityType由最初禁用的ajax填充。由于choicesnull的位置,因此它在提交时返回了InvalidValueException。我要做的是创建一个EventListener,并为当前的“ main”字段添加有效的choices。基本上就是这样,或多或少适合您的情况。

原始形式:

// Setup Fields
$builder
    ->add('maker', CarMakerSelectType::class)
    ->add('model', CarModelsSelectType::class, [
            'choices' => [],
            // I was setting the disabled on a Event::PRE_SET_DATA if previous field was null
            // since I could be loading values from the database but I guess you can do it here
            'attr' => ['disabled' => 'disabled'],
        ]
    );
$builder->addEventSubscriber(new ModelListener($this->extractor));

事件订户,可添加有效选择:

class ModelListener implements EventSubscriberInterface
{
    public function __construct(VehicleExtractorService $extractor)
    {
        $this->extractor = $extractor;
    }

    public static function getSubscribedEvents()
    {
        return [
            FormEvents::PRE_SUBMIT => 'onPreSubmitData',
        ];
    }

    public function onPreSubmitData(FormEvent $event)
    {
        // At this point you get only the scalar values, Model hasn't been transformed yet
        $data = $event->getData();
        $form = $event->getForm();

        $maker_id = $data['maker'];
            $model= $form->get('model');
            $options = $model->getConfig()->getOptions();

            if (!empty($maker_id)) {
                unset($options['attr']['disabled']);
                $options['choices'] = $this->extractor->getModelsFor($maker_id);

                $form->remove('model');
                $form->add('model', CarModelsSelectType::class, $options );
            }
        }
    }
}