2

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

树枝模板

<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 的实体作为变量,并在 twig 表单中显示为下拉框。我希望当前登录(经过身份验证的)用户的 ID 自动插入 - 如果可能的话,隐藏 - 在“用户”字段中。我知道我正在获取用户的 ID

$user = $this->get('security.context')->getToken()->getUser();
$userId = $user->getId();

但我不能让它工作。

4

1 回答 1

7

如果您想将其放入表单中,并且可以由用户编辑,则必须先在您的 Guest 对象中为用户提供集合,然后再将其注入表单:

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

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

于 2012-08-13T06:42:52.637 回答