<?php
declare(strict_types=1);
namespace App\Form\Type\UserAlertStock;
use App\Entity\UserAlertStock\AvailabilityNotifier;
use Sylius\Bundle\ResourceBundle\Form\Type\AbstractResourceType;
use Sylius\Component\Channel\Context\ChannelContextInterface;
use Sylius\Component\Core\Model\ProductVariantInterface;
use Sylius\Component\Locale\Context\LocaleContextInterface;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\NotBlank;
final class AvailabilityNotifierType extends AbstractResourceType
{
private LocaleContextInterface $localeContext;
private ChannelContextInterface $channelContext;
public function __construct(
string $dataClass,
array $validationGroups,
LocaleContextInterface $localeContext,
ChannelContextInterface $channelContext
) {
parent::__construct($dataClass, $validationGroups);
$this->localeContext = $localeContext;
$this->channelContext = $channelContext;
}
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->add('emailCustomer', EmailType::class, [
'label' => 'app.ui.email_address',
'constraints' => [
new NotBlank([
'message' => 'app.customer_email.not_blank',
]),
]
])
->addEventListener(FormEvents::POST_SUBMIT, [$this, 'onPostSubmit']);
}
public function onPostSubmit(FormEvent $event): void
{
$form = $event->getForm();
$productVariant = $form->getConfig()->getOption('productVariant');
/** @var AvailabilityNotifier $data */
$data = $event->getData();
$data->setStatus(false);
$data->setLocaleCode($this->localeContext->getLocaleCode());
$data->setChannel($this->channelContext->getChannel());
if($productVariant === null){
return;
}
$data->setProductVariant($productVariant);
}
public function configureOptions(OptionsResolver $resolver): void
{
parent::configureOptions($resolver);
$resolver
->setDefined([
'productVariant',
])
->setAllowedTypes('productVariant', ProductVariantInterface::class)
;
}
public function getBlockPrefix(): string
{
return 'app_availability_notifier';
}
}