clem
clem

Reputation: 897

Symfony 3: How can I implement an EntityType in Form with a lot of objects?

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

Upvotes: 2

Views: 1395

Answers (2)

clem
clem

Reputation: 897

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.

Upvotes: 1

Fabien Salles
Fabien Salles

Reputation: 1201

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

Upvotes: 1

Related Questions