使用createFormBuilder()预填充symfony2表单

时间:2014-02-23 14:18:38

标签: php symfony

这是我的表格:

$studentObj = $this->getDoctrine()->getRepository('ProjectEntityBundle:Student')
                    ->findBy(array('user' => $userId));
    $form = $this->createFormBuilder($studentObj)
            ->add('fname', 'text', array('label' => 'First Name'))
            ->add('lname', 'text', array('label' => 'Last Name'))
            ->add('save', 'submit', array('label' => 'Save My Profile'))
            ->getForm();

我从路由变量传递$ userId。但它不预先填充数据。我该如何解决这个问题?

2 个答案:

答案 0 :(得分:2)

您必须在控制器“级别”执行“预填充”。

假设您有一个editStudentController并且您的表单名为studentFormType,您将会这样做

public function editStudentController() {
  //retrieve here $userId;
  $student = $this->getDoctrine()->getRepository('ProjectEntityBundle:Student')
                                     ->findOneBy(array('user'=>$userId));
  $form = $this->createForm(new studentFormType(), $student);
  [...]
  $view = $form->createView();
  [...]
}

答案 1 :(得分:0)

也许最好的方法是为您的实体ProjectEntityBundle:Student创建一个FormType,可以帮助您完成命令

$ php app/console doctrine:create:form ProjectEntityBundle:Student

您可以在src/ProjectEntityBundle/Form/StudentType.php上查看和自定义课程,稍后您的操作可以使用;

// here you can use [ParamConvert][1] to get the correct Entity without call your repository   
public function editStudentAction(Student $student)
{
  // don't forget the 'use' statement on top
  $editForm = $this->createForm(new StudentType(), $student);

  return array('edit_form' => $editForm->createView());
}

帮助链接