How do you default to the empty_value choice in a custom symfony form field type?

Viewed 26978

I have a created a custom form field dropdown list for filtering by year. One of the things I want to do is to allow the user to filter by all years, which is the default option. I am adding this as an empty_value. However, when I render the form, it defaults on the first item that's not the empty value. The empty value is there, just above it in the list. How do I make the page default to, in my case 'All' when the page initially loads? Code is below.

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';
  }
}

I'm rendering my form in twig with a simple {{ form_widget(filter_form) }}

2 Answers

When I've needed a simple cities dropwdown from database without using relations, I've ended up using this config for city field (adding null as first element of choices array), as empty_data param didn't do work for me:

$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();
        },
    ]);
Related