以Symfony 2的形式嵌入当前用户ID

时间:2015-06-17 16:41:10

标签: php symfony symfony-forms

我正在尝试验证Symfony 2.3中的表单。我需要获取当前用户ID并在我的数据库中提交。

我的控制器:

   public function giftcardAction(Request $request)
    {
        $giftcard = new Giftcard();
        $giftcard->setDate(new \DateTime());
        $user = $this->container->get('security.context')->getToken()->getUser();
        $userId = $user->getId();

        var_dump($userId);
        $form = $this->createFormBuilder($giftcard)
            ->add('amount', 'integer')
            ->add('onBehalfOf')
            ->add('towards')
            ->add('message', 'text')
//            ->add($userId)
            ->add('submit', 'submit')
            ->getForm();

        $form->handleRequest($request);

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

        }else{
            throw new NotFoundHttpException("Page not found");
           }
        }
            return $this->render('FrontBundle:Forms:giftcard.html.twig', array(
            'form' => $form->createView(),
        ));
    }

我的FormType

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class GiftCardType extends AbstractType
{
    private $userId;

    public function __construct(array $userId)
    {
        $this->userId = $userId;
    }

    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('date')
            ->add('onBehalfOf')
            ->add('towards')
            ->add('message')
//            ->add('UserId')
        ;
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Front\Bundle\Entity\GiftCard',
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'front_bundle_giftcard';
    }
}

目前我可以在控制器的var_dump中获取用户ID。但是我如何在表单中传递变量。有没有人可以帮助我。谢谢。

0 个答案:

没有答案