EasyCorp / EasyAdminBundle

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

Disallow clear in AssociationField #5161

Open itomxi opened 2 years ago

itomxi commented 2 years ago

Short description of what this feature will allow to do: There is no reason to show clear buttons f.e. for OneToMany field where the other side is not nullable.

Example of how to use this feature

AssociationField::new('marks')->setFormTypeOptions([ 'attr.data-ea-allow-clear' => 'false' ])

fabienlem commented 2 years ago

Hello @itomxi,

Use the following:

AssociationField::new('marks')->setFormTypeOption('attr', ['data-ea-allow-clear' => 'false']);

Kind regards

itomxi commented 2 years ago

Hi @fabienlem, Thank you for your idea, unfortunately id doesn't work. I can see data-ea-allow-clear="false" using inspector on the select. But clear buttons are still there.

I was wondering, where did you find this option? There is only one mention of allow-clear in the whole codebase, and not in this context (I am using version 4.0.4).

fabienlem commented 2 years ago

My bad! I thought data-ea-allow-clear (from your original post) was an existing option and you didn't know how to pass it to the view.

I didn't see such feature in the javascript plugin documentation: https://tom-select.js.org/

itomxi commented 2 years ago

Hi, tom-select doesn't show clear button in items by default. It must be enabled via plugin remove_button. It looks like it is enabled in autocomplete.js using

if (null !== element.getAttribute('multiple')) { config.plugins.remove_button = { title: '' }; }

This approach is wrong, since it doesn't look whether the relation can or cannot be nullable.

Any ideas what to do? I would suggest adding the mentioned data-ea-allow-clear and altering autocomplete.js to look for it.

Jamie-Vandenbalck commented 2 years ago

I've the same problem. When setting an AssociationField as required (->setRequired(true)), it does not set the required attribute on the select element.

The comparison in assets/js/autocomplete.js on line 36 is thus for this occasions pointless:

if (null === element.getAttribute('required') && null === element.getAttribute('disabled')) {
   config.plugins.clear_button = { title: '' };
}
Natizyskunk commented 1 month ago

Don't know if it can help anyone esle but I've been able to make required. If you still need the field to be required / not empty on a OneToMany AssociationField, use ->setFormTypeOption('attr', ['required' => 'required']) on the field. and it should do the trick, the clear button will be hidden.

Credits : StackOverflowk - Add empty value to associationfield in easyadminbundle, first answer from @select0r.