Reputation: 1844
I have a form type in symfony2 :
namespace Acme\SomethingBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
class GuestType extends AbstractType
{
public function buildForm(FormBuilder $builder, array $options)
{
$builder
->add('name')
->add('email')
->add('address')
->add('phone')
->add('created_at')
->add('updated_at')
->add('is_activated')
->add('user','entity', array('class'=>'Acme\SomethingBundle\Entity\User', 'property'=>'id' ));
}
public function getName()
{
return 'acme_somethingbundle_guesttype';
}
}
The action:
/**
* Displays a form to create a new Guest entity.
*
*/
public function newAction()
{
$entity = new Guest();
$form = $this->createForm(new GuestType(), $entity);
return $this->render('AcmeSomethingBundle:Guest:new.html.twig', array(
'entity' => $entity,
'form' => $form->createView()
));
}
/**
* Creates a new Guest entity.
*
*/
public function createAction()
{
$entity = new Guest();
$request = $this->getRequest();
$form = $this->createForm(new GuestType(), $entity);
$form->bindRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getEntityManager();
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('guest_show', array('id' => $entity->getId())));
}
return $this->render('AcmeSomethingBundleBundle:Guest:new.html.twig', array(
'entity' => $entity,
'form' => $form->createView()
));
}
Twig template
<h1>Guest creation</h1>
<form action="{{ path('guest_create') }}" method="post" {{ form_enctype(form) }}>
{{ form_widget(form) }}
<p>
<button type="submit">Create</button>
</p>
</form>
<ul class="record_actions">
<li>
<a href="{{ path('guest') }}">
Back to the list
</a>
</li>
</ul>
the 'user' property takes an entity of user Ids as a variable and in the twig form is displayed as a drop down box. I want the current logged in (authenticated) user's Id to insert automatically - and hidden If possible - in the 'user' field. I know that I am getting a user's Id with
$user = $this->get('security.context')->getToken()->getUser();
$userId = $user->getId();
but I cannot make it work.
Upvotes: 2
Views: 2045
Reputation: 7448
You have to give the set the user in your Guest object before injecting it in the form if you want to have it in the form, and editable by the user:
$entity = new Guest();
$entity->setUser($this->get('security.context')->getToken()->getUser());
$form = $this->createForm(new GuestType(), $entity);
Otherwise, if it's not editable, you should remove this field from the form and set user after the isValid
() test.
Upvotes: 7