<?php
namespace App\Form;
use App\Entity\Customer;
use App\Repository\CustomerRepository;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Validator\Constraints\NotBlank;
class LoginType extends AbstractType
{
private $customerRepository;
public function __construct(CustomerRepository $customerRepository)
{
$this->customerRepository = $customerRepository;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$customers = $this->customerRepository->findBy(array('deleted_at' => NULL));
$builder
->add('customer', ChoiceType::class, [
'choices' => $customers,
// string value that will be submitted by the form
'choice_value' => 'customer_name',
'choice_label' => function($customer, $key, $index) {
// var_dump($customer);
// Result : int(0)
return $customer->getCustomerName();
// Exception !
},
'choice_attr' => function($customer, $key, $index) {
return ['class' => $customer->getId()];
},
'constraints' => array(
new NotBlank(['groups' => ['form_validation_only']]),
),
])
->add('save', SubmitType::class, array('label' => 'Login'))
;
}
public function setDefaultOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'validation_groups' => ['form_validation_only'],
));
}
}