<?php
namespace App\Form;
use App\Entity\Subscription;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
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;
use Symfony\Component\Validator\Constraints\Email;
use Symfony\Component\Validator\Constraints\NotBlank;
class SubscriptionType extends AbstractType
{
public function __construct(private string $countriesJsonFile)
{}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('countryCode', ChoiceType::class, [
'required' => true,
'choices' => $this->getCountriesOptions(),
'attr' => [
'placeholder' => 'choose an option',
'class'=>'form-control'
],
/*
'choice_label' => function($item){
$data = (array) $item;
return sprintf('%s %s', $data['dial_code'], $data['name']);
},
*/
'choice_value' => function($item){
return $item;
} ,
'constraints' => [
new NotBlank()
],
'data'=>'United States'
]
)
->add('phoneNumber', TextType::class, [
'required' => true,
'attr' => [
'placeholder' => 'Phone',
'class'=>'form-control'
],
'constraints' => [
new NotBlank()
],
]
)
->add('email', EmailType::class, [
'attr' => [
'placeholder' => 'Enter your email',
'class'=> 'form-control mb-3'
],
'constraints' => [
new Email(['message' => 'Invalid email address.'])
],
])
->add('optIn', CheckboxType::class, [
'required'=>false,
'label' => 'Keep me up to date on news and offers',
'attr' => [
'class' => 'form-check-input'
]
])
->add('submit', SubmitType::class, [
'label' => 'Subscribe Now',
'attr' => [
'class'=>'btn btn-primary btn-primary-fast'
]
])
;
}
private function getCountriesOptions(): array
{
$countries = json_decode(file_get_contents($this->countriesJsonFile, true));
$data = [];
foreach($countries as $country){
$country = (array)$country;
$data[$country['dial_code'].' '.$country['name']] = $country['name'];
}
return $data;
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'data_class' => Subscription::class
]);
}
}