如何使symfony2表单在表单类型中自动输入当前登录用户的ID?

时间:2012-08-13 05:30:41

标签: symfony twig

我在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';
    }
}

行动:

    /**
     * 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模板

<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>

'user'属性将用户ID的实体作为变量,并在树枝形式中显示为下拉框。我希望当前登录(已验证)用户的ID自动插入 - 如果可能,则隐藏在“用户”字段中。我知道我正在使用

获取用户的ID
$user = $this->get('security.context')->getToken()->getUser();
$userId = $user->getId();

但我不能让它发挥作用。

1 个答案:

答案 0 :(得分:7)

如果您希望将表单中的用户放入表单中,并且用户可以编辑,则必须先将该对象设置为Guest对象中的用户:

$entity  = new Guest();
$entity->setUser($this->get('security.context')->getToken()->getUser());
$form    = $this->createForm(new GuestType(), $entity);

否则,如果它不可编辑,则应从表单中删除此字段,并在isValid()测试后设置用户。