EasyCorp / EasyAdminBundle

EasyAdmin is a fast, beautiful and modern admin generator for Symfony applications.
MIT License
4.09k stars 1.03k forks source link

Empty autocomplete field causes doctrine exception #1845

Closed acogent closed 7 years ago

acogent commented 7 years ago

Hello,

When i want to use autocomplete feature on an empty field, i have an exception like this when i want to save my entity :

An exception occurred while executing 'SELECT t0.ptg_no AS ptg_no_1,
t0.croquis_lettre AS croquis_lettre_2, t0.insee AS insee_3, t0.designation_cod
AS designation_cod_4, t0.rem_portage AS rem_portage_5, t0.carte_serie_cid AS
carte_serie_cid_6, ST_AsEWKB(t0.postgis_geom) AS postgis_geom_7,
t0.ptg_diffusion AS ptg_diffusion_8, t0.ptg_cid AS ptg_cid_9, t0.carte_no AS
carte_no_10, t0.designation AS designation_11, t0.remarque AS remarque_12,
ST_AsEWKB(t0.postgis_geom_wgs84) AS postgis_geom_wgs84_13, t0.maj_date AS
maj_date_14, t0.sit_cid AS sit_cid_15, t0.photo_diffusee_id AS
photo_diffusee_id_16 FROM rsgo.rsgo_ptg t0 WHERE t0.ptg_cid = ?' with params
[""]: SQLSTATE[22P02]: Invalid text representation: 7 ERREUR: syntaxe en entrée
invalide pour l'entier : « »

I don't know if i can easily surcharge Form/EventListener/EasyAdminAutocompleteSubscriber, but whith :

public function preSubmit(FormEvent $event)
    {
        $form = $event->getForm();
        if (null === $data = $event->getData()) {
            $data = array('autocomplete' => array());
            $event->setData($data);
        }
        $options = $form->get('autocomplete')->getConfig()->getOptions();

+        if ($data['autocomplete'] === '') {
+           $data['autocomplete'] = null;
+       }

        $options['choices'] = $options['em']->getRepository($options['class'])->findBy(array(
            $options['id_reader']->getIdField() => $data['autocomplete'],
        ));
        if (isset($options['choice_list'])) {
            // clear choice list for SF < 3.0
            $options['choice_list'] = null;
        }
        $form->add('autocomplete', LegacyFormHelper::getType('entity'), $options);
    }

It works.

Regards,

Armelle

javiereguiluz commented 7 years ago

@acogent thanks for reporting this issue!

@yceruto does the change proposed for preSubmit() look good to you? I think it's OK, but I'd like to double check. Thanks!

acogent commented 7 years ago

Yes, @yceruto, it solves my problem. Armelle

yceruto commented 7 years ago

Yes, I've improved the solution a bit https://github.com/javiereguiluz/EasyAdminBundle/pull/1848 avoiding useless DB query if the submitted data is empty. @acogent thanks!