我有以下情况: 我的网站上有一个表单(创建用户组),用户需要输入多个组详细信息。他也应该能够下订单,这与集团本身完全无关(在数据模型的意义上)。 这是当前的代码,但仅适用于实体UserGroup。
$form = $this->createForm(new UserGroupType($this->get('session')), $entity, array(
'action' => $this->generateUrl('spf_user_group_create'),
'method' => 'POST',
));
return $form;
我如何更改此(或UserGroupType类)以支持与UserGroup无关的第二个实体?
答案 0 :(得分:1)
每个FormType只能有一个data_class。
如果您需要以相同的形式输入多个实体,则需要创建另一个实体类,它将所有需要的实体粘合在一起。
例如,如果您有一个注册激活表单,其中用户输入了User,Account和Location实体的数据,那么您将拥有一个类,如下所示:
<?php
namespace Service\Bundle\UserBundle\Entity;
class RegistrationActivation
{
/**
* @var User
*/
private $user;
/**
* @var Account
*/
private $account;
/**
* @var Location
*/
private $location;
/**
* @param User $user
* @param Account $account
* @param Location $location
*/
public function __construct(User $user, Account $account, Location $location)
{
$this->user = $user;
$this->account = $account;
$this->location = $location;
}
/**
* @return User
*/
public function getUser()
{
return $this->user;
}
/**
* @return Account
*/
public function getAccount()
{
return $this->account;
}
/**
* @return Location
*/
public function getLocation()
{
return $this->location;
}
/**
* This is a proxy method
* @param $boolean
* @return $this
*/
public function setFirstLocationDiffers($boolean)
{
$this->getLocation()->setFirstLocationDiffers($boolean);
return $this;
}
/**
* This is a proxy method
* @return bool
*/
public function getFirstLocationDiffers()
{
return $this->getLocation()->getFirstLocationDiffers();
}
/**
* @param User $user
* @return $this
*/
public function setUser(User $user) {
$this->user = $user;
return $this;
}
/**
* @param Account $account
* @return $this
*/
public function setAccount(Account $account) {
$this->account = $account;
$this->getUser()->setAccount($account);
return $this;
}
/**
* @param Location $location
* @return $this
*/
public function setLocation(Location $location) {
$this->location = $location;
$this->getUser()->addLocation($location);
$this->getAccount()->addLocation($location);
return $this;
}
}
然后在FormType中,将data_class选项设置为'Service \ Bundle \ UserBundle \ Entity \ RegistrationActivation',例如。
另一个解决方案(如果这对您的示例来说变得复杂)是使用数据变换器。
此外,通过构造函数将值传递给FormType(就像使用会话一样)并不是一个好习惯。而是将其作为选项传递给动作和方法。