我有表A和B(名称不重要),一对多关系,B包含A_id,我想添加一个B记录,从表单中的隐藏字段插入A_id,所以我有:
index.html.twig(A)
<a href="{{ path('B_new', { 'id': entity.id }) }}">Follow</a>
Bcontroller.php
public function newAction($id)
{
$entity = new B();
$form = $this->createCreateForm($entity, $id);
return $this->render('UjcBundle:B:new.html.twig', array(
'entity' => $entity,
'form' => $form->createView(),
));
}
但是我收到了一个错误:
Error: Uncaught TypeError: Argument 1 passed to Symfony\Component\Debug\ExceptionHandler::handle() must be an instance of Exception, instance of Error given in E:\xampInstall\htdocs\nuevo\vendor\symfony\symfony\src\Symfony\Component\Debug\ExceptionHandler.php:90
Stack trace:
#0 [internal function]: Symfony\Component\Debug\ExceptionHandler->handle(Object(Error))
#1 {main}
thrown in E:\xampInstall\htdocs\nuevo\vendor\symfony\symfony\src\Symfony\Component\Debug\ExceptionHandler.php line 90
似乎问题是createCreateForm中的$ id参数,
然后:
private function createCreateForm(B $entity, $id)
{
$form = $this->createForm(new BType($id), $entity, array(
'action' => $this->generateUrl('b_create'),
'method' => 'POST',
));
$form->add('submit', 'submit', array('label' => 'Create'));
return $form;
}
有没有更好的方法呢? createCreateForm $ id参数是问题吗?
答案 0 :(得分:0)
我不理解您的错误,但如果您需要向表单提供其他数据,我会在您的configureOptions()
方法(BType
内)中定义新的必需选项:
$resolver->setRequired('something_id');
在您的控制器中:
$form = $this->createForm(new BType($id), $entity, array(
'action' => $this->generateUrl('b_create'),
'method' => 'POST',
'something_id' => $id
));
然后在您的buildForm()
方法中,您可以通过$options
变量访问它:$options['something_id']
希望有所帮助
答案 1 :(得分:0)
你在BType中用$ id做什么?
我会这样做:从BType和createCreateForm中删除$ id。和
#BController
newAction($id){
$a = $this->getDoctrine()->getRepository('AppBundle:A')->findOneBy(['id' => $id]);
$b = new B();
$form = $this->createForm(BType::clasa, $b);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()){
$b->setA($a);
$em = $this->getDoctrine()->getManager();
$em->persist($b);
$em->flush();
}
return $this->render('...');
}