我有一个名为 ClassSubject 的实体,你可以看到它,
/**
* ClassSubject
*
* @ORM\Table(name="class_subject")
* @ORM\Entity(repositoryClass="PIE10Bundle\Repository\ClassSubjectRepository")
*
* @UniqueEntity( fields={"class", "subjects"},
* errorPath="subjects",
* message="This subject is already added"
* )
*/
class ClassSubject
{
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var int
*
* @ORM\ManyToOne(targetEntity="Classes")
* @ORM\JoinColumn(name="class_id", referencedColumnName="id")
*/
private $class;
/**
* @var int
*
* @ORM\ManyToOne(targetEntity="Subject")
* @ORM\JoinColumn(name="subject_id", referencedColumnName="id")
*/
private $subjects;
如您所见,我想制作此唯一实体,因此我following this guide.
此外,我已将以下内容添加到实体文件的顶部,
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
毕竟当我提交数据时,它仍然会向表中添加重复的行。例如,
如果表中存在像 class = clsA和subject = subA 这样的行,并且如果我尝试使用相同的值插入,则会插入没有验证/消息的数据“此主题已添加“
我的控制器如下所示,
public function addTeacherSubjectAction( $id, Request $request )
{
$em = $this->getDoctrine()->getManager();
$user = $em->getRepository('PIE10Bundle:Users')->find($id);
$subjects = $em->getRepository('PIE10Bundle:Subject')->findAll();
$form = $this->createForm(ClassSubjectType::class,$subjects);
$form->handleRequest($request);
if( $form->isSubmitted() && $form->isValid() )
{
$allSubjects = $form['subject']->getData();
foreach( $allSubjects as $subject )
{
$subject_repo = $em->getRepository('PIE10Bundle:Subject')->find($subject->getId());
$teacherSubject = new TeacherSubjects();
$teacherSubject->setTeachers($user);
$teacherSubject->setSubjects($subject_repo);
$em->persist($teacherSubject);
$em->flush();
}
$this->addFlash('notice',
'Subjects added');
return $this->redirectToRoute('user_teachers');
}
return $this->render( 'PIE10Bundle:Form:layout_commom_form.html.twig',
array( 'title' => 'Add Subjects',
'form' => $form->createView() )
);
}
,ClassSubjectType如下所示,
class ClassSubjectType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('subject',
EntityType::class,
array('class' => 'PIE10Bundle:Subject',
'expanded' => true,
'multiple' => true,
'attr' => array( 'class' => 'form-control',
'style' => 'margin:5px 0;')));
$builder->add('Add Classes',
SubmitType::class,
array('attr' => array('class' => 'btn btn-primary',
'style' => 'margin:15px 0;')) );
}
}
所以我需要知道我的代码有什么问题。提前谢谢。