10

我创建了一个自定义表单字段下拉列表,用于按年份过滤。我想做的一件事是允许用户按所有年份过滤,这是默认选项。我将其添加为empty_value. 但是,当我呈现表单时,它默认在第一个不是空值的项目上。空值就在那里,就在列表的上方。当页面最初加载时,如何使页面默认为“全部”?代码如下。

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;

class YearType extends AbstractType
{

  private $yearChoices;

  public function __construct()
  {
      $thisYear = date('Y');
      $startYear = '2012';

      $this->yearChoices = range($thisYear, $startYear);
  }

  public function getDefaultOptions(array $options)
  {
    return array(
        'empty_value' => 'All',
        'choices' => $this->yearChoices,
    );
  }

  public function getParent(array $options)
  {
    return 'choice';
  }

  public function getName()
  {
    return 'year';
  }
}

我正在用简单的树枝渲染我的表格{{ form_widget(filter_form) }}

4

2 回答 2

21

尝试添加empty_data选项到null,所以它是第一位的。我有很多这种类型的字段并且它正在工作,例如:

class GenderType extends \Symfony\Component\Form\AbstractType
{

    public function getDefaultOptions(array $options)
    {
        return array(
            'empty_data'  => null,
            'empty_value' => "Non specificato",
            'choices'     => array('m' => 'Uomo', 'f' => 'Donna'),
            'required'    => false,
        );
    }

    public function getParent(array $options) { return 'choice'; }

    public function getName() { return 'gender'; }

}

编辑:另一种可能性(我想)是设置preferred_choices。这样,您将获得顶部的“全部”选项。但我不知道它是否可以使用null empty_data,但您可以更改empty_data为您想要的任何内容:

  public function getDefaultOptions(array $options)
  {
    return array(
        'empty_value'       => 'All',
        'empty_data'        => null,
        'choices'           => $this->yearChoices,
        'preferred_choices' => array(null)         // Match empty_data
    );
  }
于 2012-08-06T19:48:50.017 回答
0

当我需要一个简单的城市下拉列表而不使用关系时,我最终将这个配置用于城市字段(添加 null 作为选择数组的第一个元素),因为empty_data参数对我不起作用:

$builder->add('city',
    ChoiceType::class,
    [
        'label'        => 'ui.city',
        'choices'      => array_merge([null], $this->cityRepository->findAll()),
        'choice_label' => static function (?City $city) {
            return null === $city ? '' : $city->getName();
        },
        'choice_value' => static function(?City $city) {
            return null === $city ? null : $city->getId();
        },
    ]);
于 2020-06-12T10:07:55.027 回答