我正在对实体中的属性使用@Assert\Choice
验证。
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;
}
从ApplicationQuestion
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;
}
}
如何在插入之前访问validator
服务以验证assert
条件。所以想在ApplicationQuestionRepository
$this->get('validator')->validate($question);
但不确定如何在自定义存储库中注入validator
服务。
由于
答案 0 :(得分:0)
最好创建一个使用实体管理器和验证器服务作为依赖关系的服务。称之为ApplicationQuestionService或类似的东西。
然后,您拥有验证和保存问题所需的所有依赖项。
或者您可以查看工厂:http://symfony.com/doc/current/components/dependency_injection/factories.html