Создаю VehicleType:

class VehicleType extends AbstractType {

    public function buildForm(FormBuilderInterface $builder, array $options) {
        $builder
                ->add('name')
                ->add('user', EntityType::class, [
                    'class' => User::class,
                    'choice_label' => 'email',
                ])
                ->add('vehicleBrand', EntityType::class, [
                    'placeholder' => 'Choose an vehicle brand',
                    'class' => VehicleBrand::class,
                    'choice_label' => 'name',
                    "attr" => array(
                        "class" => "form-control"
                    )
                ])
                ->add('vehicleModel', EntityType::class, array(
                    'placeholder' => 'Choose an vehicle model',
                    'class' => VehicleModel::class,
                    'choice_label' => 'name',
                    'multiple' => false,
                    'expanded' => false,
                ))
        ;

        $formModifier = function (FormInterface $form, VehicleBrand $vehicleBrand = null) {
            $models = null === $vehicleBrand ? array() : $vehicleBrand->getVehicleModels();
            $form->add('vehicleModel', EntityType::class, array(
                'placeholder' => 'Choose an option',
                'class' => VehicleModel::class,
                'choice_label' => 'name',
                'choices' => $models,
                'multiple' => false,
                'expanded' => false,
            ));
        };

        $builder->addEventListener(
                FormEvents::PRE_SET_DATA, function (FormEvent $event) use ($formModifier) {
            $data = $event->getData();
            $brand = null !== $data->getVehicleBrand() ? $data->getVehicleBrand() : null !== $data->getVehicleModel() ? $data->getVehicleModel()->getBrand() : null;
            $formModifier($event->getForm(), $brand);
            if (!$data->getVehicleBrand() && $data->getVehicleModel()) {
                $event->getForm()->add('vehicleBrand', EntityType::class, [
                    'placeholder' => 'Choose an option',
                    'class' => VehicleBrand::class,
                    'choice_label' => 'name',
                    "attr" => array(
                        "class" => "form-control"
                    ),
                    'data' => $data->getVehicleModel()->getBrand()
                ]);
            }
        }
        );

        $builder->get('vehicleBrand')->addEventListener(
                FormEvents::POST_SUBMIT, function (FormEvent $event) use ($formModifier) {
            $brand = $event->getForm()->getData();
            $formModifier($event->getForm()->getParent(), $brand);
        }
        );
    }

}

Javascript для обновления модели автомобиля после выбора марки автомобиля:

$('#vehicle_vehicleBrand').on('change', function () {
    var brandId = this.value;
    if (brandId < 1) {
        $("#vehicle_vehicleModel").prop('disabled', 'disabled');
        return;
    }
    $.getJSON("/api/v2/vehiclemodels/" + brandId + "/brands.json", function (j) {
        var options = '<option value="0">' + $("#vehicle_vehicleModel option:first").text() + '</option>';
        for (var i = 0; i < j.length; i++) {
            options += '<option value="' + j[i].id + '">' + j[i].name + '</option>';
        }
        $("#vehicle_vehicleModel").removeAttr("disabled");
        $('#vehicle_vehicleModel').html(options);
    });
});

Этот код очень сложный, но он почти работает

Я могу создать новый автомобиль, я могу редактировать автомобиль той же марки, но когда я меняю марку и выбираю новую модель автомобиля, я вижу ошибку « Это значение недействительно ».

Что происходит? Может быть, мне добавить новый тип событий формы?

Спасибо за помощь

0
Pionas 19 Окт 2019 в 00:08

1 ответ

Лучший ответ

Я нашел решение:

class VehicleType extends AbstractType {

    public function buildForm(FormBuilderInterface $builder, array $options) {
        $builder
                ->add('name')
                ->add('user', EntityType::class, [
                    'class' => User::class,
                    'choice_label' => 'email',
                ])
                ->add('vehicleBrand', EntityType::class, [
                    'placeholder' => 'Choose an vehicle brand',
                    'class' => VehicleBrand::class,
                    'choice_label' => 'name',
                    "attr" => array(
                        "class" => "form-control"
                    )
                ])
                ->add('vehicleModel', EntityType::class, array(
                    'placeholder' => 'Choose an vehicle model',
                    'class' => VehicleModel::class,
                    'choice_label' => 'name',
                    'multiple' => false,
                    'expanded' => false,
                ))
        ;

        $formModifier = function (FormInterface $form, VehicleBrand $vehicleBrand = null) {
            $models = null === $vehicleBrand ? array() : $vehicleBrand->getVehicleModels();
            $form->add('vehicleModel', EntityType::class, array(
                'placeholder' => 'Choose an option',
                'class' => VehicleModel::class,
                'choice_label' => 'name',
                'choices' => $models,
                'multiple' => false,
                'expanded' => false,
            ));
        };

        $builder->addEventListener(
                FormEvents::PRE_SET_DATA, function (FormEvent $event) use ($formModifier) {
            $data = $event->getData();
            $vehicleModelBrand = null !== $data->getVehicleModel() ? $data->getVehicleModel()->getBrand() : null;
            $vehicleBrand = null !== $data->getVehicleBrand() ? $data->getVehicleBrand() : null;
            $brand = null !== $vehicleModelBrand ? $vehicleModelBrand : $vehicleBrand;
            $formModifier($event->getForm(), $brand, $data->getVehicleModel());
            $data->setVehicleBrand($brand);
        }
        );

        $builder->get('vehicleBrand')->addEventListener(
                FormEvents::POST_SUBMIT, function (FormEvent $event) use ($formModifier) {
            $brand = $event->getForm()->getData();
            $formModifier($event->getForm()->getParent(), $brand);
        }
        );
    }

}

Спасибо за помощь :)

0
Pionas 22 Окт 2019 в 04:28