symfonysymfony4symfony2-easyadmineasyadmin

Set easyadmin_autocomplete Select Null by default. Symfony


I would like to know if there is any way to put null value by default in the easyadmin_autocomplete select.

The first item in the list is selected and filled with data from database but i need a null value by default and setted automaticly. The goal is a first result point to an empty one (Choose one...).

Do you know how to do it?

Can you think of any way combining the options defined below?

#easy_admin.yml
Product:
      class: App\Entity\Product
      controller: App\Controller\ProductController
      new:
        fields:
          - { property: 'category', label: 'Category', type: 'easyadmin_autocomplete', type_options: { class: 'App\Entity\Category' } }
 }

In this example, one select has a placeholder with the text 'Any' (Ninguno). I need to know why is handling them different. form_pic These are the options defined for the attr fields -> type_options of the yml:

  1. action
  2. allow_extra_fields
  3. allow_file_upload
  4. attr
  5. auto_initialize
  6. block_name
  7. by_reference
  8. class
  9. compound
  10. constraints
  11. csrf_field_name
  12. csrf_message
  13. csrf_protection
  14. csrf_token_id
  15. csrf_token_manager
  16. data
  17. data_class
  18. disabled
  19. empty_data
  20. error_bubbling
  21. error_mapping
  22. extra_fields_message
  23. help
  24. help_attr
  25. inherit_data
  26. invalid_message
  27. invalid_message_parameters
  28. label
  29. label_attr
  30. label_format
  31. mapped
  32. method
  33. multiple
  34. post_max_size_message
  35. property_path
  36. required
  37. translation_domain
  38. trim
  39. upload_max_size_message
  40. validation_groups

Solution

  • If setting your default value would be a solution for you (like zero), service listener might be an answer:

    // You need to add this listener yourself:
    class ProductServiceListener
    {
        ...
    
        // you can manipulate entity in this level as you wish:
        public function preUpdate(LifeCycleEventArgs $args)
        {
    
           // You will focus to Product entity, so block others:
           if (!(get_class($entity) == 'App\Entity\Product')) {
               return;
            }
    
            // Set whatever default value you want if it's null:
            if($entity->getCategory() == null) {
               $entity->setCategory(0); // Zero, as an example.
            }