<?php
|
declare(strict_types=1);
|
|
namespace App\Form;
|
|
use App\Enum\LabelType;
|
use Symfony\Component\Form\AbstractType;
|
use Symfony\Component\Form\Extension\Core\Type\EnumType;
|
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\Callback;
|
use Symfony\Component\Validator\Constraints\Length;
|
use Symfony\Component\Validator\Constraints\NotBlank;
|
use Symfony\Component\Validator\Context\ExecutionContextInterface;
|
|
/**
|
* @extends AbstractType<array{type: LabelType, label: string}>
|
*/
|
class AddLabelType extends AbstractType {
|
public function buildForm(FormBuilderInterface $builder, array $options): void {
|
$builder
|
->add('type', EnumType::class, [
|
'class' => LabelType::class,
|
'label' => 'label_type_header',
|
'choice_label' => static fn(LabelType $type): string => 'label_type_' . $type->value,
|
])
|
->add('label', TextType::class, [
|
'label' => 'label_header',
|
'constraints' => [new NotBlank(), new Length(max: 255)],
|
])
|
->add('save', SubmitType::class, ['label' => 'label_action_add']);
|
}
|
|
public function configureOptions(OptionsResolver $resolver): void {
|
$resolver->setDefaults([
|
'constraints' => [new Callback(self::validateFormat(...))],
|
]);
|
}
|
|
/**
|
* @param array{type: ?LabelType, label: ?string} $data
|
*/
|
public static function validateFormat(array $data, ExecutionContextInterface $context): void {
|
$type = $data['type'];
|
|
if ($type !== null && !$type->isValid($type->normalize((string)$data['label']))) {
|
$context->buildViolation('label_invalid_number')->setTranslationDomain('messages')->atPath('[label]')->addViolation();
|
}
|
}
|
}
|