使用自定义验证约束检查数据库中是否存在条目

时间:2022-09-25 23:55:40

So in my Symfony application I have an Entity called Post.

所以在我的Symfony应用程序中,我有一个名为Post的实体。

My Post Entity has the following properties: post_start,post_end and many more.

我的帖子实体具有以下属性:post_start,post_end等等。

ENTITY:

/**
 * @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 startdate and enddate and of cource from the same user.

当我提交表单时,我想检查数据库是否已经有一个具有相同startdate和enddate的条目以及来自同一用户的cource。

1. If YES -> Show error message 
2. If NO -> Create post request.

When the entry already exists, but it's from a different user, just go ahead and create the post.

当条目已经存在,但它来自不同的用户时,请继续创建帖子。

I wanted to do that with a custom validator constraint. But what happens 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();
}
    }
     }

1 个解决方案

#1


0  

@Max Trui, you have not mentioned how are the User and Post entities are related in your database.

@Max Trui,您还没有提到数据库中的User和Post实体是如何相关的。

If you have UserId in Post Entity, you can do Following.

如果您在Post Entity中有UserId,则可以执行以下操作。

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

you can replace 'post_start' with the dynamic fieldname value(post_start or post_end), which you can provide from where you call validator.

您可以使用动态fieldname值(post_start或post_end)替换'post_start',您可以从调用验证器的位置提供该值。

If you want to check for both dates at the same time, provide both values in validator.

如果要同时检查两个日期,请在验证程序中提供这两个值。

#1


0  

@Max Trui, you have not mentioned how are the User and Post entities are related in your database.

@Max Trui,您还没有提到数据库中的User和Post实体是如何相关的。

If you have UserId in Post Entity, you can do Following.

如果您在Post Entity中有UserId,则可以执行以下操作。

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

you can replace 'post_start' with the dynamic fieldname value(post_start or post_end), which you can provide from where you call validator.

您可以使用动态fieldname值(post_start或post_end)替换'post_start',您可以从调用验证器的位置提供该值。

If you want to check for both dates at the same time, provide both values in validator.

如果要同时检查两个日期,请在验证程序中提供这两个值。