Symfony和Doctrine - 在控制器方法中显示数据库中的数据

时间:2016-12-11 18:36:31

标签: symfony doctrine

这是我的代码。我想在表单中设置数据库的默认值。我想在我用这种方法创建的形式中设置值。

public function updateBlogAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();
        $data = $em->getRepository('AppBundle:Blog\Post')->find($id);

        $blogs = new Post();

        $form = $this->createFormBuilder($blogs)
                ->add('title', TextType::class, array('attr'=>array( 'class'=>'form-control','placeholder'=>'Blog title')))
                ->add('description', TextareaType::class, array('attr'=>array('class'=>'form-control','placeholder'=>'Blog description')))
                ->add('submit',SubmitType::class, array('label'=>'Add Blog', 'attr'=> array('class'=>'btn btn-primary pull-right')))
                ->getForm();

        $form->handleRequest($request);

        if( $form->isSubmitted() && $form->isValid() ){
            $data->setTitle($blogs);
            $em->flush();

            return $this->redirectToRoute('blog');
        }

        return $this->render('blog/update_blog.html.twig', array(
            'form'  =>  $form->createView()
        ));
    }

1 个答案:

答案 0 :(得分:0)

就像

一样简单
$em = $this->getDoctrine()->getManager();
$blogs= $em->getRepository('AppBundle:Blog\Post')->find($id);

$form = $this->createFormBuilder($blogs)
/* ... */