将一个ID传递给

时间:2018-02-06 19:53:47

标签: symfony symfony-forms

我有一个表单,其中我选择了学生ID和课程的ID,该课程在UserCourse实体中创建了一个复合键,并且具有该课程的状态(通过,注册等)。

我想要的是将当前登录的学生的值传递给表单,以使用当前用户ID填充userid字段,这样它只需选择课程和状态并提交。 我尝试过使用default_value和data => $ userId但失败了。

这是UserController

/**
 * @Route("/courses/{userId}/new", name="new_usercourse")
 */
public function newMylistAction(Request $request, $userId)
{
    $userCourse = new UserCourse();
    $userCourse->setUserId($userId);
    $form = $this->createForm('AppBundle\Form\UserCourseType', $userCourse);

    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $em->persist($userCourse);
        $em->flush();

        return $this->redirectToRoute('mycourses');
    }

    return $this->render('student/new_mycourses.html.twig', array(
        'usercourse' => $userCourse,
        'form' => $form->createView()
    ));
}

这是UserCourseType表单。 userId也是EntityType

namespace AppBundle\Form;
use AppBundle\Entity\Course;
use AppBundle\Entity\UserCourse;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class UserCourseType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
       $builder
           ->add('userId', null)
           ->add('courseId', EntityType::class, array(
               'class' => 'AppBundle\Entity\Course',
               'choice_label' => 'name'
           ))
           ->add('status', ChoiceType::class, array(
               'choices' => array(
                   'Passed' => 'passed',
                   'Enrolled' => 'enrolled',
                   'Null' => '',
               )))
           ->add('save', SubmitType::class, array('label' => 'Create'));

    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => UserCourse::class
        ));
    }
}

希望你能帮忙

1 个答案:

答案 0 :(得分:0)

在flush()之前设置用户ID

 if ($form->isSubmitted() && $form->isValid()) {
      $em = $this->getDoctrine()->getManager();
      $userCourseRepo=$em->getRepository('AppBundle:UserCourse');
      $userCourseIddata = $userCourseRepo->find($id);
      $userCourse->setUserId($userCourseIddata);////set userid
      $em->persist($userCourse);
      $em->flush();

            return $this->redirectToRoute('mycourses');
        }