embedding current user id in a form Symfony 2

1.3k views Asked by At

I am trying to validate a form in Symfony 2.3. I need to get the current User id and submit in my database.

My controller :

   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(),
        ));
    }

My 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';
    }
}

At the moment i can get the user id in var_dump in the controller. But how I can pass the variable in the form. Has anyone may help me. Thank you.

0

There are 0 answers