I have created a custom form type in Symfony 5. This is the class:
namespace App\Form;
use App\Entity\Product;
use App\Entity\Species;
use App\Repository\SpeciesRepository;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class ProductUploadType extends AbstractType
{
private $speciesRepository;
public function __construct(SpeciesRepository $speciesRepository)
{
$this->speciesRepository = $speciesRepository;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('species', ChoiceType::class, [
'choices' => $this->speciesRepository->findAll(),
'choice_value' => 'name',
'choice_label' => function (Species $species) {
return ucwords($species->getName());
},
'label_attr' => ['class' => 'label'],
'mapped' => false,
]);
$builder->add('title', TextType::class, [
'attr' => ['class' => 'input'],
'label_attr' => ['class' => 'label'],
]);
$builder->add('upload', SubmitType::class, [
'attr' => ['class' => 'button is-primary'],
]);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Product::class,
]);
}
}
It produces the following output (other fields are cut down due to simplicity):
<select id="product_upload_species" name="product_upload[species]">
<option value="photo">Photo</option>
<option value="video">Video</option>
</select>
But I want something like this:
<select id="product_upload_species" name="product_upload[species]">
<option disabled selected>-- Choose One --</option>
<option value="photo">Photo</option>
<option value="video">Video</option>
</select>
With my current implementation (and also by not using form theme), how can I achieve my expectation?
Thanks in advance.