0

estoy intentando replicar el ejemplo del manual de Sumfony:

https://symfony.com/doc/5.4/form/dynamic_form_modification.html#form-events-submitted-data

Para ello dispongo de 3 entidades. La primera "Addresses" representa una dirección que dispone como clave foránea la ciudad "Cities" y la provincia "Provinces".

<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Addresses
 *
 * @ORM\Table(name="Addresses", indexes={@ORM\Index(name="IX_Addresses_AddressTypeId", columns={"AddressTypeId"}), @ORM\Index(name="IX_Addresses_AssociationProcuratorId", columns={"AssociationProcuratorId"}), @ORM\Index(name="IX_Addresses_CityId", columns={"CityId"}), @ORM\Index(name="IX_Addresses_ProvinceId", columns={"ProvinceId"}), @ORM\Index(name="IX_Addresses_WayTypeId", columns={"WayTypeId"})})
 * @ORM\Entity
 * @ORM\Entity(repositoryClass="App\Repository\AddressesRepository")
 */
class Addresses
{
    /**
     * @var binary
     *
     * @ORM\Column(name="AddressId", type="binary", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $addressid;

    /**
     * @var \Cities
     *
     * @ORM\ManyToOne(targetEntity="Cities")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="CityId", referencedColumnName="CityId")
     * })
     */
    private $cityid;

    /**
     * @var string|null
     *
     * @ORM\Column(name="Door", type="string", length=50, nullable=true)
     */
    private $door;

    /**
     * @var string|null
     *
     * @ORM\Column(name="Floor", type="string", length=50, nullable=true)
     */
    private $floor;

    /**
     * @var string|null
     *
     * @ORM\Column(name="FullAddress", type="text", length=0, nullable=true)
     */
    private $fulladdress;

    /**
     * @var bool
     *
     * @ORM\Column(name="IsPublic", type="boolean", nullable=false)
     */
    private $ispublic;

    /**
     * @var bool
     *
     * @ORM\Column(name="IsReceivingMagazine", type="boolean", nullable=false)
     */
    private $isreceivingmagazine;

    /**
     * @var string|null
     *
     * @ORM\Column(name="MailBox", type="string", length=20, nullable=true)
     */
    private $mailbox;

    /**
     * @var string|null
     *
     * @ORM\Column(name="Stairway", type="string", length=50, nullable=true)
     */
    private $stairway;

    /**
     * @var string|null
     *
     * @ORM\Column(name="WayName", type="string", length=100, nullable=true)
     */
    private $wayname;

    /**
     * @var string|null
     *
     * @ORM\Column(name="WayNumber", type="string", length=50, nullable=true)
     */
    private $waynumber;

    /**
     * @var string|null
     *
     * @ORM\Column(name="ZipCode", type="string", length=14, nullable=true)
     */
    private $zipcode;

    /**
     * @var string|null
     *
     * @ORM\Column(name="BuildingName", type="string", length=100, nullable=true)
     */
    private $buildingname;

    /**
     * @var \Addresstypes
     *
     * @ORM\ManyToOne(targetEntity="Addresstypes")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="AddressTypeId", referencedColumnName="TypeId")
     * })
     */
    private $addresstypeid;

    /**
     * @var \Associationprocurators
     *
     * @ORM\ManyToOne(targetEntity="Associationprocurators")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="AssociationProcuratorId", referencedColumnName="AssociationProcuratorId")
     * })
     */
    private $associationprocuratorid;

    /**
     * @var \Provinces
     *
     * @ORM\ManyToOne(targetEntity="Provinces")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="ProvinceId", referencedColumnName="ProvinceId")
     * })
     */
    private $provinceid;

    /**
     * @var \Waytypes
     *
     * @ORM\ManyToOne(targetEntity="Waytypes")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="WayTypeId", referencedColumnName="TypeId")
     * })
     */
    private $waytypeid;

Entidad Provinces

<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Provinces
 *
 * @ORM\Table(name="Provinces")
 * @ORM\Entity
 * @ORM\Entity(repositoryClass="App\Repository\ProvincesRepository")
 */
class Provinces
{
    /**
     * @var string
     *
     * @ORM\Column(name="ProvinceId", type="string", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $provinceid;

    /**
     * @var string|null
     *
     * @ORM\Column(name="ProvinceCode", type="string", length=2, nullable=true)
     */
    private $provincecode;

    /**
     * @var string|null
     *
     * @ORM\Column(name="ProvinceName", type="string", length=30, nullable=true)
     */
    private $provincename;


    /**
     * @var  ArrayCollection<Cities>
     * @ORM\OneToMany(targetEntity="Cities", mappedBy="provinceid", fetch="LAZY")
    */
    private $cities;

Entidad Cities

<?php

namespace App\Entity;

use App\Entity\Provinces;
use Doctrine\ORM\Mapping as ORM;

/**
 * Cities
 *
 * @ORM\Table(name="Cities", indexes={@ORM\Index(name="IX_Cities_ProvinceId", columns={"ProvinceId"})})
 * @ORM\Entity
 * @ORM\Entity(repositoryClass="App\Repository\CitiesRepository")
 */
class Cities
{
    /**
     * @var string
     *
     * @ORM\Column(name="CityId", type="string", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $cityid;

    /**
     * @var string
     *
     * @ORM\Column(name="CityCode", type="string", length=12, nullable=false)
     */
    private $citycode;

    /**
     * @var string
     *
     * @ORM\Column(name="CityName", type="string", length=30, nullable=false)
     */
    private $cityname;

    /**
     * @var \Provinces
     *
     * @ORM\ManyToOne(targetEntity="Provinces", inversedBy="cities")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="ProvinceId", referencedColumnName="ProvinceId")
     * })
     */
    private $provinceid;

He creado mi FormType:

<?php
namespace App\Entity\Form;
use App\Entity\Addresses;
use App\Entity\Provinces;
use App\Entity\Cities;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\OptionsResolver\OptionsResolver;


class AddressFormType extends AbstractType
{


   public function buildForm(FormBuilderInterface $builder, array $options) : void
    {
        $builder
        ->add('provinceid',  EntityType::class, array(
            'class' => Provinces::class,
            'placeholder' => 'Elige uno...',
            
        ))
        ;
        


        $formModifier = function ( FormInterface $form, Provinces $province = null) {
            
            $cities = null === $province ? [] : $province->getCities();
            $form->add('cityid', EntityType::class, array(
                'class' => Cities::class,
                'placeholder' => 'Elige uno...',
                'choices'     => $cities,
            ));
        };    


        $builder->addEventListener(
            FormEvents::PRE_SET_DATA,
            function (FormEvent $event) use ($formModifier) {
                // this would be your entity, i.e. SportMeetup
                $address = $event->getData();
                //var_dump($event->getData());
                $formModifier($event->getForm(), $address->getProvinceid());
            }
        );


        $builder->get('provinceid')->addEventListener(

            FormEvents::POST_SUBMIT,
            function (FormEvent $event) use ($formModifier) {
                var_dump($event);
                // It's important here to fetch $event->getForm()->getData(), as
                // $event->getData() will get you the client data (that is, the ID)
                $province = $event->getForm()->getData();

                
                // since we've added the listener to the child, we'll have to pass on
                // the parent to the callback functions!
                $formModifier($event->getForm()->getParent(), $province);
            }
        );    






    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => Addresses::class,
            'include_published_at' => false,
        ]);
    }
    

}

La vista :

          {{ form_start(form_address) }}

          {{ form_row(form_address.provinceid) }} 

          {{ form_row(form_address.cityid) }} 

          {{ form_end(form_address) }}


          <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
          <script>
             var $province = $('#address_form_provinceid');
             $province.change(function() {
                var $form = $(this).closest('form');
                var data = {};
                data[$province.attr('name')] = $province.val();
                $.ajax({
                   url : $form.attr('action'),
                   type: $form.attr('method'),
                   data : data,
                   complete: function(html) {
                         $('#address_form_cityid').replaceWith(
                            $(html.responseText).find('#address_form_cityid')
                         );
                   }
                });
             });
          </script>

El problema es que en ningún caso se recarga el desplegable de las ciudades. Nunca se llega a ejecutar la función dentro del EventListener del POST_SUBMIT

¿Alguna idea?

Muchas gracias

1 respuesta 1

0

Finalmente el problema estaba en el Controller. Todo el código del formulario está correcto. El problema era que faltaba el handler del request:

        $address = new Addresses();
        $form_address = $this->createForm(AddressFormType::class, $address);
        $form_address->handleRequest($request);  // Si no hay manejador no captura los EventLister

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.