简体   繁体   中英

How to access validator service in custom repository in Symfony

I'm using @Assert\\Choice validation for a property in an entity.

ApplicationQuestion.php

<?php

/**
 * ApplicationQuestion
 *
 * @ORM\Table(name="j_application_questions")
 * @ORM\Entity(repositoryClass="JobsBundle\Repository\ApplicationQuestionRepository")
 * @ExclusionPolicy("all")
 */
class ApplicationQuestion
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     * @Expose()
     */
    private $id;

    /**
     * @var string
     * @Column(type="string", length=20)
     * @Assert\Choice(choices={"free_text","boolean", "multiple_choice", "video"}, message="Choose a valid answer type")
     * @Expose()
     */
    protected $answer_type;

}

Creating a new ApplicationQuestion from ApplicationQuestionRepository

ApplicationQuestionRepository.php

<?php
class ApplicationQuestionRepository extends EntityRepository
{
    /**
     * @param $data
     * @param Job $job
     * @return bool|ApplicationQuestion
     */
    private function createNewQuestion($data, Job $job)
    {
        if( $data['answer_type'] == 'multiple_choice' && !array_key_exists('answer_choices', $data) ){
            return false;
        }

        $question = new ApplicationQuestion();
        $question
            ->setJob($job)
            ->setQuestion($data['question'])
            ->setAnswerType($data['answer_type'])
            ->setQuestionFor('job_application')
            ;
        if( $data['answer_type'] == 'multiple_choice' )
            $question->setAnswerChoices($data['answer_choices']);

        return $question;
    }

}

How go I access the validator service to validate for assert condition before inserting. So want to do something like this in ApplicationQuestionRepository

$this->get('validator')->validate($question);

but not sure how to inject the validator service inside the custom repository.

Thanks

Better to create a service that uses the entity manager and your validator service as a dependency. Call it ApplicationQuestionService or something like that.

You then have all the dependencies you need for validating and saving your question.

Alternatively you could look at a factory: http://symfony.com/doc/current/components/dependency_injection/factories.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM