Check if a database entry exists with a custom validation constraint

So, in my Symfony app, I have Entity called Post.

My Post Entity has the following properties: post_start, post_endand many others.

FACE:

/**
 * @ORM\Entity
 * @ORM\Table(name="post")
 */
class Post
{

    /**
     * @var int
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @var DateType
     * @ORM\Column(type="date")
     */
    private $post_start;

    /**
     * @var DateType
     * @ORM\Column(type="date")
     * @Assert\GreaterThanOrEqual(propertyPath="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:

/**
 * @Annotation
 */
class ContainsEqualDate extends Constraint
{
    public $message = 'Post request is already exists.';

    public function getTargets()
    {
        return self::CLASS_CONSTRAINT;
    }
}

ContainsEqualDateValidator:

class ContainsEqualDateValidator extends ConstraintValidator
{
    /**
     * @var ORMUserRepository
     */
    private $userRepository;

    /**
     * @var ORMPostRepository
     */
    private $postRepository;

    /**
     * @param ORMUserRepository $userRepository
     * @param ORMPostRepository $postRepository
     */
    public function __construct(ORMUserRepository $userRepository, ORMPostRepository $postRepository)
    {
        $this->userRepository = $userRepository;
        $this->postRepository = $postRepository;
    }

    /**
     * Checks if the passed value is valid.
     *
     * @param mixed $value The value that should be validated
     * @param Constraint $constraint The constraint for the validation
     */
    public function validate($value, Constraint $constraint)
    {

 $userId = $this->getUser();

    $postExists = $this->postRepository->findBy(array(
        'post_start' => $value,
        'app_user_id' => $userId
    ));
}

/**
 * @return User
 */
private function getUser(): User
{
    return $this->storage->getToken()->getUser();
}
    }
     }
+4
source share
1

@Max Trui, , User Post .

UserId Post Entity, .

$userId = $this->userRepository->getUser()->getId();
$entryExists = ($this->postRepository->findBy(array('post_start' => $value, 'user_id' => $userId)) == null) ? true : false;

"post_start" (post_start post_end), , .

, .

+1

Source: https://habr.com/ru/post/1692267/


All Articles