我有一个表单,我想填充控制器中的1个字段(fromID)(我以前用它做setFromId方法),但是我收到错误。 有我的代码:
public function newAction()
{
$entity = new PrivateMessage();
$user = $this->container->get('security.context')->getToken()->getUser();
$entity->setFromId($user);
$form = $this->createForm(new PrivateMessageType(), $entity);
$form->setData($entity);
return $this->render('AcmeStoreBundle:PrivateMessage:new.html.twig', array(
'entity' => $entity,
'form' => $form->createView(),
));
}
我错过了什么吗?
@edit:我忘了补充一点,当来自ID的字段可用时,它正在工作。但我不想让用户改变它。
这是PrivateMessage实体的一部分:
class PrivateMessage
{/ ** * @var整数 * * @ORM \ Column(name =“id”,type =“integer”) * @ORM \ Id * @ORM \ GeneratedValue(strategy =“AUTO”) * / 私人$ id;
/**
*
* @ORM\ManyToOne(targetEntity="User", inversedBy="pm_to")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="to_id", referencedColumnName="id", nullable=false)
* })
*/
private $toID;
/**
*
* @ORM\ManyToOne(targetEntity="User", inversedBy="pm_from")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="from_id", referencedColumnName="id", nullable=false)
* })
*/
private $fromID;
function __construct()
{
$this->setOpened(false);
$this->setRecipientDelete(false);
$this->setSenderDelete(false);
}
/**
* @ORM\PrePersist
*/
public function setFromIdValue()
{
$this->fromID= $this->getFromId();
}
/**
* Set fromID
*
* @param \Acme\Bundle\Entity\User $fromId
* @return PrivateMessage
*/
public function setFromId(\Acme\StoreBundle\Entity\User $fromId = null)
{
$this->fromID = $fromId;
return $this;
}
/**
* Get fromID
*
* @return \Acme\StoreBundle\Entity\User
*/
public function getFromId()
{
return $this->fromID;
}
答案 0 :(得分:0)
有一个比控制器更好的地方来设置(甚至覆盖)你的表单字段 - 事件监听器。您应该为prePersist
doctrine事件和set / update字段编写监听器。请查看文档示例:http://symfony.com/doc/current/cookbook/doctrine/event_listeners_subscribers.html#configuring-the-listener-subscriber