Symfony Forms EntityType Select 全部使用 JS

Symfony Forms EntityType Select All using JS

在我的网页上,我使用的是带有 EntityType class 的 Symfony 表单。我想创建一个额外的按钮,在单击时从此下拉列表中选择所有项目。这可能使用 JavaScript / JQuery 吗?简单地更改自动生成的 HTML 是行不通的。

FormType.php:

->add('item', EntityType::class, [
   'class' => Item::class,
   'choice_label' => function(Item $item) {
      return sprintf('%s', $item->getName());
    },
    'label' => 'Staff',
    'multiple' => true,

我认为类似的东西可以解决问题:

<!-- Somewhere in your Twig file : -->
<button id="check-all-options">Check all !</button>
document.querySelector('#check-all-options').addEventListener('click', () => {
  // Select all the options of your <select> tag
  const options = document.querySelectorAll('#form_item option');

  // Loop on all the options and pass them to selected ✅
  options.forEach(option => option.selected = true);
});

如果有帮助请告诉我:)