【问题标题】:Symfony and Doctrine - displaying data from database in controller methodSymfony 和 Doctrine - 在控制器方法中显示来自数据库的数据
【发布时间】:2017-04-26 15:46:32
【问题描述】:

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

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()
        ));
    }

【问题讨论】:

  • 您只需将默认值设置为$blogs 对象
  • 例如$blogs->setTitle($data->getTitle());
  • 感谢您的帮助。效果很好。

标签: symfony doctrine


【解决方案1】:

就这么简单

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

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

【讨论】:

    猜你喜欢
    • 2013-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-05
    • 2012-07-19
    • 2018-08-18
    • 2015-01-27
    相关资源
    最近更新 更多