Symfony2形式的未定义变量

时间:2012-05-01 08:11:49

标签: php forms symfony

我刚刚开始使用Symfony2。我决定在php中实现我的表单,而不是必须学习twig。我按照书中的说明进行操作,如下:

在控制器中:

public function editAction($id)
{
    $em = $this->getDoctrine()->getEntityManager();

    $entity = $em->getRepository('MyBundle:MyEntity')->find($id);

    if (!$entity) {
        throw $this->createNotFoundException('Unable to find MyEntity entity.');
    }

    $editForm = $this->createForm(new MyEntityType(), $entity);
    $deleteForm = $this->createDeleteForm($id);

    return $this->render('MyBundle:MyEntity:edit.html.php' array(
        'entity'      => $entity,
        'edit_form'    => $editForm->createView(),
        'delete_form'  => $deleteForm->createView()
    ));
}

并在edit.html.php中:

<form action="<?php echo $view['router']->generate('myentity_update', array('id'=>$entity->getId()))?>" method="post" <?php echo $view['form']->enctype($editForm) ?>>

   <?php echo $view['form']->widget($editForm)?>

  <p>
    <button type="submit">Save Changes</button>
  </p>
</form>
<ul class="record_actions">
<li>
    <a href="<?php $view['router']->generate('myentity') ?>">
        Back to the list
    </a>
</li>
<li>
    <form action="<?php $view['router']->generate('myentity_delete', array('id'=>$entity->getId()) ) ?>" method="post">
        <?php echo $view['form']->widget($deleteForm)?>
        <button type="submit">Delete</button>
    </form>
</li>

当我尝试显示表单时出现错误: 注意:未定义的变量editForm

据我所知,我完全按照The Book中给出的说明进行操作。我已经尝试用动作和模板中的$ form替换$ editForm或者用模板中的edit_form替换$ editForm - 不用说,这些都不起作用。

我非常感谢有关我接下来应该尝试的任何建议(或者我可能不得不让自己去学习树枝,因为至少那些说明似乎是正确的。)

1 个答案:

答案 0 :(得分:1)

您将变量作为edit_form传递给视图(数组键是要在视图中使用的变量的名称):

return $this->render('MyBundle:MyEntity:edit.html.php' array(
    'entity'      => $entity,
    'edit_form'    => $editForm->createView(),
    'delete_form'  => $deleteForm->createView()
));

但您在视图中将其引用为$editForm

<form action="<?php echo $view['router']->generate('myentity_update',
    array('id'=>$entity->getId()))?>" method="post" <?php echo $view['form']->enctype($editForm) ?>>

为两者(edit_form vs editForm)确定相同的方法,你应该做得很好。例如,'edit_form'在视图中变为$edit_form,同样'editForm'变为$editForm