2

I have an entity City with more than 30000 objects stored. User is able to add an Address object with a relation ManyToOne to City. But during Form building, the rendering of <input> type radio or select is not appropriate for the number of objects...

I use the following implementation code (it is a snippet):

public function buildForm(FormBuilderInterface $builder, array $options)
{
  /* Pattern to get cities */
  $pattern = 'Bor%';  //I use this filter to reduce the number of objects but not sufficient

  $builder
    ->add('city', EntityType::class, array(
      'class'        => 'AppPlatformBundle:City',
      'choice_label' => 'name',
      'multiple'     => false,
      'expanded'     => true,
      'query_builder'=> function(CityRepository $repository) use($pattern) {
        return $repository->getCitiesWithPattern($pattern);
      }));
}

I think that a solution is to use a TextType where the proposals can be selected by the user when he start type anything. But I haven't idea on how implement this.

Do you have a solution on my issue please?

Thank you

clem
  • 799
  • 9
  • 20
  • 1
    Possible duplicate of [Adding JQuery Autocomplete in Symfony2 Entity field](https://stackoverflow.com/questions/32334289/adding-jquery-autocomplete-in-symfony2-entity-field) – Fabien Salles Oct 25 '17 at 14:33

2 Answers2

1

With this steps :

  1. Create a custom form type inheriting from a simple TextType
  2. Use this custom form type with a javascript autocomplete plugin and an ajax call
  3. Create your custom action in order to retrieve your choices for your select box (created by the plugin)
  4. Use a Data Transformer in your custom form type in order to retrieve objects instead of values
Fabien Salles
  • 1,101
  • 15
  • 24
1

Thank you so much Fabien.

I was able to implement a good solution for me :)

So for anyone interrested by my solution:

I define city field as HiddenField like:

  $builder
    ->add('city', HiddenType::class);

I use a Data Transformer to convert City object into unique Id (field Id of the object)

In Twig template, I implement jQuery-ui Autocomplete

In backend, I create a route able to return a Json response with all cities filtered by the term of jQuery plugin.

In frontend, I develop a jquery script that append a new field "city" with type Text and autocomplete action.

When response is received, I fill the field city with type Hidden with the id.

clem
  • 799
  • 9
  • 20