使用Symfony 3.0,我有一个表单,其中包含从教义实体生成的下拉列表。当我完成表单并提交时,我可以在分析器中看到下拉值已正确传递,但我收到以下错误:知道会发生什么吗? 编辑我不想传递空值。窗体正在从实体下拉列表中传入所选值。但是插入数据库似乎没有使用它?
SQLSTATE[23000]: [Microsoft][SQL Server Native Client 11.0][SQL Server]Cannot
insert the value NULL into column 'account_type', table 'CRM.dbo.accounts';
column does not allow nulls. INSERT fails.
表格为:(账户类型.php)
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('accountTypeId', EntityType::class, array(
'class' => 'AppBundle:AccountType',
'choice_label' => 'typeName',
//'label' => 'Account Type',
))
->add('name')
->add('notes', null, array('label' => 'Long Name', 'required' => false))
->add('address')
->add('city')
->add('region')
->add('country', CountryType::class)
->add('postcode')
->add('telephone', null, array('required' => false))
->add('website', null, array('required' => false))
->add('email', null, array('required' => false))
->add('save', SubmitType::class);
}
控制者:(帐户控制者.php)
public function addAction(Request $request)
{
$account = new Account();
$form = $this->createForm(AccountType::class, $account);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
try {
// create account
//$account = $form->getData();
// save data to db
$em = $this->getDoctrine()->getManager();
$em->persist($account);
$em->flush();
// add flash message and return to profile
$this->addFlash('success', 'Account: ' . $account->getName() .' created successfully.');
return $this->redirectToRoute('accounts');
}
catch(Exception $e) {
$this->addFlash('error', $e->getMessage());
return $this->redirectToRoute('accounts');
}
}
// load form for new account
return $this->render('accounts/add.html.twig', array(
'form' => $form->createView()
));
}
帐户模型关系:
/**
* @ORM'ManyToOne(targetEntity="AccountType", inversedBy="accounts")
* @ORM'JoinColumn(name="account_type", referencedColumnName="id")
*/
private $accountTypeName;
帐户类型模型关系:
/**
* @ORM'OneToMany(targetEntity="Account", mappedBy="accountTypeName")
*/
private $accounts;
根据以下内容更新您的帐户实体:
/**
* @ORM'ManyToOne(targetEntity="AccountType", inversedBy="accounts")
* @ORM'JoinColumn(name="account_type", referencedColumnName="id", nullable=true)
*/
private $accountTypeName;
现在我觉得真的很笨!毕竟,我在帐户窗体中使用了错误的变量。我在实体中使用了帐户类型 ID。相反,我应该使用关系中的变量集:
我的表格使用:
/**
* @ORM'Column(type="integer", name="account_type")
*/
private $accountTypeId;
形式:
$builder
->add('accountTypeId', EntityType::class, array(
'class' => 'AppBundle:AccountType',
'choice_label' => 'typeName',
//'label' => 'Account Type',
))
我现在已将表单更改为:
$builder
->add('accountTypeName', EntityType::class, array(
'class' => 'AppBundle:AccountType',
'choice_label' => 'typeName',
//'label' => 'Account Type',
))
从:
/**
* @ORM'ManyToOne(targetEntity="AccountType", inversedBy="accounts")
* @ORM'JoinColumn(name="account_type", referencedColumnName="id")
*/
private $accountTypeName;
这显然有效!!