So, in my Symfony app, I have Entity called Post
.
My Post Entity has the following properties:
post_start
, post_end
and many others.
FACE:
class Post
{
private $id;
private $post_start;
private $post_end;
.....
}
FORMTYPE:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add(
'post_start',
DateType::class,
[
'widget' => 'single_text',
'format' => 'dd.MM.yyyy',
'required' => true,
'attr' => [
'class' => 'form-control input-inline datepicker',
'data-provide' => 'datepicker',
'data-date-format' => 'dd.mm.yyyy',
]
]
);
$builder->add(
'post_end',
DateType::class,
[
'widget' => 'single_text',
'format' => 'dd.MM.yyyy',
'required' => true,
'attr' => [
'class' => 'form-control input-inline datepicker',
'data-provide' => 'datepicker',
'data-date-format' => 'dd.mm.yyyy'
]
]
);
$builder->add('submit', SubmitType::class, [
'label' => 'save post',
'attr' => array('class' => 'btn btn-success')
]);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Post::class
]);
}
When I submit the form, I want to check if the database already has an entry with the same start and end date and taking into account the same user.
1. If YES -> Show error message
2. If NO -> Create post request.
When the record already exists, but it is from another user, just start and create a message.
I wanted to do this with a special validator constraint. But what comes next, I have to somehow compare the data with each other.
ContainsEqualDate:
class ContainsEqualDate extends Constraint
{
public $message = 'Post request is already exists.';
public function getTargets()
{
return self::CLASS_CONSTRAINT;
}
}
ContainsEqualDateValidator:
class ContainsEqualDateValidator extends ConstraintValidator
{
private $userRepository;
private $postRepository;
public function __construct(ORMUserRepository $userRepository, ORMPostRepository $postRepository)
{
$this->userRepository = $userRepository;
$this->postRepository = $postRepository;
}
public function validate($value, Constraint $constraint)
{
$userId = $this->getUser();
$postExists = $this->postRepository->findBy(array(
'post_start' => $value,
'app_user_id' => $userId
));
}
private function getUser(): User
{
return $this->storage->getToken()->getUser();
}
}
}